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

              <template v-else-if="formVal.type === 'select'">
                <el-select
                  v-model="ruleForm[key]"
                  :disabled="toBoolean(formVal.disabled)"
                  :placeholder="toBoolean(formVal.disabled) ? 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)" @[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>
              </template>

              <template v-else-if="formVal.type === 'checkbox'">
                <el-checkbox-group v-model="ruleForm[key]" :disabled="toBoolean(formVal.disabled)" @[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 === 'date'">
                <el-date-picker
                  v-model="ruleForm[key]"
                  :type="formVal.type || 'date'"
                  :disabled="toBoolean(formVal.disabled)"
                  :placeholder="toBoolean(formVal.disabled) ? 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 === 'month'">
                <el-date-picker
                  v-model="ruleForm[key]"
                  :type="formVal.type || 'date'"
                  :disabled="toBoolean(formVal.disabled)"
                  :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="formVal.type || 'date'"
                  :disabled="toBoolean(formVal.disabled)"
                  :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="formVal.type || 'date'"
                  :disabled="toBoolean(formVal.disabled)"
                  :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)"
                  :placeholder="toBoolean(formVal.disabled) ? formVal.placeholder || `请输入${formVal.label}` : null"
                  @[formVal.eventName]="(val) => handleChange(key,val,formVal)"
                ></el-transfer>
              </template>

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

<script setup>
  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
      }
    },
    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;
      }
    }
  }
</script>

<style scoped lang="scss">
  ::v-deep .cursorAuto input {
    cursor: auto!important;
  }
  ::v-deep .cursorAuto textarea {
    cursor: auto!important;
  }
</style>

