<template>
  <mu-form-item :label="currentConfig.label" :prop="currentConfig.key" :inline="currentConfig.inline"
                :tip="currentConfig.tip" :validators="currentConfig.validators" trigger="change">
    <el-switch class="mu-switch" :class="'mu-'+ currentConfig.size"
               v-model="currentValue"
               :active-text="currentConfig.isTextable ? (currentValue ? currentConfig.onText : currentConfig.offText) : ''"
               @change="handleChange"></el-switch>
  </mu-form-item>
</template>

<script lang="ts">
  import { Component, Prop, Vue, Watch, Emit } from 'vue-property-decorator';
  // import { DtFormItem } from "src/components/Form";

  type Size = 'small' | 'medium' | 'large';

  interface InputConfig {
    name: string,
    size?: Size,
    disabled?: boolean,
    label?: string,
    key?: string,
    inline?: boolean,
    tip?: string,
    isTextable?: boolean,
    onText?: string,
    offText?: string,
    validators?: any
  }

  @Component({
    name: 'mcSwitch',
    components: {
      // DtFormItem
    }
  })
  export default class extends Vue {
    @Prop({ default: () => [] }) private value!: string | undefined;
    @Prop({ default: () => [] }) private config!: InputConfig;
    private currentValue: string = this.value;
    private defaultConfig: any = {
      size: 'medium',
      isTextable: true,
      onText: "on",
      offText: "off"
    };

    // 合并默认数据
    get currentConfig() {
      const result = this.config;
      Object.keys(this.defaultConfig).forEach((key: string) => {
        if (this.config[key] === undefined) result[key] = this.defaultConfig[key];
      });
      return result;
    }

    /**
     * 输入框值改变
     * @author JieShuai
     * @param value 值
     */
    @Emit('on-change')
    handleChange(value: string) {
      this.$emit('input', value);
    }
  }
</script>
