<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>公共信息</span>
      </div>
      <div class="text item">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="150px"
        >
          <el-form-item
            label="优先级:"
            prop="priority"
            style="margin-bottom: 0"
          >
            <el-radio-group v-model="ruleForm.priority" size="small">
              <el-radio :label="1">一般</el-radio>
              <el-radio :label="2">紧急</el-radio>
              <el-radio :label="3">非常紧急</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="申请部门:"
            prop="deptId"
            style="margin-bottom: 0"
          >
            <el-select v-model="ruleForm.deptId" size="small" clearable>
              <el-option
                v-for="(item, index) in deptList"
                :label="item.deptName"
                :value="item.deptId"
                :key="index"
              ></el-option>
            </el-select>
            <span v-if="!socialId && currentNode.id">(未设置社保部门)</span>
            <span v-if="ruleForm.deptId && socialId != ruleForm.deptId"
              >(该部门非社保部门)</span
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="box-card" style="margin-top: 10px">
      <div slot="header" class="clearfix">
        <span>表单信息</span>
      </div>
      <div class="text item">
        <template v-for="(tplItem, tplIndex) in processStructureValue.tpls">
          <fm-generate-form
            v-show="
              currentNode.hideTpls === undefined ||
              currentNode.hideTpls === null ||
              currentNode.hideTpls.indexOf(tplItem.id) === -1
            "
            :key="tplIndex"
            :ref="'generateForm-' + tplItem.id"
            :preview="
              currentNode.hideTpls === undefined ||
              currentNode.hideTpls === null ||
              currentNode.hideTpls.indexOf(tplItem.id) === -1
                ? false
                : true
            "
            :remote="remoteFunc"
            :data="tplItem.form_structure"
            :value="tplItem.form_data"
            :disabled="
              currentNode.readonlyTpls === undefined ||
              currentNode.readonlyTpls === null ||
              currentNode.readonlyTpls.indexOf(tplItem.id) === -1
                ? null
                : true
            "
            :organ-list="organList"
          />
        </template>
      </div>
      <hr style="background-color: #d9d9d9; border: 0; height: 1px" />
      <div class="text item" style="text-align: center; margin-top: 18px">
        <el-button
          v-for="(item, index) in btn_group"
          :key="index"
          :type="item.className"
          :disabled="submitDisabled"
          @click="submitAction(item.target)"
          >提交</el-button
        >
        <!-- <el-button type="default" @click="onGetFormData"> 获取数据 </el-button> -->
      </div>
    </el-card>
  </div>
</template>

