<template>
  <div>
    <el-form
      ref="generateForm"
      label-suffix=":"
      :size="data.config.size"
      :model="models"
      :rules="rules"
      :label-position="data.config.labelPosition"
      :label-width="150 + 'px'"
    >
      <template v-for="item in templateData">
        <template v-if="item.type == 'grid'">
          <el-row
            :key="item.key"
            type="flex"
            :gutter="item.options.gutter ? item.options.gutter : 0"
            :justify="item.options.justify"
            :align="item.options.align"
          >
            <el-col
              v-for="(col, colIndex) in item.columns"
              :key="colIndex"
              :span="col.span"
            >
              <template v-for="citem in col.list">
                <el-form-item
                  v-if="citem.type == 'blank'"
                  :key="citem.key"
                  :label="citem.name"
                  :prop="citem.model"
                >
                  <slot :name="citem.model" :model="models" />
                </el-form-item>
                <genetate-form-item
                  v-else
                  :key="citem.key"
                  :preview="preview"
                  :models.sync="models"
                  :organ-list="itemOrganList"
                  :remote="remote"
                  :widget="citem"
                  :data="data"
                  :prop-value="citem.model"
                />
              </template>
            </el-col>
          </el-row>
        </template>

        <template v-else-if="item.type == 'blank'">
          <el-form-item :key="item.key" :label="item.name" :prop="item.model">
            <slot :name="item.model" :model="models" />
          </el-form-item>
        </template>
        <!-- 子表单 -->
        <template v-else-if="item.type === 'subform' && !item.hidden">
          <!-- <span :key="item.key">{{ item.type }}{{ item.hidden }}---</span> -->
          <el-form-item
            :key="item.key"
            :label-width="!item.options.labelWidthStatus ? '0px' : 150 + 'px'"
            :label="!item.options.labelWidthStatus ? '' : item.name"
          >
            <el-table
              :data="models[item.model]"
              border
              style="width: 100%"
              :header-cell-style="{ padding: '5px 0' }"
              size="mini"
              :class="!preview ? 'table-subform' : ''"
            >
              <el-table-column v-if="!preview" fixed width="50">
                <template slot="header">
                  <i
                    style="font-size: 25px; color: #409eff; cursor: pointer"
                    class="el-icon-circle-plus"
                    @click="addSubformCol(item)"
                  />
                </template>
                <template slot-scope="scope">
                  <i
                    style="font-size: 25px; color: red"
                    class="el-icon-remove"
                    v-if="models[item.model].length > 1"
                    @click="delSubformCol(item, scope.$index)"
                  />
                </template>
              </el-table-column>
              <template v-for="(c, i) in item.columns">
                <div :key="i">
                  <el-table-column
                    v-for="v in c.list"
                    :key="v.key"
                    :prop="v.model"
                    :label="v.name"
                    min-width="250"
                  >
                    <template slot-scope="scope">
                      <genetate-form-item
                        :prop-value="
                          item.model + '.' + scope.$index + '.' + v.model
                        "
                        :parent-form="item.model + scope.$index"
                        :preview="preview"
                        :models.sync="models"
                        :widget="v"
                        :remote="remote"
                        :data="data"
                        :disabled="disabled"
                        :fileCheck="!!fileCheckList[item.model]"
                        :is-label="false"
                        :organ-list="itemOrganList"
                        :cooperation-list="cooperationList"
                        :subform-index="scope.$index"
                        :subform-model="item.model"
                        @relationFormChange="formChange"
                        @fileCheckRequired="fileCheckRequired"
                      />
                    </template>
                  </el-table-column>
                </div>
              </template>
            </el-table>
          </el-form-item>
        </template>

        <template v-else>
          <genetate-form-item
            :key="item.key"
            :prop-value="item.model"
            :preview="preview"
            :models.sync="models"
            :widget="item"
            :remote="remote"
            :data="data"
            :organ-list="itemOrganList"
            :disabled="disabled"
            @relationFormChange="formChange"
            @fileCheckRequired="fileCheckRequired"
          />
        </template>
      </template>
    </el-form>
  </div>
</template>

