<template>
  <div class="process-mange-wrap">
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header" class="clearfix">
        <span>我的申请</span>
      </div>
      <div class="search-area">
        <el-form
          :model="queryParams"
          ref="queryParamsRef"
          label-width="80px"
          :inline="true"
          size="medium"
        >
          <el-form-item label="名称" size="normal">
            <el-input v-model="queryParams.taskName"></el-input>
          </el-form-item>
          <!-- <el-form-item label="开始时间" size="normal">
            <el-date-picker
              v-model="queryParams.startDate"
              type="date"
              size="normal"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item> -->

          <el-form-item>
            <el-button
              type="primary"
              size="medium"
              @click="getList"
              icon="el-icon-search"
              >搜索</el-button
            >
            <el-button size="medium" @click="resetQuery" icon="el-icon-refresh"
              >重置</el-button
            >
            <!-- <el-button type="info" size="medium" @click="toDetail"
              >详情</el-button
            > -->
          </el-form-item>
          <el-form-item>
            <el-radio-group
              v-model="queryParams.taskProcessState"
              @change="getList"
            >
              <el-radio-button label="3">已完成</el-radio-button>
              <el-radio-button label="0">进行中</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <!-- <el-button type="primary" size="default" @click="printTest">
        打印测试
      </el-button> -->

      <div class="show-body">
        <!--    流程任务列表    -->
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          @selection-change="() => {}"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" width="50" align="center" />
          <el-table-column
            v-for="col in newColumn"
            :prop="col.prop"
            :key="col.prop"
            :label="col.label"
            align="center"
          >
            <template slot-scope="scope">
              <span v-if="col.prop == 'benCreateTime'">{{
                scope.row.benCreateTime.replace("T", " ")
              }}</span>
              <span v-else-if="col.prop == 'bepTaskProcessType'">{{
                getDictLabel(scope.row.bepTaskProcessType, dict.type.bpm_type)
              }}</span>
              <span v-else-if="col.prop == 'benTaskNodeState'">{{
                scope.row.benTaskNodeState == "0" ? "未执行" : "已执行"
              }}</span>
              <span v-else-if="col.prop == 'bepTaskProcessState'">{{
                getDictLabel(
                  scope.row.bepTaskProcessState,
                  dict.type.task_process_state
                )
              }}</span>
              <span v-else>{{ scope.row[col.prop] }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            width="150"
            fixed="right"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <!-- <el-button
                v-show="scope.row.bepTaskProcessState != 3"
                class="mr5 mb5"
                @click="approveHandler(scope.row)"
                type="primary"
                size="small"
                >审批</el-button
              > -->
              <el-button
                @click="toDetail(scope.row)"
                type="primary"
                size="small"
                >详情</el-button
              >
              <!-- <el-dropdown>
                <el-button type="warning" plain size="small">
                  处理<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-button
                      @click="approveHandler(scope.row)"
                      type="text"
                      size="small"
                      >审批</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      @click="toDetail(scope.row)"
                      type="text"
                      size="small"
                      >详情</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      v-show="isShowCancel(scope.row)"
                      @click="cancelHandler(scope.row)"
                      type="text"
                      size="small"
                      >取消申请</el-button
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown> -->
            </template>
          </el-table-column>
        </el-table>

        <!--    分页    -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
        <!-- 审批弹窗 -->
        <el-dialog title="审批" :visible.sync="show">
          <!-- <FormGroup ref="formGroupRef" :formList="formList"></FormGroup> -->
          <Approve
            ref="approveRef"
            :formList="formList"
            :nodeLogList="nodeLogList"
          ></Approve>
          <template #footer>
            <span>
              <el-button @click="show = false">取消</el-button>
              <el-button type="primary" @click="confirmHandler">确认</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </el-card>
    <div id="print"></div>
  </div>
</template>

<script>
import {
  processList,
  runProcessNodeExecution,
  getProcessNodeFormTemplate,
  getProcessNodeFormInfoData,
  processNodeExecutionApproval,
  revokeApplication,
  listApproveLog,
} from "@/api/bpmprocess/run/executeProcess";
import { triggerExceptionNode } from "@/api/bpmprocess/process";
import getNodeSequence from "@/utils/bpmn/getNodeSequence";
import { getForm } from "@/api/dragform/form";
import FormGroup from "@/components/FormGroup/index.vue";
import Approve from "@/components/FormGroup/Approve.vue";
import receiptDocuments from "@/utils/print/receiptDocuments";
import qrCodeList from "@/utils/print/qrCodeList.js";
import { xmlStr2XmlObj } from "@/utils/bpmn/tool";

export default {
  name: "processMange",
  props: [],
  components: { FormGroup, Approve },
  dicts: ["bpm_type", "task_process_state"],
  data() {
    return {
      // 弹窗表单数据
      row: {},
      formList: [],
      show: false,
      loading: false,
      row: {}, //当前操作行数据
      myForm: "", //自定义表单组件名
      // 节点弹窗title
      nodeTitle: "节点弹窗",
      open: false,
      // 节点弹窗对应的formData
      commonData: {},
      taskType: 1,
      queryString: "",
      taskStatus: "",
      tableData: [], //表格数据
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskProcessState: "0",
        taskProcessType: 1,
      },
      total: 0,
      columns: [
        {
          prop: "bepTaskKey",
          label: "任务编号",
        },
        {
          prop: "bepTaskProcessName",
          label: "任务名称",
        },
        // {
        //   prop: "bepTaskProcessType",
        //   label: "任务流程类型",
        // },
        {
          prop: "bepTaskProcessState",
          label: "任务流程状态",
        },
        {
          prop: "benTaskNodeName",
          label: "节点名称",
        },
        {
          prop: "benTaskNodeType",
          label: "节点类型",
        },
        {
          prop: "benTaskNodeState",
          label: "节点状态",
        },
        {
          prop: "benCreateBy",
          label: "创建人",
        },
        {
          prop: "benCreateTime",
          label: "创建时间",
        },
      ],
      formType: "", //表单类型 dragForm:拖拽表单 composeForm:工艺组合表单   designForm:定制表单
      // k-form-build 数据
      dynamicData: {},
      tableName: "",
      defaultValue: {},
      jsonData: {},
      // 拖拽数据
      taskInfo: {},
      groupKey: "",
      subCount: {},
      tableCount: {},
      subTableName: "",

      // 弹窗表单渲染数据
      formData: {},
      backExceptionTaskList: ["GY06"], //特殊回退表单组件列表
      nodeLogList: [], //节点日志列表
    };
  },
  computed: {
    newColumn() {
      if (this.queryParams.taskProcessState == "3") {
        return [
          {
            prop: "bepTaskKey",
            label: "任务编号",
          },
          {
            prop: "bepTaskProcessName",
            label: "任务名称",
          },
          // {
          //   prop: "bepTaskProcessType",
          //   label: "任务流程类型",
          // },
          {
            prop: "bepTaskProcessState",
            label: "任务流程状态",
          },
          {
            prop: "benCreateBy",
            label: "创建人",
          },
          {
            prop: "benCreateTime",
            label: "创建时间",
          },
        ];
      } else {
        return this.columns;
      }
    },
  },
  mounted() {
    this.getList();
  },
  methods: {
    // 审批回调
    async approveHandler(row) {
      console.log(row);
      this.row = row;
      let {
        benTaskNodeFormKey,
        benTaskNodeFormType,
        bepTaskPlanKey,
        bepTaskKey,
        benTaskNodeKey,
        bepTaskNodeKey,
        benTaskProcessKey,
        benmTaskAutomaticScriptTriggerType,
        bepTaskNodeNextKey,
      } = row;
      // 新的运行逻辑
      let payLoad = {
        taskNodeKey: benTaskNodeKey,
        taskProcessKey: benTaskProcessKey,
        // taskAutomaticScriptTriggerType: benmTaskAutomaticScriptTriggerType,
        taskPlanKey: bepTaskPlanKey,
      };
      let res = await getProcessNodeFormTemplate(payLoad);
      if (res.code == 200) {
        if (res.data[0]?.template?.mainForm) {
          //表单组
          this.transformDataFormat(res.data[0].template);
          this.tableName =
            res.data[0].template.mainForm.showTemplate.dfTableName;
          console.log(this.formList);
        } else {
          this.formList = res.data;
          this.tableName = res.data[0].template.dfTableName;
        }

        this.nodeLogList = row.nodeLog.slice(1);
        this.show = true;
      } else {
        this.$message.error("网络异常,请稍后再试");
      }
    },
    // 将表单组数据转换成符合单个表单的数据格式
    transformDataFormat(data) {
      let { mainForm, subFormList } = data;
      this.formList = [];
      let showValue = mainForm.showValue[0];
      if (showValue) {
        mainForm.showTemplate.resultMap = mainForm.showValue;
      }
      this.formList.push({
        template: mainForm.showTemplate,
        tableName: mainForm.mainFormTable,
      });
      if (subFormList && subFormList.length > 0) {
        subFormList.forEach((item) => {
          let showValue = item.showValue[0];
          if (showValue) {
            item.showTemplate.resultMap = mainForm.showValue;
          }
          this.formList.push({
            template: item.showTemplate,
            tableName: item.formItem?.split(".")?.[0],
          });
        });
      }
    },
    toDetail(row) {
      console.log(row);
      let { bepTaskPlanKey, benTaskNodeKey, benTaskProcessKey } = row;
      window.sessionStorage.setItem("oaRow", JSON.stringify(row));
      let theLastNode = this.getTheLastNode(row.bepTaskProcessXmlContent);
      this.$router.push({
        path: "/processMange/detail",
        query: {
          taskNodeKey:
            row.bepTaskProcessState == 3 ? theLastNode : benTaskNodeKey,
          taskProcessKey: benTaskProcessKey,
          taskPlanKey: bepTaskPlanKey,
        },
      });
    },
    // 获取最后一个节点的nodekey   最后一个非结束节点
    getTheLastNode(xmlStr) {
      let xmlObj = xmlStr2XmlObj(xmlStr);
      let nodeSequence = getNodeSequence(xmlObj);
      console.log(nodeSequence);
      return nodeSequence[nodeSequence.length - 2]?.nodeId;
    },
    // 获取列表数据
    getList() {
      listApproveLog({ ...this.queryParams, taskName: this.queryString }).then(
        (res) => {
          if (res.code == 200) {
            this.tableData = res.rows.map((item) => item.resultMap);
            this.total = res.total;
            console.log(this.tableData);
          } else {
            this.$message.error("网络异常,请稍后再试");
          }
        }
      );
    },
    // 获取字典对应label
    getDictLabel(value, dictLsit = []) {
      return dictLsit.find((item) => {
        return item.value == value;
      })?.label;
    },
    // xml字符串转xml对象
    xmlStr2XmlObj(xmlStr) {
      var xmlObj = {};
      if (document.all) {
        var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
        xmlDom.loadXML(xmlStr);
        xmlObj = xmlDom;
      } else {
        xmlObj = new DOMParser().parseFromString(xmlStr, "text/xml");
      }
      return xmlObj;
    },
    // 获取下一个节点的nodekey
    getNextNodeKey(nodeKey, xmlStr) {
      let xmlObj = this.xmlStr2XmlObj(xmlStr);
      let nodeSequence = getNodeSequence(xmlObj);
      return nodeSequence.find((item) => item.nodeId == nodeKey) || {};
    },
    // 确认审批回调
    async confirmHandler() {
      let { benTaskNodeKey, bepTaskProcessXmlContent, implementationName } =
        this.row;
      let { nodeId, nextNodeId } = this.getNextNodeKey(
        benTaskNodeKey,
        bepTaskProcessXmlContent
      );
      let res = await this.$refs.approveRef.getformInfo();
      if (!res.flag) return;
      // 准备审批数据
      let payLoad = {
        taskProcessKey: this.row.bepTaskKey, //当前任务流程编码
        taskNodeKey: nodeId, //当前执行节点唯一编码
        nextNodeKey: nextNodeId, //下一节点编码
        implementationName: this.row.benmTaskAutomaticScriptTriggerType, //当前节点绑定的脚本名
        // taskProcessXmlContent: this.row.bepTaskProcessXmlContent, //当前流程xml
        tableName: this.tableName,
        // formDataMap: JSON.stringify(res.data), //自定义表单组件收集的表单数据
        taskNodeType: this.row.benTaskNodeType,
        ...res.data,
      };
      let fileXML = new File(
        [this.row.bepTaskProcessXmlContent],
        this.row.bepTaskKey + ".bpmn",
        {
          type: "text/bpmn",
        }
      );
      const subformData = new FormData();
      subformData.append("fileXML", fileXML);
      for (let key in payLoad) {
        subformData.append(key, payLoad[key] == null ? "" : payLoad[key]);
      }
      let result = await processNodeExecutionApproval(subformData);
      console.log(result);
      if (result.code == 200) {
        this.$message.success("审批成功");
        this.show = false;
        this.getList();
      } else {
        this.$message.error("审批失败");
      }
    },
    // 取消审批回调
    async cancelHandler(row) {
      console.log(row);
      // 先获取tableName
      let {
        benTaskNodeKey,
        bepTaskProcessXmlContent,
        implementationName,
        bepTaskPlanKey,
        benTaskProcessKey,
      } = row;
      let { nodeId, nextNodeId } = this.getNextNodeKey(
        benTaskNodeKey,
        bepTaskProcessXmlContent
      );
      // let payLoad = {
      //   taskNodeKey: benTaskNodeKey,
      //   taskProcessKey: benTaskProcessKey,
      //   // taskAutomaticScriptTriggerType: benmTaskAutomaticScriptTriggerType,
      //   taskPlanKey: bepTaskPlanKey,
      // };
      // 准备审批数据
      let payLoad = {
        taskProcessKey: row.bepTaskKey, //当前任务流程编码
        taskNodeKey: nodeId, //当前执行节点唯一编码
        nextNodeKey: nextNodeId, //下一节点编码
        implementationName: row.benmTaskAutomaticScriptTriggerType, //当前节点绑定的脚本名
        // taskProcessXmlContent: this.row.bepTaskProcessXmlContent, //当前流程xml
        tableName: this.tableName,
        // formDataMap: JSON.stringify(res.data), //自定义表单组件收集的表单数据
        taskNodeType: row.benTaskNodeType,
      };
      let fileXML = new File(
        [row.bepTaskProcessXmlContent],
        row.bepTaskKey + ".bpmn",
        {
          type: "text/bpmn",
        }
      );
      const subformData = new FormData();
      subformData.append("fileXML", fileXML);
      for (let key in payLoad) {
        subformData.append(key, payLoad[key] == null ? "" : payLoad[key]);
      }
      this.$confirm("确认取消吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        let result = await revokeApplication(subformData);
        if (result.code == 200) {
          this.$message.success("取消成功");
          this.getList();
        } else {
          this.$message.error("取消失败");
        }
      });
    },
    // 取消审批按钮  显示与隐藏
    isShowCancel(row) {
      if (row.bepTaskProcessState == 3) {
        return false;
      }
      this.cancelShow = !this.cancelShow;
    },

    //重置查询参数
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        taskName: "",
        taskProcessState: "0",
        taskProcessType: 1,
      };
      this.getList();
    },
    // 打印测试
    printTest() {
      // receiptDocuments({}, "print");
      qrCodeList({}, "print");
    },
  },
};
</script>