<script>
import Vue from "vue";
import { GenerateForm } from "@/components/VueFormMaking";
import "form-making/dist/FormMaking.css";
Vue.component(GenerateForm.name, GenerateForm);
import { Searchs } from "./save-data";
import {
  processStructure,
  createWorkOrder,
  checkCourseReturnFee,
  queryAllToOrgan,
  queryTeacherOrgan,
  queryUserInfo,
} from "@/api/process/work-order";
import { listUser } from "@/api/system/sysuser";
export default {
  name: "Create",
  data() {
    return {
      submitDisabled: false,
      active: 0,
      currentNode: {},
      organList: [],
      processStructureValue: {},
      socialId: null, // 是否是社保分部
      userId: null,
      tenantId: 1,
      userType: "SYSTEM",
      cacheFormData: [],
      ruleForm: {
        priority: 1,
        deptId: null, // 社保部分
        process: "",
        classify: "",
        state: [],
        source: "",
        source_state: "",
        process_method: "",
        tpls: {
          form_structure: [],
          form_data: [],
        },
        tasks: [],
      },
      rules: {
        deptId: [
          { required: true, message: "请选择申请部门", trigger: "change" },
        ],
        priority: [
          { required: true, message: "请选择工单优先级", trigger: "blur" },
        ],
      },
      deptList: [], // 分部列表
      btn_group: [],
      remoteFunc: {
        // 获取用户列表
        userList(resolve) {
          listUser({
            pageSize: 999999,
          }).then((response) => {
            const options = response.data.list;
            resolve(options);
          });
        },
      },
      documentState: 0, // 草稿状态
      searchs: null,
    };
  },
  async mounted() {
    const processId = this.$route.query.processId;
    this.searchs = new Searchs("process" + processId);
    console.log(this.$router);
    if (sessionStorage.getItem("createReopenReopen") == "1") {
      let createReopenData = sessionStorage.getItem("createReopenData");
      createReopenData = createReopenData ? JSON.parse(createReopenData) : null;
      this.cacheFormData = [createReopenData];
      console.log(this.cacheFormData, "this.cacheFormData");
    } else {
      const getSearch = this.searchs.get();
      this.cacheFormData = getSearch || [];
      console.log(getSearch, "getSearch");
    }

    await this.getUserInfo();
    await this.getAllOrgan();
    await this.getProcessNodeList();
  },
  methods: {
    onGetFormData() {
      var promiseList = [];
      for (var tpl of this.processStructureValue.tpls) {
        const beforData =
          this.$refs["generateForm-" + tpl.id][0].getDataNoValid();
        const afterData = {};

        // 去除数据为空的对象，其它的保留
        for (let i in beforData) {
          if (i.indexOf("subform") != -1) {
            afterData[i] = [];
            for (let j in beforData[i]) {
              afterData[i][j] = {};
              for (let k in beforData[i][j]) {
                if (beforData[i][j][k]) {
                  afterData[i][j][k] = beforData[i][j][k];
                }
              }
            }
          } else {
            if (beforData[i]) {
              afterData[i] = beforData[i];
            }
          }
        }
        // console.log(afterData, "afterData");

        promiseList.push({
          tplId: tpl.id,
          priority: this.ruleForm.priority,
          deptId: this.ruleForm.deptId,
          formData: afterData,
        });
      }
      this.searchs.update(promiseList, null);
    },
    async getUserInfo() {
      await queryUserInfo().then((res) => {
        if (res.code == 200) {
          this.userId = res.data.id;
          this.tenantId = res.data.tenantId;
          this.userType = res.data.userType;
        } else {
          this.$message.error(res.data);
        }
      });
    },
    async getAllOrgan() {
      // 获取分部
      await queryAllToOrgan({ tenantId: this.tenantId }).then((res) => {
        if (res.code == 200) {
          const result = res.data;
          const processId = this.$route.query.processId;
          let filterOrganId = [];
          if ([40, 41, 45, 46, 47].includes(processId)) {
            filterOrganId = [4];
          } else if ([1, 51].includes(processId)) {
            /**
             * 费用申请（借款）
             * 费用申请
             * 添加分部  128
             * 乐小雅
             */
            filterOrganId = [
              1, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
              23, 25, 26, 27, 28, 34, 37, 40, 71, 72, 124, 125, 128,
            ];
          } else {
            filterOrganId = [
              1, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
              23, 25, 26, 27, 28, 34, 37, 40, 71, 72, 124, 125,
            ];
          }

          let tempOrgan = [];
          // 过滤不会显示的分部
          result.forEach((item) => {
            if (filterOrganId.includes(item.id)) {
              tempOrgan.push(item);
            }
          });
          this.organList = tempOrgan;
        }
      });
    },
    async getProcessNodeList() {
      const processId = this.$route.query.processId;
      if (!processId) {
        return;
      }
      await processStructure({
        processId: this.$route.query.processId,
        userId: this.userId,
      }).then((response) => {
        let tempData = response.data.tpls;
        // 获取对应模板中，下拉框的key, value
        let selectList = this.getSelectValueObject(tempData);

        // 获取对应模板中，需要隐藏的字段
        let hiddenFormList = this.getSelectValueObject(
          tempData,
          "hiddenForm",
          selectList
        );
        console.log(hiddenFormList, "hiddenFormList", tempData);

        // 获取对应缓存
        const responseData = response.data;
        console.log(responseData, "responseData");
        // let formCatchData = ''
        for (let i in responseData.tpls) {
          const findItem = this.cacheFormData.find(
            (item) => item.tplId == responseData.tpls[i].id
          );
          console.log(findItem, "findItem");

          if (findItem) {
            // formCatchData = JSON.parse(
            //   JSON.stringify(findItem.formData)
            // );
            responseData.tpls[i].form_data = JSON.parse(
              JSON.stringify(findItem.formData)
            );
          } else {
            // formCatchData = '';
            responseData.tpls[i].form_data = "";
          }
        }

        // 获取需要显示的表单
        // let getShowForm = [] // 显示表单显示
        // tempData.forEach((temp, index) => {
        //   let tempList = temp.form_structure.list || [];
        //   tempList.forEach((item) => {
        //     const currentItem = formCatchData ? formCatchData[item.model] : ''
        //     if (item.type == 'select' && currentItem && item.options.relationStatus) {
        //       const selectChioce = item.options.options ? item.options.options.find(v => v.value == currentItem) : ''
        //       // 判断是否有多个select
        //       getShowForm.push(selectChioce ? selectChioce.relationOptions : [])
        //     }
        //   })
        // })

        tempData.forEach((temp, index) => {
          let tempList = temp.form_structure.list || [];
          tempList.forEach((item) => {
            // 设置默认显示和隐藏的表单
            if (hiddenFormList[index].length > 0) {
              if (item.type != "text" && !item.options.relationStatus) {
                item.hidden = true;
              } else {
                item.hidden = false;
              }
              // item.hidden = false
              if (hiddenFormList[index].includes(item.model)) {
                item.hidden = false;
              }
            } else {
              item.hidden = false;
            }
            // 子表单
            if (item.type == "subform") {
              let childList = item.columns || [];
              let subFormStatus = true;
              childList.forEach((child) => {
                let childList = child.list || [];
                childList.forEach((c) => {
                  if (hiddenFormList[index].length > 0) {
                    if (c.type != "text" && !c.options.relationStatus) {
                      c.hidden = true;
                    } else {
                      c.hidden = false;
                      subFormStatus = false;
                    }
                    if (hiddenFormList[index].includes(c.model)) {
                      c.hidden = false;
                      subFormStatus = false;
                    }
                  } else {
                    c.hidden = false;
                    subFormStatus = false;
                  }
                });
              });
              item.hidden = subFormStatus;
            }

            // if (getShowForm && getShowForm.length > 0) {
            //   const findIndex = getShowForm.findIndex(v => v == item.model)
            //   console.log(findIndex, 'findIndex')
            //   if (findIndex >= 0) {
            //     item.hidden = false
            //   }
            // }
          });
        });

        this.processStructureValue = response.data;
        this.currentNode = this.processStructureValue.nodes[0];

        this.deptList = response.data.depts || [];
        const defaultDept = response.data.deptId;
        this.socialId = defaultDept;
        if (this.cacheFormData.length > 0) {
          const tempSearch = this.cacheFormData[0];
          this.ruleForm.deptId = tempSearch.deptId
            ? Number(tempSearch.deptId)
            : null;
          this.ruleForm.priority = tempSearch.priority;
        } else {
          this.deptList.forEach((item, index) => {
            if (defaultDept) {
              if (item.deptId == defaultDept) {
                this.deptName = item.deptName;
                this.ruleForm.deptId = item.deptId;
              }
            } else {
              if (index == 0) {
                this.deptName = item.deptName;
                this.ruleForm.deptId = item.deptId;
              }
            }
            item.text = item.deptName;
          });
        }

        // 按钮设置
        const psv = response.data.edges || [];
        const btn_group = [];
        psv.forEach((item) => {
          if (item.source === this.currentNode.id && item.flowProperties == 1) {
            if (item.flowProperties == 1) {
              item.className = "primary";
            } else if (item.flowProperties == 0) {
              item.className = "danger";
            } else if (item.flowProperties == 2) {
              item.className = "primary";
            }
            btn_group.push(item);
          } else {
            item.className = "primary";
          }
        });
        this.btn_group = btn_group;
        if (!this.socialId && this.deptList.length <= 0) {
          this.$alert("您当前暂未设置所属部门，请联系管理员", "提示", {
            confirmButtonText: "确定",
            callback: (action) => {},
          });
        }
      });
    },
    // // 添加关联表单方法
    // 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();
    // },
    getSelectValueObject(tpls, type = "value", tplValues = []) {
      const tempData = tpls || [];
      let selectList = [];
      tempData.forEach((temp, index) => {
        let tempList = temp.form_structure.list || [];
        let tempSelectList = tplValues[index] || [];
        let listArray = [];
        tempList.forEach((list) => {
          if (list.type == "select") {
            if (type == "value") {
              const result = this.getFormDataDetail(temp.form_data, list.model);
              if (result.status) {
                listArray.push(result);
              }
            } else {
              let selectOptions = [];
              let selectValue = [];
              tempSelectList.forEach((tsl) => {
                if (tsl.model == list.model) {
                  selectOptions = list.options.options || [];
                  selectValue = tsl.value || [];
                }
              });
              selectOptions.forEach((so) => {
                if (selectValue.includes(so.value)) {
                  let tempRo = so.relationOptions || [];
                  listArray.push(...tempRo);
                }
              });
            }
          }
          if (list.type == "subform") {
            let childList = list.columns || [];
            childList.forEach((child) => {
              let childList = child.list || [];
              childList.forEach((c) => {
                if (c.type == "select") {
                  if (type == "value") {
                    const originObj = JSON.parse(JSON.stringify(c));
                    const result = this.getFormDataDetail(
                      temp.form_data,
                      originObj.model
                    );
                    if (result.status) {
                      listArray.push(result);
                    }
                  } else {
                    let selectOptions = [];
                    let selectValue = [];
                    tempSelectList.forEach((tsl) => {
                      if (tsl.model == c.model) {
                        selectOptions = c.options.options || [];
                        selectValue = tsl.value || [];
                      }
                    });
                    selectOptions.forEach((so) => {
                      if (selectValue.includes(so.value)) {
                        let tempRo = so.relationOptions || [];
                        listArray.push(...tempRo);
                      }
                    });
                  }
                }
              });
            });
          }
        });
        selectList.push(listArray);
      });
      return selectList;
    },
    // 获取对应元素的值
    getFormDataDetail(formData, model) {
      let modelStatus = {
        status: false,
        value: null,
      };
      for (let data in formData) {
        if (typeof formData[data] == "object") {
          // 没有子表单里面有子表单
          for (let child in formData[data]) {
            if (child == model) {
              modelStatus = {
                status: true,
                model: child,
                value: formData[data][child]
                  ? formData[data][child].split(",")
                  : [],
              };
            }
          }
        } else {
          if (data == model) {
            modelStatus = {
              status: true,
              model: data,
              value: formData[data] ? formData[data].split(",") : [],
            };
          }
        }
      }
      return modelStatus;
    },
    submitAction(target) {
      console.log(this.ruleForm, "ruleForm");
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.submitDisabled = true;
          var stateMap = {};
          this.ruleForm.process = parseInt(this.$route.query.processId);
          this.ruleForm.classify = this.processStructureValue.process.classify;
          stateMap["id"] = target;
          this.ruleForm.source_state =
            this.processStructureValue.nodes[this.active].label;
          for (var v of this.processStructureValue.nodes) {
            if (v.id === target) {
              if (v.assignType !== undefined) {
                stateMap["process_method"] = v.assignType;
              }
              if (v.assignValue !== undefined) {
                stateMap["processor"] = Array.from(new Set(v.assignValue));
              }
              stateMap["label"] = v.label;
              break;
            }
          }
          this.ruleForm.state = [stateMap];

          this.ruleForm.tpls = {
            form_structure: [],
            form_data: [],
          };
          // 绑定流程任务
          this.ruleForm.tasks =
            this.processStructureValue.process.task === undefined
              ? []
              : this.processStructureValue.process.task;
          // 追加节点任务
          if (
            this.processStructureValue.nodes[this.active].task !== undefined &&
            this.processStructureValue.nodes[this.active].task.length > 0
          ) {
            for (var task of this.processStructureValue.nodes[this.active]
              .task) {
              if (this.ruleForm.tasks.indexOf(task) === -1) {
                this.ruleForm.tasks.push(task);
              }
            }
          }

          let promiseList = [];
          for (var tpl of this.processStructureValue.tpls) {
            tpl.form_structure.id = tpl.id;
            this.ruleForm.tpls.form_structure.push(tpl.form_structure);
            promiseList.push(this.$refs["generateForm-" + tpl.id][0].getData());
          }
          Promise.all(promiseList)
            .then(async (values) => {
              this.ruleForm.source =
                this.processStructureValue.nodes[this.active].id;
              this.ruleForm.tpls.form_data = values;
              const formData = values[0];
              const tplInfo = this.processStructureValue.tpls[0]; // 默认只用第一个模板
              // 校验数据
              const res = await checkCourseReturnFee({
                tplInfoId: tplInfo.id,
                formData,
              });
              if (res.code == 200) {
                await createWorkOrder(this.ruleForm)
                  .then((response) => {
                    if (response.code === 200) {
                      this.$message.success("工单申请成功");
                      this.documentState = 1;
                      // 删除已经有数据
                      this.searchs.removeByKey();
                      setTimeout(() => {
                        this.$router.push({ path: "/process/my-create" });
                      }, 50);
                    }
                  })
                  .catch(() => {
                    this.submitDisabled = false;
                  });
              } else {
                this.$message.error(res.message);
                return;
              }
            })
            .catch(() => {
              this.submitDisabled = false;
            });
        }
      });
    },
  },
  beforeRouteLeave(to, from, next) {
    // 从 bar 里面赋值的
    const create_ticket_status = sessionStorage.getItem("create_ticket_status");
    if (this.documentState == 0 && !create_ticket_status) {
      setTimeout(() => {
        // 做是否离开判断？
        // 还是做是否保存判断？
        sessionStorage.removeItem("createReopenReopen");
        this.$confirm("您的申请尚未提交，是否确认返回？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.onGetFormData();
            next();
          })
          .catch(() => {
            next(false);
          });
      }, 200);
    } else {
      if (create_ticket_status) {
        this.onGetFormData();
        sessionStorage.removeItem("create_ticket_status");
        sessionStorage.removeItem("createReopenReopen");
      }
      next();
    }
  },
};
</script>