<script>
import GenetateFormItem from "./GenerateFormItem";
import { getOrganCooperation } from "@/api/process/work-order";
export default {
  name: "FmGenerateForm",
  components: {
    GenetateFormItem,
  },
  /* eslint-disable */
  props: [
    "data",
    "remote",
    "value",
    "insite",
    "disabled",
    "preview",
    "organList",
  ],
  data() {
    return {
      fileCheck: false,
      templateData: [], // 临时对象
      formStatus: false,
      formRelationList: [], // 表单中所在关联的表单
      fileCheckList: {},
      tableData: [],
      models: {},
      originRules: {}, // 原始规则
      rules: {},
      subformFields: {},
      itemOrganList: [],
      selectOrganId: [],
      cooperationList: [], // 合作单位列表
    };
  },
  watch: {
    data: {
      deep: true,
      handler(val) {
        this.generateModle(val.list);
      },
    },
    value: {
      deep: true,
      handler(val) {
        this.models = { ...this.models, ...val };
      },
    },
    fileCheck: {
      deep: true,
      handler(val) {
        // // 监听是否必填
        // if(val) {
        //   this.changeFormRulesRequired();
        // } else {
        //   this.rules = JSON.parse(JSON.stringify(this.rules));
        // }
      },
    },
  },
  created() {
    this.itemOrganList = this.organList;
    this.templateData = JSON.parse(JSON.stringify(this.data.list));
    this.generateModle(this.templateData);
    // 选项关联不支付子表单
    if (!this.preview) {
      let tempData = this.templateData;
      let hiddenFormList = this.getSelectValueObject(tempData);
      this.formStatus = hiddenFormList;
      this.relationFormChange();
      // 如果不是预览时，则默认给子表单添加一行数据
      tempData.forEach(async (item) => {
        if (item.type === "subform") {
          await this.addSubformCol(item);
        }
      });
    } else {
      let tempData = this.templateData;
      let hiddenFormList = this.getSelectValueObject(tempData);
      this.formStatus = hiddenFormList;
      // let ids = this.getSelectValueObject(tempData, true);
      this.relationFormChange();

      // const values = this.models[ids.model];
      // let relationArray = [];
      // ids.options &&
      //   ids.options.options.forEach((item) => {
      //     if (values == item.value) {
      //       let tempRelation = item.relationOptions || [];
      //       relationArray.push(...tempRelation);
      //     }
      //   });
      // if (relationArray.length > 0) {
      //   this.relationFormChange(relationArray);
      // }
    }

    this.originRules = JSON.parse(JSON.stringify(this.rules));
  },
  methods: {
    changeFormRulesRequired() {
      const rules = this.rules || [];
      for (let rule in rules) {
        // 判断是否是子表单
        if (rule.indexOf("subform") >= 0 && rule) {
          // 子表单有多个
          rules[rule].forEach((subItem) => {
            for (let sub in subItem) {
              subItem[sub].forEach((last) => {
                last["required"] = false;
              });
            }
          });
        }
      }
      this.rules = rules;
      this.$forceUpdate();
    },
    addSubformCol(item) {
      var subformFields = {};
      for (var c of item.columns) {
        for (var l of c.list) {
          if (l.options !== null && l.options !== undefined) {
            subformFields[l.model] =
              l.options.defaultValue !== undefined &&
              l.options.defaultValue !== null
                ? l.options.defaultValue
                : "";
          } else {
            subformFields[l.model] = "";
          }

          if (this.rules[item.model] === undefined) {
            this.rules[item.model] = [];
          }
          if (
            this.rules[item.model][this.models[item.model].length] === undefined
          ) {
            this.rules[item.model][this.models[item.model].length] = {};
          }
          this.rules[item.model][this.models[item.model].length][l.model] = [
            ...l.rules.map((item) => {
              if (item.pattern) {
                return { ...item, pattern: eval(item.pattern) };
              } else {
                if (this.fileCheck) {
                  item.required = false;
                }
                return { ...item };
              }
            }),
          ];
        }
      }
      this.originRules = JSON.parse(JSON.stringify(this.rules));
      // if(this.fileCheck) {
      //   this.changeFormRulesRequired()
      // }
      this.models[item.model].push(subformFields);
      this.models.status = 1;
    },
    getSelectValueObject(tpls, relationStatus) {
      let tempList = tpls || [];
      let status = false;
      let relationId = "";
      const relationList = []; // 关联的表单
      tempList.forEach((list) => {
        if (list.type == "select" && list.options.relationStatus) {
          status = true;
          relationId = list;
          const relations = list.options.options || [];
          relations.forEach((item) => {
            if (item.relationOptions && item.relationOptions.length > 0) {
              relationList.push(...item.relationOptions);
            }
          });
        }
      });
      this.formRelationList = relationList.filter(function (item, index) {
        return relationList.indexOf(item) === index; // 因为indexOf 只能查找到第一个
      });
      return relationStatus ? relationId : status;
    },
    // 处理是否需要校验
    fileCheckRequired(state) {
      this.fileCheck = state;
    },
    relationFormChange(value) {
      // false 为显示，true 为隐藏
      let temp = value || [];
      let tempData = JSON.parse(JSON.stringify(this.templateData));

      tempData.forEach((item) => {
        if (this.formStatus) {
          //   判断表单是否在关联列表里，如果在则隐藏
          if (this.formRelationList.includes(item.model)) {
            item.hidden = true;
            this.fileCheckList[item.model] =
              item.type == "subform" ? true : false;
          }
          //   判断是否是文本类型，一直默认显示
          if (item.type == "text") {
            item.hidden = false;
          }
        } else {
          item.hidden = false;
        }
      });
      this.templateData = tempData;
      this.$forceUpdate();
    },
    async formInit(options) {
      const _this = this;
      options = options || [];
      await new Promise(function (resolve) {
        let tempData = JSON.parse(JSON.stringify(_this.templateData));
        tempData.forEach((item) => {
          if (_this.formStatus) {
            if (options.includes(item.model)) {
              item.hidden = true;
              // 判断下拉选择框是否设置了关联
              if (item.type == "select" && item.options.relationStatus) {
                const selectOptions = item.options.options || [];
                const relationOptions = [];
                selectOptions.forEach((option) => {
                  relationOptions.push(...option.relationOptions);
                });
                // 遍历子结点表单状态
                _this.formChange([], relationOptions);
                // return false;
              }
            }
          } else {
            item.hidden = false;
          }
          if (item.type == "subform") {
            _this.fileCheckList[item.model] = item.hidden ? true : false;
          }
        });
        _this.templateData = tempData;
        _this.$forceUpdate();
        resolve();
      });
    },
    async formChange(value, options) {
      // new Promise(function(resolve, reject) {)
      console.log(value, options);
      await this.formInit(options);
      let tempData = JSON.parse(JSON.stringify(this.templateData));
      tempData.forEach(async (item) => {
        if (this.formStatus) {
          if (value.includes(item.model)) {
            item.hidden = false;
          }
        } else {
          item.hidden = false;
        }
        // this.fileCheckList[item.model] = item.type == "subform" ? true : false;
        if (item.type == "subform") {
          this.fileCheckList[item.model] = item.hidden ? true : false;
        }
      });
      this.templateData = tempData;
      this.$forceUpdate();
    },
    relationFormChange() {
      let tempData = JSON.parse(JSON.stringify(this.templateData));
      tempData.forEach((item) => {
        if (this.formStatus) {
          //   判断表单是否在关联列表里，如果在则隐藏
          if (this.formRelationList.includes(item.model)) {
            item.hidden = true;
            this.fileCheckList[item.model] =
              item.type == "subform" ? true : false;
          }
          //   判断是否是文本类型，一直默认显示
          if (item.type == "text") {
            item.hidden = false;
          }
        } else {
          item.hidden = false;
        }
      });
      this.templateData = tempData;
      this.$forceUpdate();
    },
    delSubformCol(item, index) {
      this.models[item.model].splice(index, 1);
      this.models.status = -1;
    },
    generateModle(genList) {
      for (let i = 0; i < genList.length; i++) {
        if (genList[i].type === "grid") {
          genList[i].columns.forEach((item) => {
            this.generateModle(item.list);
          });
        } else {
          if (
            this.value &&
            Object.keys(this.value).indexOf(genList[i].model) >= 0
          ) {
            this.models[genList[i].model] = this.value[genList[i].model];
          } else {
            if (genList[i].type === "blank") {
              this.$set(
                this.models,
                genList[i].model,
                genList[i].options.defaultType === "String"
                  ? ""
                  : genList[i].options.defaultType === "Object"
                  ? {}
                  : []
              );
            }
            if (genList[i].type === "subform") {
              this.$set(this.models, genList[i].model, []);
            } else {
              this.models[genList[i].model] = genList[i].options.defaultValue;
            }
          }

          if (!this.preview) {
            if (this.rules[genList[i].model]) {
              this.rules[genList[i].model] = [
                ...this.rules[genList[i].model],
                ...genList[i].rules.map((item) => {
                  if (item.pattern) {
                    return { ...item, pattern: eval(item.pattern) };
                  } else {
                    return { ...item };
                  }
                }),
              ];
            } else {
              this.rules[genList[i].model] = [
                ...genList[i].rules.map((item) => {
                  if (item.pattern) {
                    return { ...item, pattern: eval(item.pattern) };
                  } else {
                    return { ...item };
                  }
                }),
              ];
            }
          }
        }
      }
    },
    getData() {
      return new Promise((resolve, reject) => {
        this.$refs.generateForm.validate((valid) => {
          if (valid) {
            resolve(this.models);
          } else {
            reject(new Error("表单数据校验失败").message);
          }
        });
      });
    },
    reset() {
      this.$refs.generateForm.resetFields();
    },
    async onInputChange(value) {
      if (!value || this.selectOrganId.includes(value)) {
        return;
      }
      let res = await getOrganCooperation({ organId: value });
      this.cooperationList.push(...res.data);
    },
  },
};
</script>

<style lang="scss">
.table-subform td .cell {
  padding-top: 10px;
  padding-bottom: 15px;
}
</style>