<template>
    <div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :label-width="config && config.labelWidth || '130px'" :key="config && config.key" class="demo-ruleForm">
        <template v-for="(formItem,index) of formList">
          <h4 v-if="formItem && formItem.config && formItem.config.title" class="form-header h4">{{formItem.config.title}}</h4>
          <el-row>
            <el-col v-for="(formVal,key,index) of formItem['controls']" :span="formVal.span" v-if="!formVal.hidden" :class="formItem.config.colSpan" :style="formVal.style">
              <el-form-item
                :key="config && config.key ? `${config && config.key}-${key}` : `${key}`"
                :prop="key"
                :required="formVal.required">
                <template #label>
                  <span :title="formVal.label">{{formVal.label ? formVal.label + '：' : ''}}</span>
                </template>
                <template v-if="formVal.type === 'input'">
                  <el-input
                    v-model="ruleForm[key]"
                    :clearable="formVal.clearable !== false"
                    :disabled="toBoolean(formVal.disabled || formItem.config.readonly)"
                    :placeholder="toBoolean(formVal.disabled || formItem.config.readonly) ? null : formVal.placeholder || `请输入${formVal.label}`"
                    :class="toBoolean(formVal.disabled || formItem.config.readonly) ? 'cursorAuto' : ''"
                    @[formVal.eventName]="(val) => handleChange(key,val,formVal)"></el-input>
                </template>
                <template v-if="formVal.type === 'textarea'">
                  <el-input
                    v-model="ruleForm[key]"
                    :disabled="toBoolean(formVal.disabled || formItem.config.readonly)"
                    type="textarea"
                    :rows="formVal.rows"
                    :clearable="formVal.clearable !== false"
                    :class="toBoolean(formVal.disabled || formItem.config.readonly) ? 'cursorAuto' : ''"
                    :placeholder="toBoolean(formVal.disabled || formItem.config.readonly) ? null : formVal.placeholder || `请输入${formVal.label}`"></el-input>
                </template>

                <template v-else-if="formVal.type === 'select'">
                  <el-select
                    v-model="ruleForm[key]"
                    :multiple="formVal.multiple"
                    :collapse-tags="formVal.collapseTags"
                    :disabled="toBoolean(formVal.disabled || formItem.config.readonly)"
                    :placeholder="toBoolean(formVal.disabled || formItem.config.readonly) ? null : formVal.placeholder || `请输入${formVal.label}`"
                    :clearable="formVal.clearable !== false"
                    @[formVal.eventName]="(val) => handleChange(key,val,formVal)">
                    <el-option
                      v-for="option in formVal.options"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"></el-option>
                  </el-select>
                </template>

                <template v-else-if="formVal.type === 'radio'">
                  <el-radio-group v-model="ruleForm[key]" :disabled="toBoolean(formVal.disabled || formItem.config.readonly)" @[formVal.eventName]="(val) => handleChange(key,val,formVal)">
                    <el-radio
                      v-for="option in formVal.options"
                      :key="option.value"
                      :label="option.value">
                      {{ option.label }}
                    </el-radio>
                  </el-radio-group>
                  <br/><span class="warningCol">{{formVal.warningTitle}}</span>
                </template>

                <template v-else-if="formVal.type === 'checkbox'">
                  <el-checkbox-group v-model="ruleForm[key]" :disabled="toBoolean(formVal.disabled || formItem.config.readonly)" @[formVal.eventName]="(val) => handleChange(key,val,formVal)">
                    <el-checkbox
                      v-for="option in formVal.options"
                      :key="option.value"
                      :label="option.value">
                      {{ option.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </template>

                <template v-else-if="formVal.type === 'time'">
                  <el-time-picker
                    v-model="ruleForm[key]"
                    :disabled="toBoolean(formVal.disabled || formItem.config.readonly)"
                    :placeholder="toBoolean(formVal.disabled || formItem.config.readonly) ? null : formVal.placeholder || `请输入${formVal.label}`"
                    @[formVal.eventName]="(val) => handleChange(key,val,formVal)"
                  ></el-time-picker>
                </template>

                <template v-else-if="formVal.type === 'date'">
                  <el-date-picker
                    v-model="ruleForm[key]"
                    type="date"
                    :disabled="toBoolean(formVal.disabled || formItem.config.readonly)"
                    :placeholder="toBoolean(formVal.disabled || formItem.config.readonly) ? null : formVal.placeholder || `请输入${formVal.label}`"
                    :format="formVal.format || 'yyyy-MM-dd'"
                    @[formVal.eventName]="(val) => handleChange(key,val,formVal)"
                  ></el-date-picker>
                </template>

                <template v-else-if="formVal.type === 'datetime'">
                  <el-date-picker
                    v-model="ruleForm[key]"
                    type="datetime"
                    :disabled="toBoolean(formVal.disabled || formItem.config.readonly)"
                    :placeholder="toBoolean(formVal.disabled || formItem.config.readonly) ? null : formVal.placeholder || `请输入${formVal.label}`"
                    :format="formVal.format || 'yyyy-MM-dd HH:mm:ss'"
                    :value-format="formVal.valueFormat || 'yyyy-MM-dd HH:mm:ss'"
                    @[formVal.eventName]="(val) => handleChange(key,val,formVal)"
                  ></el-date-picker>
                </template>

                <template v-else-if="formVal.type === 'month'">
                  <el-date-picker
                    v-model="ruleForm[key]"
                    type="month"
                    :disabled="toBoolean(formVal.disabled || formItem.config.readonly)"
                    :format="formVal.format || 'yyyy-MM'"
                    :value-format="formVal.valueFormat || 'yyyy-MM'"
                    @[formVal.eventName]="(val) => handleChange(key,val,formVal)"
                  ></el-date-picker>
                </template>

                <template v-else-if="formVal.type === 'daterange'">
                  <el-date-picker
                    v-model="ruleForm[key]"
                    type="daterange"
                    :disabled="toBoolean(formVal.disabled || formItem.config.readonly)"
                    :format="formVal.format || 'yyyy-MM-dd'"
                    :value-format="formVal.valueFormat || 'yyyy-MM-dd'"
                    :range-separator="formVal.separator || '至'"
                    :start-placeholder="formVal.start || '开始日期'"
                    :end-placeholder="formVal.end || '结束日期'"
                    @[formVal.eventName]="(val) => handleChange(key,val,formVal)"
                  ></el-date-picker>
                </template>

                <template v-else-if="formVal.type === 'monthrange'">
                  <el-date-picker v-model="ruleForm[key]"
                    type="monthrange"
                    :disabled="toBoolean(formVal.disabled || formItem.config.readonly)"
                    :format="formVal.format || 'yyyy-MM'"
                    :value-format="formVal.valueFormat || 'yyyy-MM'"
                    :range-separator="formVal.separator || '至'"
                    :start-placeholder="formVal.start || '开始日期'"
                    :end-placeholder="formVal.end || '结束日期'"
                    @[formVal.eventName]="(val) => handleChange(key,val,formVal)"
                  ></el-date-picker>
                </template>

                <template v-else-if="formVal.type === 'transfer'">
                  <el-transfer
                    v-model="ruleForm[key]"
                    :data="formVal.options"
                    :disabled="toBoolean(formVal.disabled || formItem.config.readonly)"
                    :placeholder="toBoolean(formVal.disabled || formItem.config.readonly) ? formVal.placeholder || `请输入${formVal.label}` : null"
                    @[formVal.eventName]="(val,option) => handleChange(key,val,option)"
                  ></el-transfer>
                </template>

                <!-- 自定义插槽，用于特殊类型的表单控件 -->
                <template v-else-if="formVal.slotName">
                  <slot :name="formVal.slotName" :field="formVal"></slot>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 表单操作按钮 -->
          <el-row v-if="config && config['buttonGroup'] || !config['buttonGroup']" style="float: right;">
            <template v-if="config['buttonGroup'] && config['buttonGroup'].length > 0">
              <el-form-item>
                <el-button v-for="item of config['buttonGroup']" :type="item.type" @click="fnEventChange(item)">{{item.title}}</el-button>
              </el-form-item>
            </template>
            <template v-else-if="!config['buttonGroup'] || config['buttonGroup'] && config['buttonGroup'].length !== 0">
              <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="handleReset">返回</el-button>
              </el-form-item>
            </template>
          </el-row>
        </template>
      </el-form>
    </div>
</template>

<script>
  export default {
    name: 'Form',
    props: {
      formList: {
        type: Array,
        default: () => []
      },
      ruleFormData: {
        type: Object,
        default: () => ({})
      },
      config: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        rules: {},
        ruleForm: {}
        // formList: [
        //   {porp: 'name', label: '姓名', span: 24, type: 'input',rules: {required: true, message: '请输入活动名称', trigger: 'blur'}},
        //   {porp: 'age', label: '下拉', span: 24, type: 'select',options:[{value: '1', label: '10'},{value: '2', label: '20'}]},
        // ],
      };
    },
    watch: {
      ruleFormData: {
        handler(val) {
          this.initFormData();
        },
        deep: true,
        immediate: true
      },
      // formList: {
      //   handler(val) {
      //     this.initFormData();
      //   },
      //   deep: true,
      //   immediate: true
      // }
    },
    methods: {
      // 初始化表单数据
      initFormData() {
        let newFormValue = Object.assign({}, this.ruleForm, this.ruleFormData);
        this.ruleForm = {...newFormValue};
        // 筛选出需要校验的属性
        this.formList.forEach(item => {
          Object.keys(item.controls).forEach(val => {
            item.controls[val]['eventName'] = item.controls[val] && item.controls[val]['eventName'] || null;
            if (item.controls[val] && item.controls[val]['rules']) {
              this.rules[val] = item.controls[val]['rules'];
            } else if (item.controls[val] && item.controls[val].required) {
              let msgType = item.controls[val].type === 'input' ? '请输入' : '请选择';
              this.rules[val] = [{required: true,message: `${msgType}${item.controls[val].label}`}];
            }
          });
        });
      },
      submitForm() {
        let forList = {...this.ruleForm};
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.formList.forEach(val => {
              Object.keys(val.controls).forEach(item => {
                if (item !== 'id' && val.controls[item] && val.controls[item]['hidden']) {
                  forList[item] = null;
                } else {
                  forList[item] = forList[item] ? forList[item] : null;
                }
              });
            });
            this.$emit('fnClick', {fnCode: 'submit'}, {...forList});
          } else {
            return false;
          }
        });
      },
      // 返回
      handleReset() {
        this.$refs.ruleForm.resetFields();
        this.$emit("fnClick", {fnCode: 'cancle'});
      },
      //  change事件
      handleChange(key, val, formVal) {
        this.$emit("fnClick", {fnCode: key}, val,formVal);
      },
      toBoolean(bool) {
        if (bool === true || bool === 'true') {
          return true;
        }
        return false;
      },
      fnEventChange(result){
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'goBack':
              this.handleReset();
              break;
            default:
          }
        }
      },
    }
  }
</script>

<style scoped lang="scss">
  ::v-deep .cursorAuto input {
    cursor: auto!important;
  }
  ::v-deep .cursorAuto textarea {
    cursor: auto!important;
  }
  ::v-deep .el-form-item__label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .warningCol {
    color: #ED7B2F;
  }
</style>

