<template>
  <div class="app-container">
    <div v-if="isLoadingStatus"></div>
    <div v-else>
      <el-alert
        v-if="
          activeIndex !== nodeStepList.length &&
          processStructureValue.workOrder.is_end === 1
        "
        style="margin-top: 15px"
        :title="alertMessage"
        type="error"
        :closable="false"
      />

      <el-card class="box-card" style="margin-top: 15px">
        <div slot="header" class="clearfix">
          <span>公共信息</span>
        </div>
        <div class="text item">
          <el-form label-width="100px">
            <el-row>
              <el-col :span="6">
                <el-form-item label="编号(ID):" style="margin-bottom: 5px">
                  <span>{{ this.workOrderId }}</span>
                </el-form-item>
              </el-col>

              <el-col :span="18">
                <el-form-item label="标题:" style="margin-bottom: 5px">
                  <span>{{ processStructureValue.workOrder.title }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="优先级:" style="margin-bottom: 0">
                  <span v-if="processStructureValue.workOrder.priority === 2">
                    <el-tag type="warning">紧急</el-tag>
                  </span>
                  <span
                    v-else-if="processStructureValue.workOrder.priority === 3"
                  >
                    <el-tag type="danger">非常紧急</el-tag>
                  </span>
                  <span v-else>
                    <el-tag type="success">一般</el-tag>
                  </span>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item label="工单类型:" style="margin-bottom: 5px">
                  <span>{{ processStructureValue.process.name }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-card>

      <el-card class="box-card" style="margin-top: 15px">
        <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.form_structure.id) === -1
              "
              :key="tplIndex"
              :ref="'generateForm-' + tplItem.id"
              :preview="true"
              :remote="remoteFunc"
              :value="tplItem.form_data"
              :data="tplItem.form_structure"
              :organ-list="organList"
            />
          </template>
        </div>
        <hr
          v-if="is_end == 0"
          style="
            background-color: #d9d9d9;
            border: 0;
            height: 1px;
            margin-bottom: 15px;
          "
        />
        <div class="text item" style="margin-top: 18px; text-align: center">
          <!-- 只要没有结束就可以评论 -->
          <el-button round type="info" @click="handleCommit"
            >评论</el-button
          >

          <template v-if="is_end == 0 && processStructureValue.userAuthority">
            <!-- 没有结束，自己审批 -->
            <el-button
              type="warning"
              round
              @click="handleInversion(endNodeDetail)"
              >转交</el-button
            >
            <el-button
              v-for="(item, index) in btn_group"
              :key="index"
              :type="item.className"
              @click="submitAction(item)"
              round
              >{{ item.labelShow }}</el-button
            >

            <!-- 拒绝按钮内置 -->
            <el-button
              v-if="endNodeDetail.id"
              type="danger"
              round
              @click="submitAction(endNodeDetail)"
              >{{ endNodeDetail.label }}</el-button
            >
          </template>
        </div>
      </el-card>

      <el-card class="box-card" style="margin-top: 15px">
        <div slot="header" class="clearfix">
          <span>流程</span>
        </div>
        <div class="text item">
          <el-timeline
            v-if="
              currentNode.clazz !== undefined &&
              currentNode.clazz !== null &&
              currentNode.clazz !== ''
            "
          >
            <el-timeline-item
              v-for="(item, index) in circulationList"
              :key="index"
              :icon="formatIcon(item, index, 'icon')"
              :class="activeIndex >= index ? 'large-icon' : ''"
              size="large"
            >
              <div class="step-title">
                {{ item.state || item.label }}
                <span class="apply-time">
                  {{
                    item.create_time
                      ? dayjs(item.create_time).format("MM-DD HH:mm")
                      : null
                  }}
                </span>
              </div>

              <template v-if="!item.create_time">
                <p
                  class="apply-status"
                  v-if="item.assignUsers && item.assignUsers.length > 0"
                >
                  <!-- 判断是否是自己审批 -->
                  <template
                    v-if="
                      item.assignUsers[0].userId == userInfo.userId &&
                      activeIndex == index
                    "
                  >
                    我（审批中）
                  </template>
                  <template v-else>
                    <template v-if="item.isCounterSign">
                      <span
                        v-for="(au, aIndex) in item.assignUsers"
                        :key="aIndex"
                      >
                        {{ au.username
                        }}{{
                          aIndex < item.assignUsers.length - 1 ? "，" : null
                        }}
                      </span>
                    </template>
                    <template v-else>
                      {{ item.assignUsers[0].username }}
                    </template>
                    {{ activeIndex == index ? `（审批中）` : null }}
                  </template>
                </p>
              </template>
              <template v-else>
                <p class="apply-status" v-if="item.processor">
                  {{ item.processor
                  }}{{ item.circulation ? `（${item.circulation}）` : null }}
                </p>
                <template v-if="item.remarks && item.remarks.trim()">
                  <p
                    class="remarks"
                    v-html="dataModelFormatBr(item.remarks)"
                  ></p>
                </template>

                <!-- 判断是否有添加图片 -->
                <div
                  class="imgUploader"
                  v-if="
                    item.fileUrl &&
                    item.fileUrl.file &&
                    item.fileUrl.image.length > 0
                  "
                >
                  <el-image
                    v-for="(file, index) in item.fileUrl.image"
                    :key="index"
                    style="width: 40px; height: 40px; margin-right: 12px"
                    :src="file"
                    :preview-src-list="item.fileUrl.image"
                  >
                  </el-image>
                </div>
                <!-- 判断是否有添加的文件 -->
                <div
                  v-if="
                    item.fileUrl &&
                    item.fileUrl.file &&
                    item.fileUrl.file.length > 0
                  "
                >
                  <div
                    v-for="(uploadUrlItem, uploadUrlIndex) in item.fileUrl.file"
                    :key="uploadUrlIndex"
                    style="margin-bottom: 3px"
                    class="fileUploader"
                  >
                    <i style="color: #909399" class="el-icon-document" />
                    <span style="margin-right: 10px">{{
                      uploadUrlItem.name || uploadUrlItem.url
                    }}</span>
                    <el-button
                      round
                      size="mini"
                      @click="onDownload(uploadUrlItem, 'download')"
                      >下载</el-button
                    >
                    <!-- <el-button
                      round
                      type="primary"
                      @click="onDownload(uploadUrlItem)"
                      v-if="checkFileSuffix(uploadUrlItem.url)"
                      size="mini"
                      >预览</el-button
                    > -->
                    <el-button
                      round
                      type="primary"
                      @click="onDownload(uploadUrlItem)"
                      v-if="
                        checkFileSuffix(uploadUrlItem.url) &&
                        !isCheckImage(uploadUrlItem.url)
                      "
                      size="mini"
                      >预览</el-button
                    >
                    <div
                      v-if="isCheckImage(uploadUrlItem.url)"
                      style="
                        display: inline-flex;
                        position: relative;
                        margin-left: 10px;
                      "
                    >
                      <el-button
                        style="position: absolute; left: 0; top: 0"
                        round
                        type="primary"
                        @click="onDownload(uploadUrlItem)"
                        v-if="checkFileSuffix(uploadUrlItem.url)"
                        size="mini"
                        >预览</el-button
                      >
                      <el-image
                        style="width: 56px; height: 28px; opacity: 0"
                        :src="uploadUrlItem.url"
                        :preview-src-list="[uploadUrlItem.url]"
                      >
                      </el-image>
                    </div>
                  </div>
                </div>
              </template>

              <!-- 有抄送人并且，本节点已经审批完成了 -->
              <template
                v-if="
                  item.cc_user && item.cc_user.length > 0 && activeIndex > index
                "
              >
                <!-- 已抄送1人 -->
                <div class="ccUsers" @click="onCCChange(item)">
                  <span>已抄送{{ item.cc_user.length }}人</span>
                  <el-icon
                    v-show="!item.ccStatus"
                    style="color: #cccccc"
                    name="arrow-down"
                  />
                  <el-icon
                    v-show="item.ccStatus"
                    style="color: #cccccc"
                    name="arrow-up"
                  />
                </div>
                <div class="ccUserDetail" v-if="item.ccStatus">
                  <span>{{ item.cc_user.join(",") }}</span>
                </div>
              </template>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-card>
    </div>
    <el-dialog title="转交工单" :visible.sync="dialogVisible" width="40%">
      <TransferInversion
        v-if="dialogVisible"
        :selectItem="selectItem"
        @getList="getProcessNodeList"
        @close="dialogVisible = false"
      />
    </el-dialog>
    <el-dialog :title="submitTitle" :visible.sync="dialogSubmit" width="40%">
      <TransferSubmit
        v-if="dialogSubmit"
        :type="submitType"
        :submitItem="submitItem"
        @getList="getProcessNodeList"
        @close="dialogSubmit = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import Upload from "./model/upload";
import Vue from "vue";
import { GenerateForm } from "@/components/VueFormMaking";
import "form-making/dist/FormMaking.css";
Vue.component(GenerateForm.name, GenerateForm);
import dayjs from "dayjs";

import {
  processStructure,
  handleWorkOrder,
  activeOrder,
  asyncPlayLog,
  queryUserInfo,
  queryAllToOrgan,
  queryTeacherOrgan,
  orderComment,
} from "@/api/process/work-order";
import store from "@/store";
import { getInfo } from "@/api/user";

import { listUser } from "@/api/system/sysuser";
import TransferInversion from "./model/transferInversion";
import TransferSubmit from "./model/transferSubmit.vue";
import load from "@/utils/loading";

import { mapGetters } from "vuex";
export default {
  components: {
    TransferInversion,
    TransferSubmit,
    Upload,
  },
  data() {
    const query = this.$route.query;
    return {
      submitTitle: "提交信息",
      dialogSubmit: false,
      submitType: "commit",
      submitItem: {},
      workOrderId: query.workOrderId,
      processId: query.processId,
      isLoadingStatus: true,
      currentNode: {
        hideTpls: null,
        writeTpls: null,
      },
      isActiveProcessing: false,
      tpls: [],
      organList: [],
      dataList: {
        remarks: "", // 备注信息
      },
      fileUrl: [],
      userInfo: {},
      alertMessage: "",
      nodeStepList: [],
      circulationHistoryList: [],
      circulationList: [],
      activeIndex: 0,
      processStructureValue: {
        workOrder: { title: "" },
      },
      ownerApply: false, // 是否是自己提交的申请
      endNodeDetail: {}, // 结束结节信息
      ruleForm: {
        title: "",
        process: "",
        classify: "",
        state_id: "",
        state: "",
        source_state: "",
        processor: "",
        process_method: "",
        tpls: [],
        tasks: [],
      },
      userIds: null,
      tenantId: 1,
      userType: "SYSTEM",
      btn_group: [],
      is_end: 0, // 是否结束
      remoteFunc: {
        // 获取用户列表
        userList(resolve) {
          listUser({
            pageSize: 999999,
          }).then((response) => {
            const options = response.data.list;
            resolve(options);
          });
        },
      },
      dialogVisible: false,
      selectItem: {
        work_order_id: "",
        node_id: null,
        nodeList: [],
        users: [],
      },
    };
  },
  computed: {
    ...mapGetters(["userId"]),
  },
  async mounted() {
    await this.getUserInfo();
    await this.getAllOrgan();
    await this.getProcessNodeList();
    // 获取用户信息
    try {
      let user = await getInfo();
      this.userInfo = user.data;
      this.ownerApply =
        this.processStructureValue.workOrder.creator == user.data.userId
          ? true
          : false;
    } catch {
      //
    }
    console.log({
      is_end: this.is_end,
      ownerApply: this.ownerApply,
      userAuthority: this.processStructureValue.userAuthority,
    });
  },
  methods: {
    dayjs,
    // 获取学校列表
    onDownload(item, type) {
      if (type == "download") {
        window.location.href = item.url;
        return;
      }

      let urlArr = item.url.split(".");
      let suffix = urlArr[urlArr.length - 1];
      const imgSuffix = ["png", "jpg", "jpeg", "gif", "ico"];
      if (imgSuffix.includes(suffix)) {
      } else if (suffix != "pdf") {
        this.previewUrl =
          "https://view.officeapps.live.com/op/view.aspx?src=" + item.url;
        window.open(this.previewUrl);
        return;
      } else {
        this.previewUrl =
          this.validManageUrl() + "/pdf/web/viewer.html?file=" + item.url;
        window.open(this.previewUrl);
        return;
      }
    },
    // 教务地址
    validManageUrl() {
      let url = window.location.hostname;
      let returnUrl = "";
      if (/dev/.test(url)) {
        // dev 环境
        returnUrl = "https://dev.gym.lexiaoya.cn/manager";
      } else if (/test/.test(url)) {
        // dev 环境
        returnUrl = "https://test.gym.lexiaoya.cn/manager";
      } else {
        //线上
        returnUrl = "https://gym.lexiaoya.cn/manager";
      }
      return returnUrl;
    },
    isCheckImage(file) {
      const urlArr = file.split(".");
      const suffix = urlArr[urlArr.length - 1];
      const imgSuffix = ["png", "jpg", "jpeg", "gif", "ico"];
      console.log(imgSuffix.includes(suffix), "11");
      return imgSuffix.includes(suffix);
    },
    checkFileSuffix(url) {
      let urlArr = url.split(".");
      let suffix = urlArr[urlArr.length - 1];
      const passSuffix = [
        "xlsx",
        "xls",
        "pdf",
        "png",
        "jpg",
        "jpeg",
        "gif",
        "ico",
      ];
      if (passSuffix.includes(suffix)) {
        return true;
      } else {
        return false;
      }
    },
    async handleCommit() {
      console.log("handleCommit", true);
      this.submitTitle = "添加评论";
      this.submitType = "commit";
      this.submitItem = {
        workOrderId: parseInt(this.workOrderId),
      };
      this.dialogSubmit = true;
    },
    async handleInversion() {
      let workOrder = this.processStructureValue.workOrder;
      this.selectItem.work_order_id = workOrder.id;
      this.selectItem.nodeList = workOrder.state || [];
      this.selectItem.nodeList.forEach((item) => {
        item.text = item.label;
      });
      if (this.selectItem.nodeList.length === 1) {
        this.selectItem.node_id = this.selectItem.nodeList[0].id;
      }
      if (this.selectItem.users.length <= 0) {
        load.startLoading();
        await listUser({
          pageSize: 999999,
        }).then((response) => {
          this.selectItem.users = response.data.list;
        });
        load.endLoading();
      }
      this.dialogVisible = true;
    },
    async getUserInfo() {
      await queryUserInfo().then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.userIds = res.data.id;
          this.tenantId = res.data.tenantId;
          this.userType = res.data.userType;
        } else {
          this.$message.error(res.data);
        }
      });
    },
    async getProcessNodeList() {
      await processStructure({
        processId: this.processId,
        workOrderId: this.workOrderId,
        userId: this.userIds,
      }).then((response) => {
        let tempData = response.data.tpls;
        // 获取对应模板中，下拉框的key, value
        let selectList = this.getSelectValueObject(tempData);

        // 获取对应模板中，需要隐藏的字段
        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.isActiveProcessing = false;
        this.processStructureValue = response.data;
        this.is_end = this.processStructureValue.workOrder.is_end;
        this.circulationHistoryList =
          this.processStructureValue.circulationHistory;
        this.circulationList = JSON.parse(
          JSON.stringify(this.circulationHistoryList)
        );
        this.circulationHistoryList.forEach((item) => {
          const file = item.file_url ? JSON.parse(item.file_url) : [];
          const tempFile = {
            image: [],
            file: [],
          };
          // console.log(file)
          file.forEach((item) => {
            if (item.type == "image") {
              tempFile.image.push(item.url);
            } else if (item.type == "file") {
              tempFile.file.push(item);
            }
          });
          item.fileUrl = tempFile;
        });

        this.circulationList.forEach((item) => {
          const file = item.file_url ? JSON.parse(item.file_url) : [];
          const tempFile = {
            image: [],
            file: [],
          };
          // console.log(file)
          file.forEach((item) => {
            if (item.type == "image") {
              tempFile.image.push(item.url);
            } else if (item.type == "file") {
              tempFile.file.push(item);
            }
          });
          item.fileUrl = tempFile;
        });
        // console.log(this.circulationHistoryList, "circulationHistoryList");

        // 获取当前展示节点列表
        // this.nodeStepList = this.processStructureValue.circulationHistory

        // 获取当前展示节点列表
        this.nodeStepList = [];
        let nodes = this.processStructureValue.nodes;
        this.principals = "处理中";
        for (var i = 0; i < nodes.length; i++) {
          // console.log(
          //   nodes[i].id,
          //   this.processStructureValue.workOrder.current_state,
          //   "xji"
          // );
          if (
            nodes[i].id === this.processStructureValue.workOrder.current_state
          ) {
            // 当前节点
            this.nodeStepList.push(nodes[i]);
            this.activeIndex = this.nodeStepList.length - 1;
            if (i + 1 === nodes.length) {
              this.activeIndex = this.nodeStepList.length;
            }
            this.currentNode = nodes[i];

            // 处理是认谁在处理,已处理完成则显示处理中
            const assignUsers = nodes[i].assignUsers;
            if (assignUsers && assignUsers.length > 0) {
              this.principals = assignUsers[0].username + "处理中";
            }
          } else if (!nodes[i].isHideNode) {
            // 非隐藏节点
            this.nodeStepList.push(nodes[i]);
          }

          // 判断节点里面是否有结束节点，而且一个流程里面只能有一个结束结点，
          if (nodes[i].clazz == "end") {
            this.endNodeDetail = JSON.parse(JSON.stringify(nodes[i]));
            this.endNodeDetail.target = nodes[i].id;
            this.endNodeDetail.flowProperties = 0; // 拒绝属性
            this.endNodeDetail.label = "拒绝";
          }
        }
        this.circulationList.reverse();
        // 如果审批流程没有结束则，流程和历史记录合并显示；结束了，就只显示历史记录
        if (!this.processStructureValue.workOrder.is_end) {
          this.circulationList.forEach((cir) => {
            this.nodeStepList.forEach((node) => {
              if (cir.source == node.id) {
                cir.label = node.label;
                cir.assignType = node.assignType;
                cir.assignValue = node.assignValue;
                cir.assignUsers = node.assignUsers;
                cir.id = node.id;
              }
            });
          });

          let tempNodes = [];
          this.nodeStepList.forEach((node) => {
            let count = 0;
            this.circulationList.forEach((cir) => {
              if (node.id === cir.source) {
                count += 1;
              }
            });
            if (count <= 0) {
              tempNodes.push(node);
            }
          });
          this.circulationList.push(...tempNodes);
          this.circulationList.forEach((cir, index) => {
            if (cir.id == this.processStructureValue.workOrder.current_state) {
              this.activeIndex = index;
              if (index + 1 == this.circulationList.length) {
                this.activeIndex = this.circulationList.length;
              }
            }
          });
        } else {
          this.activeIndex = this.circulationList.length;
        }
        // 添加抄送状态
        this.circulationList.forEach((res) => {
          res.ccStatus = true;
        });

        // console.log(this.nodeStepList);
        // console.log(this.circulationList, "this.circulationList");

        // if(this.processStructureValue.nodes) {
        // for (var i = 0; i < this.processStructureValue.nodes.length; i++) {
        //   if (this.processStructureValue.nodes[i].id === this.processStructureValue.workOrder.current_state) {
        //     // 当前节点
        //     this.nodeStepList.push(this.processStructureValue.nodes[i])
        //     this.activeIndex = this.nodeStepList.length - 1
        //     if (i + 1 === this.processStructureValue.nodes.length) {
        //       this.activeIndex = this.nodeStepList.length
        //     }
        //     this.currentNode = this.processStructureValue.nodes[i]
        //   } else if (!this.processStructureValue.nodes[i].isHideNode) {
        //     // 非隐藏节点
        //     this.nodeStepList.push(this.processStructureValue.nodes[i])
        //   }
        // }
        // }

        // 如果回退到初始节点则可编辑。
        if (this.activeIndex === 0 && this.currentNode.clazz === "start") {
          this.currentNode.writeTpls = [];
          for (var tplTmp of this.processStructureValue.tpls) {
            this.currentNode.writeTpls.push(tplTmp.form_structure.id);
          }
        }

        // 判断是否需要主动处理
        for (var stateValue of this.processStructureValue.workOrder.state) {
          if (
            this.processStructureValue.workOrder.current_state ===
              stateValue.id &&
            stateValue.processor.length > 1
          ) {
            this.isActiveProcessing = true;
            break;
          }
        }

        // const nodes = this.processStructureValue.nodes;
        // for (var i = 0; i < nodes.length; i++) {
        //   // 判断节点里面是否有结束节点，而且一个流程里面只能有一个结束结点，
        //   if (nodes[i].clazz == "end") {
        //     this.endNodeDetail = JSON.parse(JSON.stringify(nodes[i]));
        //     this.endNodeDetail.target = nodes[i].id;
        //     this.endNodeDetail.flowProperties = 0; // 拒绝属性
        //     this.endNodeDetail.label = "拒绝";
        //   }
        // }

        let psv = response.data.edges || [];
        let btn_group = [];
        psv.forEach((item) => {
          // 过滤其它类型的操作
          if (
            this.processStructureValue.workOrder.is_end === 0 &&
            item.source === this.currentNode.id &&
            item.flowProperties == 1
          ) {
            if (item.flowProperties == 1) {
              item.className = "primary";
              item.labelShow = "同意";
            } 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;
        this.isLoadingStatus = false;
        // console.log(this.circulationList, "circulationList");
        // console.log(this.currentNode, "currentNode  ");
        this.getAlertMessage();
      });
    },
    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(item) {
      var promiseList = [];
      this.tpls = [];
      for (var tpl of this.processStructureValue.tpls) {
        this.tpls.push({
          tplDataId: tpl.id,
          tplId: tpl.form_structure.id,
        });
        promiseList.push(this.$refs["generateForm-" + tpl.id][0].getData());
      }
      console.log({
        tasks: this.processStructureValue.process.task,
        source_state: this.processStructureValue.workOrder.current_state,
        target_state: item.target,
        circulation: item.label,
        flow_properties:
          item.flowProperties === undefined ? 2 : parseInt(item.flowProperties),
        work_order_id: parseInt(this.$route.query.workOrderId),
        remarks: this.dataList.remarks,
        fileUrl: JSON.stringify(this.fileUrl || []),
        tpls: this.tpls,
      });

      const flow =
        item.flowProperties === undefined ? 2 : parseInt(item.flowProperties);
      let str = "同意";
      if (flow == 1) {
        str = "同意";
        this.submitTitle = "确认同意";
        this.submitType = "argee";
      } else if (flow == 0) {
        str = "拒绝";
        this.submitTitle = "确认拒绝";
        this.submitType = "reject";
      } else {
        str = "操作";
        this.submitTitle = "操作";
        this.submitType = "operation";
      }
      const tips = `您是否${str}此审批?`;
      // this.$confirm(tips, "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // }).then(() => {
      Promise.all(promiseList).then((values) => {
        for (var tplDataIndex in this.tpls) {
          this.tpls[tplDataIndex].tplValue = values[tplDataIndex];
        }

        let fileList = [];
        this.tpls &&
          this.tpls.forEach((tpl) => {
            for (let val in tpl.tplValue) {
              if (val.indexOf("file") != -1) {
                const file = tpl.tplValue[val] || [];
                file.forEach((item) => {
                  fileList.push(item.url);
                });
              }
            }
          });
        this.submitItem = {
          tasks: this.processStructureValue.process.task,
          source_state: this.processStructureValue.workOrder.current_state,
          target_state: item.target,
          circulation: item.label,
          flow_properties:
            item.flowProperties === undefined
              ? 2
              : parseInt(item.flowProperties),
          work_order_id: parseInt(this.$route.query.workOrderId),
          tpls: this.tpls,
          fileList,
          tips,
        };
        this.dialogSubmit = true;
      });
      // });
    },
    onCCChange(item) {
      item.ccStatus = !item.ccStatus;
      this.$forceUpdate();
    },
    // 获取提示消息
    getAlertMessage() {
      if (this.processStructureValue.workOrder.is_end === 1) {
        this.alertMessage = "当前工单已结束。";
      }
    },
    // activeOrderActive() {
    //   var jsonData = [{
    //     id: this.nodeStepList[this.activeIndex].id,
    //     label: this.nodeStepList[this.activeIndex].label,
    //     process_method: 'person',
    //     processor: [this.userId]
    //   }]
    //   activeOrder(jsonData, this.$route.query.workOrderId).then(() => {
    //     this.getProcessNodeList()
    //   })
    // },
    async getAllOrgan() {
      // 获取分部
      console.log(this.tenantId, "tenantId");
      // if (this.userType.indexOf("SYSTEM") != -1) {
      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 {
            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, 123, 124, 125, 128, 134,
              148, 147, 127, 139, 151, 36, 149, 152, 153, 158
            ];
          }

          let tempOrgan = [];
          // 过滤不会显示的分部
          result.forEach((item) => {
            if (filterOrganId.includes(item.id)) {
              tempOrgan.push(item);
            }
          });
          this.organList = tempOrgan;
        }
      });
      // } else {
      //   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;
      //     }
      //   });
      // }
    },
    dataModelFormatBr(str) {
      return str ? str.replace(/\n/g, "<br />") : str;
    },
    formatIcon(item, index, type) {
      // 格式化ICON
      // console.log(item, index)
      // console.log(this.activeIndex)
      if (this.activeIndex >= index) {
        if (item.circulation == "转交") {
          return "icon-transfer";
        } else if (this.activeIndex == index) {
          return "icon-wait";
        } else if (item.status == 0) {
          return "el-icon-error";
        } else {
          return "el-icon-success";
        }
      }

      // #fd803a
      return "";
    },
  },
};
</script>

