<!--
 * @Author: ysh
 * @Date: 2024-01-03 09:23:11
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-05-29 14:27:58
-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:deployment:add']">发起流程</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:deployment:remove']">删除</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="myProcessList" border @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column label="流程状态" align="center" prop="finishTime" width="100">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.finishTime == null" size="mini">进行中</el-tag>
          <el-tag type="success" v-if="scope.row.finishTime != null" size="mini">已完成</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="流程编号" align="center" prop="procInsId" :show-overflow-tooltip="true" /> -->
      <el-table-column label="流程名称" align="center" prop="procDefName" :show-overflow-tooltip="true" />
      <el-table-column label="标题" align="center" prop="title" />
      <!-- <el-table-column label="流程类别" align="center" prop="category" width="100px" /> -->
      <!-- <el-table-column label="流程版本" align="center" width="80px">
        <template slot-scope="scope">
          <el-tag size="medium">v{{ scope.row.procDefVersion }}</el-tag>
        </template>
</el-table-column> -->
      <el-table-column label="提交时间" align="center" prop="createTime" width="180" />
      <el-table-column label="耗时" align="center" prop="duration" width="180" />
      <el-table-column label="当前节点" align="center" prop="taskName" />
      <el-table-column label="待办人" align="center">

        <template slot-scope="scope">
          <label v-if="scope.row.assigneeName">
            {{ scope.row.assigneeName }}
            <el-tag type="info" size="mini">{{ scope.row.assigneeDeptName }}</el-tag></label>
          <!--          <label v-if="scope.row.candidate">{{scope.row.candidate}}</label>-->
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button @click="handleFlowRecord(scope.row)" type="text" size="small">办理进度</el-button>
          <el-button @click="handleFlowNote(scope.row)" type="text" size="small">表单信息</el-button>
          <!-- <el-button @click="handleStop(scope.row)" type="text" size="small">取消申请</el-button> -->
          <el-button @click="handleDelete(scope.row)" style="color:#F56C6C" type="text" size="small"
            :disabled="beDeleted(scope.row)" v-hasPermi="['system:deployment:remove']">取消流程</el-button>
        </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="title" :visible.sync="open" width="400px" append-to-body>
      <progress-tree :definitionList="definitionList" @confirm="handleStartProcess"
        @close="open = false"></progress-tree>
    </el-dialog>
    <el-dialog title="流程进度" :visible.sync="detailsOpen" append-to-body width="600px">
      <el-scrollbar style="height: 600px;">
        <RowDetail :rows="clickRow"></RowDetail>
      </el-scrollbar>
    </el-dialog>

    <el-dialog title="表单信息" :visible.sync="formOpen" append-to-body width="80%">
      <conditionDisplay :passingParam="passingParam"></conditionDisplay>
    </el-dialog>
  </div>
</template>

