<!--  -->
<template>
  <el-dialog title="审批信息" :visible.sync="dialogVisible" width="850px" :before-close="handleCancel">
    <div v-loading="processInstanceLoading">
      <div class="start-msg">
        <div class="title-box"><span>申请人</span>：{{ startUserObj.nickname || '-'}}</div>
        <div class="title-box"><span>所属部门</span>：{{ startUserObj.deptName || '-'}}</div>
        <div class="title-box"><span>创建时间</span>：{{ startUserObj.createTime || '-'}}</div>
      </div>
      <el-row>
        <el-col :span="24">
          <el-table stripe border :data="tasks" ref="tasks">
            <el-table-column label="审批人员" align="center" prop="assigneeUser">
              <template slot-scope="{row}">
                {{row.assigneeUser.nickname || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="所属部门" align="center" prop="assigneeUser">
              <template slot-scope="{row}">
                {{row.assigneeUser.deptName || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="审批意见" align="center" prop="reason">
              <template slot-scope="{row}">
                {{ row.reason || '-'  }}
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="reason">
              <template slot-scope="{row}">
                <el-tag :type="getTimelineItemType(row)"> {{getTimelineItemTypeStr(row) || '-' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="审批时间" align="center" prop="endTime">
              <template slot-scope="{row}">
                {{ parseTime(row.endTime) || '-'  }}
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <!-- 审批流程图 -->
      <el-row style="margin-top: 10px;">
        <el-col :span="24">
          <!-- 高亮流程图 -->
          <div slot="header" class="clearfix">
            <span class="el-icon-picture-outline">流程图 </span>
          </div>
          <my-process-viewer key="designer" v-model="bpmnXML" v-bind="bpmnControlForm" :activityData="activityList" :processInstanceData="processInstance" :taskData="tasks" />
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>
<script>
import { getProcessDefinitionBpmnXML } from "@/api/bpm/definition";
import { getProcessInstance } from "@/api/bpm/processInstance";
import { getActivityList } from "@/api/bpm/activity";
import { getTaskListByProcessInstanceId } from "@/api/bpm/task";
import store from "@/store";
import Vue from "vue";
import dayjs from 'dayjs';
import { parseTime } from "@/utils/ruoyi";
export default {
  name: '',
  props: {
    isOpen: Boolean,
    processInstanceId: [Number, String]
  },
  data() {
    return {
      startUserObj: {},
      dialogVisible: false,
      loading: false,
      activityList: [],
      // 审批记录
      tasksLoad: false,
      tasks: [],
      // 遮罩层
      processInstanceLoading: false,
      // 流程实例
      id: undefined, // 流程实例的编号
      processInstance: {},

      // 流程表单详情
      detailForm: {
        fields: []
      },
      runningTasks: [],
      // BPMN 数据
      bpmnXML: null,
      bpmnControlForm: {
        prefix: "flowable"
      },
    }
  },
  watch: {
    isOpen: {
      handler(val) {
        this.dialogVisible = val
        if (val) {
          this.processInstanceId && this.getDetail(this.processInstanceId)
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getTimelineItemTypeStr(item) {
      if (item.result === 1) {
        return '处理中';
      }
      if (item.result === 2) {
        return '通过';
      }
      if (item.result === 3) {
        return '驳回';
      }
      if (item.result === 4) {
        return '取消';
      }
      return '未知';
    },
    getTimelineItemType(item) {
      if (item.result === 1) {
        return 'primary';
      }
      if (item.result === 2) {
        return 'success';
      }
      if (item.result === 3) {
        return 'danger';
      }
      if (item.result === 4) {
        return 'info';
      }
      return '';
    },
    getDetail(id) {
      // 获得流程实例相关
      this.processInstanceLoading = true
      getProcessInstance(id).then(response => {
        if (!response.data) {
          this.$message.error('查询不到流程信息！');
          return;
        }
        // 设置流程信息
        this.processInstance = response.data;
        this.startUserObj = {
          ...(response.data.startUser || {}),
          createTime: response.data.createTime && parseTime(response.data.createTime) || '-'
        }
        //将业务表单，注册为动态组件
        const path = this.processInstance.processDefinition.formCustomViewPath;
        Vue.component("async-biz-form-component", function (resolve) {
          require([`@/views${path}`], resolve);
        });

        // 设置表单信息
        if (this.processInstance.processDefinition.formType === 10) {
          this.detailForm = {
            ...JSON.parse(this.processInstance.processDefinition.formConf),
            disabled: true, // 表单禁用
            formBtns: false, // 按钮隐藏
            fields: decodeFields(this.processInstance.processDefinition.formFields)
          }
          // 设置表单的值
          this.detailForm.fields.forEach(item => {
            const val = this.processInstance.formVariables[item.__vModel__]
            if (val) {
              item.__config__.defaultValue = val
            }
          });
        }

        // 加载流程图
        getProcessDefinitionBpmnXML(this.processInstance.processDefinition.id).then(response => {
          this.bpmnXML = response.data
        });
        // 加载活动列表
        getActivityList({
          processInstanceId: this.processInstance.id
        }).then(response => {
          this.activityList = response.data;
        });

        // 取消加载中
        // this.processInstanceLoading = false;
        // 获得流程任务列表（审批记录）
        this.runningTasks = [];
        this.auditForms = [];
        getTaskListByProcessInstanceId(id).then(response => {
          // 审批记录
          this.tasks = [];
          // 移除已取消的审批
          response.data.forEach(task => {
            if (task.result !== 4) {
              this.tasks.push(task);
            }
          });
          // 排序，将未完成的排在前面，已完成的排在后面；
          this.tasks.sort((a, b) => {
            // 有已完成的情况，按照完成时间倒序
            if (a.endTime && b.endTime) {
              return b.endTime - a.endTime;
            } else if (a.endTime) {
              return 1;
            } else if (b.endTime) {
              return -1;
              // 都是未完成，按照创建时间倒序
            } else {
              return b.createTime - a.createTime;
            }
          });

          // 需要审核的记录
          const userId = store.getters.userId;
          this.tasks.forEach(task => {
            if (task.result !== 1) { // 只有待处理才需要
              return;
            }
            if (!task.assigneeUser || task.assigneeUser.id !== userId) { // 自己不是处理人
              return;
            }
            this.runningTasks.push({ ...task });
            this.auditForms.push({
              reason: ''
            })
          });
          let newTasks = this.tasks.map(item => {
            return {
              ...item,
              result: this.getTimelineItemTypeStr(item),
              endTime: item.endTime ? dayjs(item.endTime).format('YYYY-MM-DD HH:ss:mm') : '-'
            }
          })
          this.$emit('onTasks', { tasks: newTasks || [], startUserObj: this.startUserObj })
          this.$emit('onSetId', (Array.isArray(this.runningTasks) && this.runningTasks.length ? this.runningTasks[this.runningTasks.length - 1] : {}).id)
          this.processInstanceLoading = false;
          // 取消加载中
          // this.tasksLoad = false;
        });
      });
    },
    handleCancel() {
      this.$emit('onCancel')
    },
    handleConfirm() {
      this.$emit('onCancel')
    },
  }
}

</script>
<style lang='scss' scoped>
.start-msg {
  display: flex;
  margin-bottom: 15px;
  font-size: 15px;
  span {
    font-size: 18px;
  }
  .title-box {
    margin-right: 10px;
  }
}
::v-deep .el-dialog__body {
  max-height: 70vh !important;
}
.my-process-designer {
  height: 500px;
}
</style>