<template>
  <basic-container>
    <avue-affix id="avue-view"
                :offset-top="116">
      <div class="header">
        <avue-title :value="process.processDefinitionName"></avue-title>
      </div>
    </avue-affix>
    <el-tabs v-model="activeName">
      <el-tab-pane label="申请信息"
                   name="first">
        <el-card shadow="never">
          <div ref="printBody">
            <avue-form v-if="option && option.column && option.column.length > 0"
                       v-model="form"
                       ref="form"
                       :option="option">
            </avue-form>
          </div>
        </el-card>
        <el-card shadow="never"
                 style="margin-top: 20px"
                 v-if="process.status == 'todo'">
          <avue-form v-model="examineForm"
                     ref="examineForm"
                     :option="examineOption">
          </avue-form>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="流转信息"
                   name="second">
        <el-card shadow="never"
                 style="margin-top: 5px;">
          <el-row type="flex"
                  class="row-bg">
            <el-timeline>
              <template v-for="item in flow">
                <el-timeline-item v-if="item.historyActivityType != 'sequenceFlow'"
                                  :key="item.id"
                                  :timestamp="item.endTime || item.createTime"
                                  placement="top">
                  <el-card shadow="never">
                    <p>{{item.assigneeName}} 在 [{{item.createTime}}] 开始处理 [{{item.historyActivityName}}] 环节</p>
                    <p v-if="item.historyActivityDurationTime">任务历时 [{{item.historyActivityDurationTime}}]</p>
                    <p v-if="item.comment">批复意见: [{{item.comment}}]</p>
                    <p v-if="item.endTime">结束时间: [{{item.endTime}}]</p>
                  </el-card>
                </el-timeline-item>
              </template>
            </el-timeline>
          </el-row>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="流程跟踪"
                   name="third">
      </el-tab-pane>
    </el-tabs>
    <template v-if="activeName == 'third'">
      <el-card v-if="process && process.xml"
               shadow="never"
               style="margin-top: 5px;">
        <wf-design ref="bpmn"
                   style="height: 500px;"
                   :options="bpmnOption"></wf-design>
      </el-card>
    </template>
    <template v-if="process.status == 'todo'">
      <div style="height: 120px;"></div>
      <el-row class="foot-item avue-affix"
              id="avue-view">
        <el-button v-if="buttonList.find(b => b.key == 'wf_pass')"
                   type="success"
                   size="medium"
                   v-loading="submitLoading"
                   @click="handleCompleteTask(true)">通过</el-button>
        <el-button v-if="buttonList.find(b => b.key == 'wf_reject')"
                   type="danger"
                   size="medium"
                   v-loading="submitLoading"
                   @click="handleCompleteTask(false)">驳回</el-button>
        <el-button v-if="buttonList.find(b => b.key == 'wf_transfer')"
                   type="warning"
                   size="medium"
                   v-loading="submitLoading"
                   @click="handleUserSelect('transfer')">转办</el-button>
        <el-button v-if="buttonList.find(b => b.key == 'wf_delegate')"
                   type="warning"
                   size="medium"
                   v-loading="submitLoading"
                   @click="handleUserSelect('delegate')">委托</el-button>
        <el-button v-if="buttonList.find(b => b.key == 'wf_print')"
                   type="warning"
                   size="medium"
                   v-loading="submitLoading"
                   @click="handlePrint()">打印</el-button>
        <!-- <el-button type="warning"
                   size="medium"
                   v-loading="submitLoading"
                   @click="handleSelect()">选人</el-button> -->
      </el-row>
    </template>
    <user-select ref="user-select"
                 :select-type="selectType"
                 @onClose="handleClose"
                 @onConfirm="handleConfirm"></user-select>
  </basic-container>
</template>

<script>
import { detail, completeTask, transferTask, delegateTask } from '@/api/plugin/workflow/process'
import userSelect from './user-select'

import { mapGetters } from 'vuex'
import Print from '../../util/print'