<style lang="scss" scoped>
:deep(.el-step__title) {
  font-size: 13px;
  line-height: 1.3;
  width: 100%;
  padding-top: 10px;
  padding-right: 10px;
}

.step-title {
  color: #000;
  font-size: 16px;
}
.apply-time {
  font-size: #999;
  color: #999;
  padding-left: 10px;
}
.apply-status {
  line-height: 1.5;
  color: #999;
  margin: 5px 0;
}

.remarks {
  background: #f5f5f5;
  padding: 8px;
  color: #323233;
  border-radius: 6px;
  line-height: 1.5;
}
.imgUploader {
  background: #f5f5f5;
  margin-top: 8px;
  padding: 8px;
  border-radius: 6px;

  .el-image {
    vertical-align: middle;
  }
}

.fileUploader {
  display: flex;
  align-items: center;
  margin-top: 8px;
  background: #f5f5f5;
  padding: 6px;
  border-radius: 4px;
}

:deep(.icon-transfer),
:deep(.icon-wait) {
  display: flex;
  align-items: center;
  box-sizing: content-box;
  background-color: #fff;
  padding: 2px 0;
  height: 23px;
  &::before {
    content: " ";
    display: inline-block;
    width: 23px;
    height: 23px;
    background: url("../../../assets/system-transfer.png") no-repeat center;
    background-size: contain;
  }
}

:deep(.icon-wait) {
  &::before {
    content: " ";
    display: inline-block;
    width: 23px;
    height: 23px;
    background: url("../../../assets/system-wait.png") no-repeat center;
    background-size: contain;
  }
}

.large-icon {
  :deep(.el-timeline-item__node--large) {
    top: -8px;
    left: -7px;
    width: 24px;
    height: 24px;
    background-color: transparent;
  }

  :deep(.el-icon-success),
  :deep(.el-icon-error) {
    font-size: 24px;
    color: #22b4a9;
    background-color: #fff;
    padding: 2px 0;
  }

  :deep(.el-icon-error) {
    color: #ff2e2e;
  }
}
</style>