<style scoped lang="scss">
.process-mange-wrap {
  background-color: #f2f3f8;
  padding: 20px;

  .col {
    background-color: #fff;
    border-right: 1px solid #ebedf2;
    /* margin-right: 3px; */
    .statistic-wrap {
      /* // height: 70px; */
      box-sizing: border-box;
      display: flex;
      align-items: center;
      padding: 10px 17px;
      justify-content: space-between;

      .discription {
        display: flex;
        flex-direction: column;

        .title {
          line-height: 20px;
          font-size: 18px;
          font-weight: 700;
          margin-bottom: 5px;
        }

        .sub-title {
          font-size: 14px;
        }
      }

      .data {
        font-size: 20px;
        font-weight: 700;
      }
    }
  }

  .main-area {
    margin-top: 30px;
    box-shadow: 0 1px 15px 1px rgb(69 65 78 / 8%);
    background-color: #fff;

    .show-header {
      border-bottom: 1px solid #ebedf2;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0px 20px 0px 20px;
      height: 70px;

      /* .header {
      } */

      .search-list {
        display: flex;

        .search-tab {
          margin-right: 20px;

          .btn-list-two {
            margin-left: 10px;
          }
        }
      }
    }

    .show-body {
      padding: 25px;
    }
  }
}
</style>
