<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" style="color: #000;" class="form-header h4">{{formItem.config.title}}</h4>
          <el-row style="color: #606266;">
            <el-col v-for="(formVal,key,index) of formItem['controls']" :span="formVal.span" v-if="!formVal.hidden" :class="formItem.config.colSpan" :style="formVal.style" style="vertical-align: top;">
              <template v-if="formVal.type === 'button'">
                <el-button :type="formVal.btnType || 'primary'" size="mini" class="ml10" @click="(val) => handleChange(key,val,formVal)">{{formVal.label}}</el-button>
              </template>
              <el-form-item
                v-else
                :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>
                  <br/><span v-if="!toBoolean(formVal.disabled || formItem.config.readonly)" class="warningCol">{{formVal.warningTitle}}</span>
                </template>

                <template v-if="formVal.type === 'textarea'">
                  <div v-if="toBoolean(formVal.disabled || formItem.config.readonly)">
                    <div style="color: #606266;font-weight: 700;padding-left: 15px;" v-html="ruleForm[key]"></div>
                  </div>
                  <template v-else>
                    <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>
                    <br/><span v-if="!toBoolean(formVal.disabled || formItem.config.readonly)" class="warningCol">{{formVal.warningTitle}}</span>
                  </template>
                </template>

                <template v-else-if="formVal.type === 'select'">
                  <el-select
                    v-model="ruleForm[key]"
                    :multiple="formVal.multiple"
                    :multiple-limit="formVal.multipleLimit || 0"
                    :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 === 'treeSelect'">
                  <Treeselect
                    v-model="ruleForm[key]"
                    :multiple="formVal.multiple"
                    :searchable="formVal.searchable"
                    :options="formVal.options"
                    :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)">
                  </Treeselect>
                </template>

                <template v-else-if="formVal.type === 'cascader'">
                  <el-cascader
                    v-model="ruleForm[key]"
                    class="w100"
                    :ref="(el) => { if (el) this.cascaderRefs[key] = el; }"
                    :props="{ multiple: true}"
                    :options="formVal.options"
                    :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-cascader>
                </template>

                <template v-else-if="formVal.type === 'radio'">
                  <template v-if="toBoolean(formVal.disabled || formItem.config.readonly)">
                    <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>
                    <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>
                  </template>
                  <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]"
                    :class="toBoolean(formVal.disabled || formItem.config.readonly) ? 'timeSty' : null"
                    :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]"
                    :class="toBoolean(formVal.disabled || formItem.config.readonly) ? 'timeSty' : null"
                    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'"
                    :value-format="formVal.valueFormat || '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]"
                    :class="toBoolean(formVal.disabled || formItem.config.readonly) ? 'timeSty' : null"
                    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]"
                    :class="toBoolean(formVal.disabled || formItem.config.readonly) ? 'timeSty' : null"
                    type="month"
                    :disabled="toBoolean(formVal.disabled || formItem.config.readonly)"
                    :placeholder="toBoolean(formVal.disabled || formItem.config.readonly) ? null : formVal.placeholder || `请选择${formVal.label}`"
                    :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]"
                    :class="toBoolean(formVal.disabled || formItem.config.readonly) ? 'timeSty' : null"
                    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]"
                    :class="toBoolean(formVal.disabled || formItem.config.readonly) ? 'timeSty' : null"
                    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 === 'datetimerange'">
                  <el-date-picker
                    v-model="ruleForm[key]"
                    :class="toBoolean(formVal.disabled || formItem.config.readonly) ? 'timeSty' : null"
                    type="datetimerange"
                    :disabled="toBoolean(formVal.disabled || formItem.config.readonly)"
                    :format="formVal.format || 'yyyy-MM-dd HH:mm:ss'"
                    :value-format="formVal.valueFormat || 'yyyy-MM-dd HH:mm:ss'"
                    :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>
        </template>
        <!-- 表单操作按钮 -->
        <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('submit')">提交</el-button>
              <el-button @click="handleReset">返回</el-button>
            </el-form-item>
          </template>
        </el-row>
      </el-form>
    </div>
</template>

<script>
  import Treeselect from "@riophae/vue-treeselect"
  import "@riophae/vue-treeselect/dist/vue-treeselect.css"
  export default {
    name: 'Form',
    components: {Treeselect},
    props: {
      formList: {
        type: Array,
        default: () => []
      },
      ruleFormData: {
        type: Object,
        default: () => ({})
      },
      config: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        rules: {},
        ruleForm: {},
        cascaderRefs: {},
        // 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 (this.toBoolean(item.config.readonly || item.controls[val].disabled)) {
              item.controls[val]['required'] = false;
            }
            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(fnCodeName) {
        let forList = {...this.ruleForm};
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.formList.forEach(val => {
              Object.keys(val.controls).forEach(item => {
                // if (val.controls[item].type === 'cascader') {
                //   // 获取当前 cascader 的实例
                //   const cascaderInstance = this.cascaderRefs[item];
                //   console.log('cascaderInstance===',cascaderInstance);
                //   if (cascaderInstance) {
                //     // 调用 getCheckedNodes，获取选中节点（支持多选，返回数组）
                //     const checkedNodes = cascaderInstance.getCheckedNodes();
                //     console.log('checkedNodes===',checkedNodes);
                //     // // 处理节点信息：例如提取 age、label、value 等（根据你的需求）
                //     // const cascaderData = checkedNodes.map(node => ({
                //     //   value: node.value,
                //     //   label: node.label,
                //     //   age: node.age, // 你的自定义属性（如之前提到的 age）
                //     //   path: node.path // 节点完整路径
                //     // }));
                //     // // 将处理后的节点信息存入提交数据 forList（键可自定义，如 `${key}Detail`）
                //     // forList[`${key}Detail`] = cascaderData;
                //   }
                // }
                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: fnCodeName}, {...forList});
          } else {
            return false;
          }
        });
      },
      // 返回
      handleReset() {
        this.$refs.ruleForm.resetFields();
        this.$emit("fnClick", {fnCode: 'cancel'});
      },
      //  change事件
      handleChange(key, val, formVal) {
        // // 仅针对 switchType 和 snmpVersion 这两个触发字段显示/隐藏的切换
        // if (key === 'switchType' || key === 'snmpVersion') {
        //   // 获取当前焦点元素
        //   const activeEl = document.activeElement;
        //   // 检查焦点元素是否在 Form 组件内的输入框/选择器中
        //   const isFormControl = activeEl.closest('.el-input') || activeEl.closest('.el-select') || activeEl.closest('.el-radio');
        //   if (isFormControl) {
        //     // 找到 Form 组件内的“返回”按钮，将焦点转移过去（或其他可见按钮）
        //     const resetBtn = this.$el.querySelector('.el-button:not(.el-button--primary)'); // 匹配“返回”按钮
        //     resetBtn?.focus();
        //   }
        // }
        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:
             this.submitForm(result.fnCode);
          }
        }
      },
    }
  }
</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 {
    color: #C0C4CC;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .warningCol {
    color: #ED7B2F;
  }
  ::v-deep .timeSty .el-input__inner{
    padding-left: 15px!important;
  }
  ::v-deep .vue-treeselect__multi-value{
    line-height: 25px!important;
  }
</style>

