<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"
            :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
        >
      </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 {
  processStructure,
  createWorkOrder,
  checkCourseReturnFee,
  queryAllOrgan,
  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",
      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, // 草稿状态
    };
  },
  async mounted() {
    await this.getUserInfo();
    await this.getAllOrgan();
    this.getProcessNodeList();
  },
  methods: {
    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() {
      // 获取分部
      if (this.userType.indexOf("SYSTEM") != -1) {
        await queryAllOrgan({ tenantId: this.tenantId }).then((res) => {
          if (res.code == 200) {
            const result = res.data;
            const filterOrganId = [
              36, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 52, 54, 55, 56,
            ];
            let tempOrgan = [];
            // 过滤不会显示的分部
            result.forEach((item) => {
              if (!filterOrganId.includes(item.id)) {
                tempOrgan.push(item);
              }
            });
            this.organList = tempOrgan;
          }
        });
      } else {
        await queryTeacherOrgan({ tenantId: this.tenantId }).then((res) => {
          if (res.code == 200) {
            const result = res.data;
            const filterOrganId = [
              36, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 52, 54, 55, 56,
            ];
            let tempOrgan = [];
            // 过滤不会显示的分部
            result.forEach((item) => {
              if (!filterOrganId.includes(item.key)) {
                tempOrgan.push({
                  id: item.key,
                  name: item.value,
                });
              }
            });
            this.organList = tempOrgan;
          }
        });
      }
    },
    getProcessNodeList() {
      const processId = this.$route.query.processId;
      if (!processId) {
        return;
      }
      processStructure({
        processId: this.$route.query.processId,
        userId: this.userId,
      }).then((response) => {
        let tempData = response.data.tpls;
        // console.log(response);
        // 获取对应模板中，下拉框的key, value
        let selectList = this.getSelectValueObject(tempData);
        // console.log(selectList);

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

        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;
            }
          });
        });

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

        this.deptList = response.data.depts || [];
        const defaultDept = response.data.deptId;
        this.socialId = defaultDept;
        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.$dialog.alert({
          //   message: "您当前暂未设置所属部门，请联系管理员",
          //   confirmButtonColor: "#01C1B5"
          // })
          this.$alert("您当前暂未设置所属部门，请联系管理员", "提示", {
            confirmButtonText: "确定",
            callback: (action) => {},
          });
        }
      });
    },
    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) {
      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);
              }
            }
          }

          var 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]; // 默认只用第一个模板
              // console.log(this.ruleForm.tpls.form_data);
              // 校验数据
              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.$router.push({ path: "/process/my-create" });
                    }
                  })
                  .catch(() => {
                    this.submitDisabled = false;
                  });
              } else {
                this.$message.error(res.message);
                return;
              }
            })
            .catch(() => {
              this.submitDisabled = false;
            });
        }
      });
    },
    compareData() {},
  },
  beforeRouteLeave(to, from, next) {
    if (this.documentState == 0) {
      setTimeout(() => {
        // 做是否离开判断？
        // 还是做是否保存判断？
        this.$confirm("您的申请尚未提交，是否确认返回？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            next();
          })
          .catch(() => {});
      }, 200);
    } else {
      next();
    }
  },
};
</script>