<script>
import { getDeployment, delDeployment, addDeployment, updateDeployment, exportDeployment, flowRecord } from "@/api/flowable/finished";
import { todoList } from "@/api/flowable/todo";
import { myProcessList, stopProcess } from "@/api/flowable/process";
import { listDefinition } from "@/api/flowable/definition";
import { getNextFlowNodeByStart } from "@/api/flowable/todo";
import { definitionStart, flowXmlAndNode } from "@/api/flowable/definition";
import { Snowflake } from '@/utils/snowFlake.js';
import RowDetail from './send/rowDetail.vue';
import ProgressTree from './progressTree.vue';
import { parseTime } from "@/utils/ruoyi";
import { getProcessVariables } from "@/api/flowable/definition";
import conditionDisplay from '@/views/flowable/form/components/conditionDisplay.vue';
import { deleteResources } from "@/utils/deleteResource";
import { listPerformance } from "@/api/oa/performance/performance";
import { listProject } from '@/api/oa/project/project';
export default {
  name: "Deploy",
  components: {
    RowDetail,
    ProgressTree,
    conditionDisplay
  },
  data() {
    return {
      projectList: [],
      // 遮罩层
      loading: true,
      processLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      processTotal: 0,
      // 我发起的流程列表数据
      myProcessList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 详情弹出框
      detailsOpen: false,
      formOpen: false,
      src: "",
      definitionList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        name: null,
        category: null,
        key: null,
        tenantId: null,
        deployTime: null,
        derivedFrom: null,
        derivedFromRoot: null,
        parentDeploymentId: null,
        engineVersion: null
      },
      // 查询参数
      queryProcessParams: {
        pageNum: 1,
        pageSize: 9999,
        name: null,
        category: null,
        key: null,
        tenantId: null,
        deployTime: null,
        derivedFrom: null,
        derivedFromRoot: null,
        parentDeploymentId: null,
        engineVersion: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 当前点击的行数据
      clickRow: {},
      passingParam: {},
      pathRoute: [
        {
          name: '借款审批',
          path: '/applyForm/borrow'
        },
        {
          name: '用车审批',
          path: '/applyForm/carApply'
        },
        {
          name: '设备审批',
          path: '/applyForm/deviceApply'
        },
        {
          name: '项目结算',
          path: '/applyForm/settleApply'
        }
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询流程定义列表 */
    getList() {
      this.loading = true;
      myProcessList(this.queryParams).then(response => {
        this.myProcessList = response.data.records;
        this.myProcessList.sort((a, b) => {
          // 如果有结束时间，则返回1，表示a应该排在b之后  
          if (a.finishTime) return 1;
          // 如果b有结束时间，则返回-1，表示a应该排在b之前  
          if (b.finishTime) return -1;
          // 如果都没有结束时间，则返回0，表示它们的顺序不变  
          return 0;
        })
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        category: null,
        key: null,
        tenantId: null,
        deployTime: null,
        derivedFrom: null,
        derivedFromRoot: null,
        parentDeploymentId: null,
        engineVersion: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleProcessQuery() {
      this.queryProcessParams.pageNum = 1;
      this.listDefinition();
    },
    /** 重置按钮操作 */
    resetProcessQuery() {
      this.resetForm("queryProcessForm");
      this.handleProcessQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.procInsId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 排序
    handleSortChange({ column, prop, order }) {
      if (prop === 'finishTime') {
        this.myProcessList.sort((a, b) => {
          // 如果有结束时间，则排在后面  
          if (a.finishTime && !b.finishTime) return 1;
          // 如果没有结束时间，则排在前面  
          if (!a.finishTime && b.finishTime) return -1;
          // 如果都有或都没有结束时间，则保持原有顺序（或根据其他规则排序）  
          return 0;
        })
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "发起流程";
      this.listDefinition();
    },
    listDefinition() {
      listDefinition(this.queryProcessParams).then(response => {
        this.definitionList = response.data.records;
        this.processTotal = response.data.total;
        this.processLoading = false;
      });
    },
    /**  发起流程申请 */
    async handleStartProcess(row) {
      if (row.name == "绩效审批") {
        let deptId = this.$store.getters.deptId;
        let reportTime = parseTime(new Date(), '{y}-{m}')
        let res = await listPerformance({ reportDept: deptId, reportTime });
        if (res.total >= 1) {
          let reporter = this.getUserName(res.rows[0].reporter)
          this.$message.error('本月部门已发起过绩效审批，发起人：' + reporter + '，请勿再次发起。')
          return
        }
      }
      let formId = new Snowflake(1n, 1n, 0n).nextId().toString();
      getNextFlowNodeByStart({ deploymentId: row.deploymentId, variables: { formId: formId } }).then(res => {
        let data = res.data;
        // debugger
        if (data.dataType === 'dynamic' && row.name != '项目预算') {
          if (data.type === 'assignee') { // 指定人员
            this.checkSendUser = true;
            this.checkType = "single";
          } else if (data.type === 'candidateUsers') {  // 候选人员(多个)
            this.checkSendUser = true;
            this.checkType = "multiple";
          } else if (data.type === 'candidateGroups') { // 指定组(所属角色接收任务)
            this.checkSendRole = true;
          } else { // 会签
            // 流程设计指定的 elementVariable 作为会签人员列表
            this.multiInstanceVars = data.vars;
            this.checkSendUser = true;
            this.checkType = "multiple";
          }
          this.taskOpen = true;
          this.taskTitle = "选择任务接收";
        } else {
          const variables = {};
          const formData = {};
          formData.disabled = true;
          formData.formBtns = false;
          formData.formId = formId
          if (row.id) {
            variables.variables = formData;
            let routePath = this.getRoutePath(row);
            if (row.name == '项目预算') {
              variables.approval = this.$store.getters.userId;
              formData.formId = row.projectId;
            }
            // 启动流程并将表单数据加入流程变量
            definitionStart(row.id, JSON.stringify(variables)).then(res => {
              this.$modal.msgSuccess(res.msg);
              let procInstanceId = res.data;
              todoList({
                pageNum: 1,
                pageSize: 99999999, processInsId: procInstanceId
              }).then(toDoRes => {
                let records = toDoRes.data.records;
                if (records.length == 1) {
                  records = records[0]
                }
                if (row.name == '项目预算') {
                  this.open = false;
                }
                this.$router.push({
                  path: routePath,
                  query: {
                    procInsId: records.procInsId,
                    executionId: records.executionId,
                    deployId: records.deployId,
                    taskId: records.taskId,
                    taskName: records.taskName,
                    startUser: records.startUserName + '-' + records.startDeptName,
                    formId: formData.formId,
                    procDefName: records.procDefName
                  }
                })
              })
            })
          }
        }
      })
    },
    getRoutePath(row) {
      let path;
      for (let p of this.publicData.pathRoute) {
        if (p.name == row.name) {
          path = p.path
          break
        } else {
          path = '/flowable/task/todo/detail/index'
        }
      }
      return path
    },
    /**  取消流程申请 */
    handleStop(row) {
      const params = {
        instanceId: row.procInsId
      }
      stopProcess(params).then(res => {
        this.$modal.msgSuccess(res.msg);
        this.getList();
      });
    },
    /** 流程流转记录 */
    handleFlowRecord(row) {
      // this.$router.push({
      //   path: '/flowable/task/myProcess/detail/index',
      //   query: {
      //     procInsId: row.procInsId,
      //     deployId: row.deployId,
      //     taskId: row.taskId
      //   }
      // })
      this.clickRow = row;
      this.detailsOpen = true;
    },
    // 表单信息
    handleFlowNote(row) {
      getProcessVariables(row.taskId).then(res => {
        if (res.data) {
          this.passingParam = row
          this.passingParam.formId = res.data.formId
          this.formOpen = true
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDeployment(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改流程定义";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDeployment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeployment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.procInsId || this.ids;// 暂不支持删除多个流程
      this.$confirm('取消流程将删除对应数据，是否确定取消流程？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        getProcessVariables(row.taskId).then(res => {
          if (res.data) {
            let delId = res.data.formId;
            this.deleteDataByUrl(row.procDefName, delId)
          }
          return delDeployment(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("流程取消成功");
        })
      })
    },
    deleteDataByUrl(procDefName, id) {
      return deleteResources(procDefName, id)
    },
    // 子流程不可以删除
    beDeleted(row) {
      if (row.procDefName == '技术方案' || row.procDefName == '安全交底' || row.procDefName == '技术交底' || row.finishTime != null) {
        return true
      } else if (row.procDefName == '项目流转' && row.taskName != '项目登记') {
        return true
      } else {
        return false
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有流程定义数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return exportDeployment(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    }
  }
};
</script>
