<template>
  <div class="app-container">
    <el-tabs tab-position="top" :value="processed === true ? 'approval' : 'form'">

      <el-tab-pane label="任务办理" name="approval" v-if="processed === true">
        <el-card class="box-card" shadow="hover" v-if="taskFormOpen">
          <div slot="header" class="clearfix">
            <span>填写表单</span>
          </div>
        </el-card>
        <el-card class="box-card" shadow="hover">
          <div slot="header" class="clearfix">
            <span>审批流程</span>
          </div>
          <el-row>
            <el-col :span="20" :offset="2">
              <el-form ref="taskForm" :model="taskForm" :rules="rules" label-width="120px">
                <el-form-item label="审批意见" prop="comment">
                  <el-input type="textarea" :rows="5" v-model="taskForm.comment" placeholder="请输入 审批意见" />
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-row :gutter="10" type="flex" justify="center" >
            <el-col :span="1.5">
              <el-button icon="el-icon-circle-check" type="success" @click="handleComplete">通过</el-button>
            </el-col>
            <el-col :span="1.5">
              <!--              <el-button icon="el-icon-chat-line-square" type="primary" @click="handleDelegate">委派</el-button>-->
            </el-col>
            <el-col :span="1.5">
              <!--              <el-button icon="el-icon-thumb" type="success" @click="handleTransfer">转办</el-button>-->
            </el-col>
            <el-col :span="1.5">
              <el-button icon="el-icon-refresh-left" type="warning" @click="handleReturn">退回</el-button>
            </el-col>
            <el-col :span="1.5">
              <!--              <el-button icon="el-icon-circle-close" type="danger" @click="handleReject">拒绝</el-button>-->
            </el-col>
          </el-row>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="表单信息" name="form">
        <div>
          <div class="main" v-loading="loading">
            <div class="">
              <div class="">
                <el-card style="">
                  <el-row>
                    <div>
                      <h1>差旅费报销申请单</h1>
                    </div>
                  </el-row>
                </el-card>
                <el-card>
                  <div class="header">
                    基本信息
                  </div>
                  <el-divider></el-divider>
                  <div>
                    <el-form :form="form" label-width="100px" :rules="rules">
                      <el-form-item label="报销描述：" prop="remark">
                        <el-input type="textarea" v-model="form.remark"  :rows="5" disabled></el-input>
                      </el-form-item>

                      <el-row>
                        <el-col :span="8">
                          <el-form-item label="开始时间：" prop="startTime">
                            <el-date-picker
                              v-model="form.startTime"
                              align="right"
                              type="date"
                              placeholder="选择日期"
                              value-format="yyyy-MM-dd"
                              disabled
                            >
                            </el-date-picker>
                          </el-form-item>

                          <el-form-item label="出差天数：" prop="tripDays">
                            <el-input type="number" v-model="form.tripDays"placeholder="请输入出差天数" disabled></el-input>
                          </el-form-item>

                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="结束时间：" prop="endTime" >
                            <el-date-picker
                              v-model="form.endTime"
                              align="right"
                              type="date"
                              placeholder="选择日期"
                              value-format="yyyy-MM-dd"
                              disabled
                            >
                            </el-date-picker>
                          </el-form-item>
                          <el-form-item label="报销总额：" prop="cost">
                            <el-input  v-model="form.cost" placeholder="请输入报销总额" disabled>
                              <template slot="append">元</template>
                            </el-input>
                          </el-form-item>

                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="关联项目：" prop="projectId">
                            <el-select v-model="form.projectId" filterable placeholder="请选择" disabled>
                              <el-option
                                v-for="item in projectList"
                                :key="item.projectId"
                                :label="item.projectName"
                                :value="item.projectId">
                              </el-option>
                            </el-select>
                          </el-form-item>

                          <el-form-item label="票据总数：" prop="detailNumber">
                            <el-input  v-model="form.detailNumber" placeholder="请输入票据总数" disabled>
                              <template slot="append">张</template>
                            </el-input>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-form>

                    <el-divider></el-divider>
                    <div style="font-weight: 900;display: flex;">
                      <div style="width: 50%">
                        最终报销金额：
                        <span style="color: red">{{form.cost===""?'请输入金额':form.cost}}</span>
                      </div>

                      <div>
                        大写：<span style="color: red">{{numberToCNY(form.cost)}}</span>
                      </div>
                    </div>
                  </div>
                </el-card>

                <el-card>
                  报销明细
                  <el-divider></el-divider>
                  <div>
                    <el-table
                      :data="detailList"
                      style="width: 100%"
                      border
                      stripe
                      v-loading="loading"
                      highlight-current-row
                    >
                      <el-table-column label="序号" width="80" type="index"></el-table-column>
                      <el-table-column label="报销类型">
                        <template slot-scope="scope">
                          <dict-tag :options="dict.type.claim_detail_type" :value="scope.row.claimType"/>
                        </template>
                      </el-table-column>
                      <el-table-column label="开始时间">
                        <template slot-scope="scope">
                          <span>{{ parseTime(scope.row.beginTime, '{y}-{m}-{d}') }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="结束时间">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
                        </template>
                      </el-table-column>

                      <el-table-column label="入住地点" prop="lodgingAddress"></el-table-column>
                      <el-table-column label="款项金额" prop="cost"></el-table-column>
                    </el-table>
                  </div>
                </el-card>
                <el-card>
                  票据留存
                  <el-divider></el-divider>
                  <div style="display: flex">
                    <div style="margin-right: 20px">
                      上传票据:
                    </div>
                    <div>
                      <!-- 文件列表 -->
                      <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
                        <li :key="file.fileUrl" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in form.fileList">
                          <el-link :href="`${baseUrl}${file.fileUrl}`" :underline="false" target="_blank">
                            <span class="el-icon-document"> {{ getFileName(file.fileUrl) }} </span>
                          </el-link>
                        </li>
                      </transition-group>
                    </div>
                  </div>


                </el-card>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane >

      <el-tab-pane label="流转记录" name="record">

        <div class="title-record">流程标题：{{processTitleValue}}</div>

        <el-card class="box-card" shadow="never">
          <el-col :span="20" :offset="2">
            <div class="block">
              <el-timeline>
                <el-timeline-item v-for="(item,index) in historyProcNodeList" :key="index" :icon="setIcon(item.endTime)" :color="setColor(item.endTime)">
                  <p style="font-weight: 700">{{ item.activityName }}</p>
                  <el-card v-if="item.activityType === 'startEvent'" class="box-card" shadow="hover">
                    {{ item.assigneeName }} 在 {{ item.createTime }} 发起流程
                  </el-card>
                  <el-card v-if="item.activityType === 'userTask'" class="box-card" shadow="hover">
                    <el-descriptions :column="5" :labelStyle="{'font-weight': 'bold'}">
                      <el-descriptions-item label="实际办理">{{ item.assigneeName || '-'}}</el-descriptions-item>
                      <!--                      <el-descriptions-item label="候选办理">{{ item.candidate || '-'}}</el-descriptions-item>-->
                      <el-descriptions-item label="接收时间">{{ item.createTime || '-'}}</el-descriptions-item>
                      <el-descriptions-item label="办结时间">{{ item.endTime || '-' }}</el-descriptions-item>
                      <el-descriptions-item label="耗时">{{ item.duration || '-'}}</el-descriptions-item>
                    </el-descriptions>
                    <div v-if="item.commentList && item.commentList.length > 0">
                      <el-divider content-position="left">
                        <el-tag :type="approveTypeTag(item.commentList[0].type)" size="mini">{{ commentType(item.commentList[0].type) }}</el-tag>
                        <el-tag type="info" effect="plain" size="mini">{{ item.commentList[0].time }}</el-tag>
                      </el-divider>
                      <span>{{ item.commentList[0].fullMessage }}</span>
                      <!--                      <div v-for="(comment, index) in item.commentList" :key="index">
                                              <el-divider content-position="left">
                                                <el-tag :type="approveTypeTag(comment.type)" size="mini">{{ commentType(comment.type) }}</el-tag>
                                                <el-tag type="info" effect="plain" size="mini">{{ comment.time }}</el-tag>
                                              </el-divider>
                                              <span>{{ comment.fullMessage }}</span>
                                            </div>-->
                    </div>
                  </el-card>
                  <el-card v-if="item.activityType === 'endEvent'" class="box-card" shadow="hover">
                    {{ item.createTime }} 结束流程
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-col>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="流程跟踪" name="track">
        <el-card class="box-card" shadow="never">
          <process-viewer :key="`designer-${loadIndex}`" :style="'height:' + height" :xml="xmlData"
                          :finishedInfo="finishedInfo" :allCommentList="historyProcNodeList"
          />
        </el-card>
      </el-tab-pane>


    </el-tabs>




  </div>
</template>

<script>
import { detailProcess } from '@/api/workflow/process'
import Parser from '@/utils/generator/parser'
import { complete, delegate, transfer, rejectTask, returnList, returnTask } from '@/api/workflow/task'
import { selectUser, deptTreeSelect } from '@/api/system/user'
import ProcessViewer from '@/components/ProcessViewer'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import Treeselect from '@riophae/vue-treeselect'
import {getOaClaim} from "../../../api/oa/claim";
import {numberToCNY} from "../../../utils/currencyFormatter";
import {listProject} from "../../../api/oa/project";

export default {
  name: "WorkDetail",
  dicts:['claim_detail_type'],
  components: {
    ProcessViewer,
    Parser,
    Treeselect
  },
  props: {},
  computed: {
    commentType() {
      return val => {
        switch (val) {
          case '1': return '通过'
          case '2': return '退回'
          case '3': return '驳回'
          case '4': return '委派'
          case '5': return '转办'
          case '6': return '终止'
          case '7': return '撤回'
        }
      }
    },
    approveTypeTag() {
      return val => {
        switch (val) {
          case '1': return 'success'
          case '2': return 'warning'
          case '3': return 'danger'
          case '4': return 'primary'
          case '5': return 'success'
          case '6': return 'danger'
          case '7': return 'info'
        }
      }
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      height: document.documentElement.clientHeight - 205 + 'px;',
      // 模型xml数据
      loadIndex: 0,
      xmlData: undefined,
      detailList:[],
      finishedInfo: {
        finishedSequenceFlowSet: [],
        finishedTaskSet: [],
        unfinishedTaskSet: [],
        rejectedTaskSet: []
      },
      historyProcNodeList: [],
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      userLoading: false,
      // 用户表格数据
      userList: null,
      deptProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined
      },
      total: 0,
      // 遮罩层
      loading: true,
      taskForm: {
        comment: "", // 意见内容
        procInsId: "", // 流程实例编号
        taskId: "",// 流程任务编号
        copyUserIds: "", // 抄送人Id
        vars: "",
        targetKey: ""
      },
      rules: {
        comment: [{required: true, message: '请输入审批意见', trigger: 'blur'}],
      },
      currentUserId: null,
      variables: [], // 流程变量数据
      taskFormOpen: false,
      taskFormData: {}, // 流程变量数据
      processFormList: [], // 流程变量数据
      processTitleValue: null,
      formOpen: false, // 是否加载流程变量数据
      returnTaskList: [],  // 回退列表数据
      processed: false,
      returnTitle: null,
      returnOpen: false,
      rejectOpen: false,
      rejectTitle: null,
      userData: {
        title: '',
        type: '',
        open: false,
      },
      copyUser: [],
      nextUser: [],
      userMultipleSelection: [],
      userDialogTitle: '',
      userOpen: false,
      form:{}
    };
  },
  created() {
    this.getClaimDetail();

  },
  methods: {
    numberToCNY,
    getProjectList(){
      let params = {
        pageSize:999,
        pageNum:1
      }
      listProject(params).then(response => {
        this.projectList = response.rows
      })
    },
    /** 获取报销单详情 */
    getClaimDetail() {
      getOaClaim(this.$route.params.claimId).then(res => {
        this.form = res.data;
        this.detailList = res.data.detailList
        this.initData();
        this.loading=false
      })
    },

    /** 初始化流程数据 */
    initData() {
      this.taskForm.procInsId = this.form.procInsId

      this.processed = this.$route.query && eval(this.$route.query.processed || false);
      // 流程任务重获取变量表单
      this.getProcessDetails(this.form.procInsId);
      this.loadIndex = this.taskForm.procInsId;
    },
    /** 查询部门下拉树结构 */
    getTreeSelect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询用户列表 */
    getList() {
      this.userLoading = true;
      selectUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.toggleSelection(this.userMultipleSelection);
        this.userLoading = false;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    setIcon(val) {
      if (val) {
        return "el-icon-check";
      } else {
        return "el-icon-time";
      }
    },
    setColor(val) {
      if (val) {
        return "#2bc418";
      } else {
        return "#b3bdbb";
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.userMultipleSelection = selection
    },
    toggleSelection(selection) {
      if (selection && selection.length > 0) {
        this.$nextTick(() => {
          selection.forEach(item => {
            let row = this.userList.find(k => k.userId === item.userId);
            this.$refs.userTable.toggleRowSelection(row);
          })
        })
      } else {
        this.$nextTick(() => {
          this.$refs.userTable.clearSelection();
        });
      }
    },
    // 关闭标签
    handleClose(type, tag) {
      let userObj = this.userMultipleSelection.find(item => item.userId === tag.id);
      this.userMultipleSelection.splice(this.userMultipleSelection.indexOf(userObj), 1);
      if (type === 'copy') {
        this.copyUser = this.userMultipleSelection;
        // 设置抄送人ID
        if (this.copyUser && this.copyUser.length > 0) {
          const val = this.copyUser.map(item => item.id);
          this.taskForm.copyUserIds = val instanceof Array ? val.join(',') : val;
        } else {
          this.taskForm.copyUserIds = '';
        }
      } else if (type === 'next') {
        this.nextUser = this.userMultipleSelection;
        // 设置抄送人ID
        if (this.nextUser && this.nextUser.length > 0) {
          const val = this.nextUser.map(item => item.id);
          this.taskForm.nextUserIds = val instanceof Array ? val.join(',') : val;
        } else {
          this.taskForm.nextUserIds = '';
        }
      }
    },
    /** 流程变量赋值 */
    handleCheckChange(val) {
      if (val instanceof Array) {
        this.taskForm.values = {
          "approval": val.join(',')
        }
      } else {
        this.taskForm.values = {
          "approval": val
        }
      }
    },
    //获取的表单信息、流转记录、流程跟踪信息
    getProcessDetails(procInsId) {
      const params = {procInsId: procInsId, taskId: null}
      detailProcess(params).then(res => {
        const data = res.data;
        this.xmlData = data.bpmnXml;
        this.processFormList = data.processFormList;
        this.historyProcNodeList = data.historyProcNodeList;
        this.finishedInfo = data.flowViewer;
        this.formOpen = true
        this.processTitleValue = data.processFormList[0].fields[0].__config__.defaultValue;
      })
    },
    onSelectCopyUsers() {
      this.userMultipleSelection = this.copyUser;
      this.onSelectUsers('添加抄送人', 'copy')
    },
    onSelectNextUsers() {
      this.userMultipleSelection = this.nextUser;
      this.onSelectUsers('指定审批人', 'next')
    },
    onSelectUsers(title, type) {
      this.userData.title = title;
      this.userData.type = type;
      this.getTreeSelect();
      this.getList()
      this.userData.open = true;
    },
    /** 通过任务 */
    handleComplete() {
      // 校验表单
      const taskFormRef = this.$refs.taskFormParser;
      const isExistTaskForm = taskFormRef !== undefined;
      // 若无任务表单，则 taskFormPromise 为 true，即不需要校验
      const taskFormPromise = !isExistTaskForm ? true : new Promise((resolve, reject) => {
        taskFormRef.$refs[taskFormRef.formConfCopy.formRef].validate(valid => {
          valid ? resolve() : reject()
        })
      });
      const approvalPromise = new Promise((resolve, reject) => {
        this.$refs['taskForm'].validate(valid => {
          valid ? resolve() : reject()
        })
      });
      Promise.all([taskFormPromise, approvalPromise]).then(() => {
        if (isExistTaskForm) {
          this.taskForm.variables = taskFormRef[taskFormRef.formConfCopy.formModel]
        }
        //执行是否同意的任务
        complete(this.taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.goBack();
        });
      })
    },
    /** 委派任务 */
    handleDelegate() {
      this.$refs["taskForm"].validate(valid => {
        if (valid) {
          this.userData.type = 'delegate';
          this.userData.title = '委派任务'
          this.userData.open = true;
          this.getTreeSelect();
        }
      })
    },
    /** 转办任务 */
    handleTransfer() {
      this.$refs["taskForm"].validate(valid => {
        if (valid) {
          this.userData.type = 'transfer';
          this.userData.title = '转办任务';
          this.userData.open = true;
          this.getTreeSelect();
        }
      })
    },
    /** 拒绝任务 */
    handleReject() {
      this.$refs["taskForm"].validate(valid => {
        if (valid) {
          const _this = this;
          this.$modal.confirm('拒绝审批单流程会终止，是否继续？').then(function () {
            return rejectTask(_this.taskForm);
          }).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.goBack();
          });
        }
      });
    },
    changeCurrentUser(val) {
      this.currentUserId = val.userId
    },
    /** 返回页面 */
    goBack() {
      // 关闭当前标签页并返回上个页面
      this.$tab.closePage(this.$route)
      this.$router.back()
    },
    /** 接收子组件传的值 */
    getData(data) {
      if (data) {
        const variables = [];
        data.fields.forEach(item => {
          let variableData = {};
          variableData.label = item.__config__.label
          // 表单值为多个选项时
          if (item.__config__.defaultValue instanceof Array) {
            const array = [];
            item.__config__.defaultValue.forEach(val => {
              array.push(val)
            })
            variableData.val = array;
          } else {
            variableData.val = item.__config__.defaultValue
          }
          variables.push(variableData)
        })
        this.variables = variables;
      }
    },
    submitUserData() {
      let type = this.userData.type;
      if (type === 'copy' || type === 'next') {
        if (!this.userMultipleSelection || this.userMultipleSelection.length <= 0) {
          this.$modal.msgError("请选择用户");
          return false;
        }
        let userIds = this.userMultipleSelection.map(k => k.userId);
        if (type === 'copy') {
          // 设置抄送人ID信息
          this.copyUser = this.userMultipleSelection;
          this.taskForm.copyUserIds = userIds instanceof Array ? userIds.join(',') : userIds;
        } else if (type === 'next') {
          // 设置下一级审批人ID信息
          this.nextUser = this.userMultipleSelection;
          this.taskForm.nextUserIds = userIds instanceof Array ? userIds.join(',') : userIds;
        }
        this.userData.open = false;
      } else {
        if (!this.taskForm.comment) {
          this.$modal.msgError("请输入审批意见");
          return false;
        }
        if (!this.currentUserId) {
          this.$modal.msgError("请选择用户");
          return false;
        }
        this.taskForm.userId = this.currentUserId;
        if (type === 'delegate') {
          delegate(this.taskForm).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.goBack();
          });
        }
        if (type === 'transfer') {
          transfer(this.taskForm).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.goBack();
          });
        }
      }

    },
    /** 可退回任务列表 */
    handleReturn() {
      this.$refs['taskForm'].validate(valid => {
        if (valid) {
          this.returnTitle = "退回流程";
          returnList(this.taskForm).then(res => {
            this.returnTaskList = res.data;
            this.taskForm.values = null;
            this.returnOpen = true;
          })
        }
      });

    },

    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    /** 提交退回任务 */
    submitReturn() {
      this.$refs["taskForm"].validate(valid => {
        if (valid) {
          if (!this.taskForm.targetKey) {
            this.$modal.msgError("请选择退回节点！");
          }
          returnTask(this.taskForm).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.goBack()
          });
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.button-new-tag {
  margin-left: 10px;
}

.title-record {
  font-size: 16px;
  padding: 10px 0;
  color: #1ab394
}


</style>