export default {
  components: { userSelect },
  computed: {
    ...mapGetters(['tag', 'userInfo']),
  },
  watch: {
    '$route.params.params': {
      handler(val) {
        if (val) {
          const param = JSON.parse(Buffer.from(val, 'base64').toString())
          const { taskId, processInsId } = param
          if (taskId && processInsId) this.getDetail(taskId, processInsId)
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      activeName: 'first',
      form: {},
      option: {
        menuBtn: false,
      },
      examineForm: {},
      examineOption: {
        menuBtn: false,
        column: [{
          label: '批复意见',
          prop: 'comment',
          type: 'textarea',
          span: 24,
        }, {
          label: '抄送人',
          prop: '$copyUser',
          placeholder: '请选择 抄送人',
          readonly: true,
          append: '➕',
          span: 24,
          event: {
            click: () => {
              this.$refs['user-select'].visible = true
              this.selectType = 'checkbox'
              this.userSelectType = 'copy'
            }
          }
        }, {
          label: '指定审批人',
          prop: '$assignee',
          placeholder: '请选择 下一级审批人，如不选择则使用默认处理人，驳回时无效',
          readonly: true,
          span: 24,
          event: {
            click: () => {
              this.$refs['user-select'].visible = true
              this.selectType = 'radio'
              this.userSelectType = 'assignee'
            }
          }
        }]
      },
      process: {},
      flow: [],
      bpmnOption: {
        mode: 'view'
      },
      vars: [],
      submitLoading: false,
      buttonList: [],
      watermarkText: '', //水印文字
      userSelectType: '', // transfer转办 delegate委托
      selectType: 'radio'
    }
  },
  created() {
    this.watermarkText = this.userInfo.user_name + " " + this.userInfo.real_name
  },
  methods: {
    getDetail(taskId, processInsId) {
      detail({ taskId, processInsId }).then(res => {
        const { process, form, flow, button } = res.data.data
        const { variables, status, xml } = process

        let { allForm, taskForm } = form
        if (allForm) {
          const option = eval('(' + allForm + ')')
          option.menuBtn = false
          if (status != 'todo') option.detail = true
          else {
            const arr = []
            const vars = []
            taskForm.forEach(task => {
              const column = option.column.find(c => c.prop == task.id)
              if (task.readable && column) {
                if (!task.writable) {
                  column.readonly = true
                  column.disabled = true
                } else vars.push(column.prop)
              }
              arr.push(column)
            })
            option.column = arr
            this.vars = vars
          }

          this.option = option
          this.form = variables
          this.process = process
          this.flow = flow
          this.buttonList = button

          const flows = []
          flow.forEach(f => {
            const ff = {
              id: f.historyActivityId
            }
            if (f.historyActivityType == 'sequenceFlow') ff.class = "lineWarn"
            else ff.class = "nodeWarn"
            flows.push(ff)
          })

          this.bpmnOption = {
            mode: 'view',
            xml,
            flows
          }
        }
      })
    },
    handleCompleteTask(pass) {
      this.submitLoading = true

      const { comment, copyUser, assignee } = this.examineForm
      if (!pass && !comment) {
        this.$message.error("请填写批复意见")
        this.submitLoading = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const variables = {}
          this.vars.forEach(v => {
            if (v != 'comment' && this.form[v]) variables[v] = this.form[v]
          })

          const { taskId, processInstanceId, processDefinitionName } = this.process
          const params = {
            taskId, processInstanceId, processDefinitionName, pass,
            comment, copyUser, assignee, variables
          }

          completeTask(params).then(() => {
            this.$message.success("处理成功")
            this.$store.commit('DEL_TAG', this.tag)
            this.$router.push("/plugin/workflow/process/todo")
          }).catch(() => {
            this.submitLoading = false
          })
        }
      })
    },
    handlePrint() { //打印
      // this.watermark({ text: this.watermarkText })
      Print(this.$refs.printBody)
    },
    handleUserSelect(type) { //选人
      this.$refs['user-select'].visible = true
      this.userSelectType = type
    },
    handleClose() { //关闭选人
      this.$refs['user-select'].visible = false
    },
    handleConfirm(id, name) { //选人回调
      const type = this.userSelectType
      const param = {
        taskId: this.process.taskId,
        assignee: id
      }
      if (type == 'transfer') {
        transferTask(param).then(() => { // 转办
          this.$message.success("转办成功")
          this.$store.commit('DEL_TAG', this.tag)
          this.$router.push("/plugin/workflow/process/todo")
        })
      } else if (type == 'delegate') { // 委托
        delegateTask(param).then(() => {
          this.$message.success("委托成功")
          this.$store.commit('DEL_TAG', this.tag)
          this.$router.push("/plugin/workflow/process/todo")
        })
      } else if (type == 'copy') { // 抄送
        this.examineForm.copyUser = id
        this.examineForm.$copyUser = name
      } else if (type == 'assignee') { // 指定下一步审批人
        this.examineForm.assignee = id
        this.examineForm.$assignee = name
      }
      this.$refs['user-select'].visible = false
    },
  }
}
</script>

<style lang="scss" scoped>
.header {
  width: 100%;
  height: 50px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px 10px 0;
}
.foot-item {
  position: fixed;
  bottom: 0;
  margin-left: -20px;
  // right: 0;
  z-index: 101;
  width: 98%;
  height: 66px;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  -webkit-transition: 0.3s;
  transition: 0.3s;
  -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>