<template>
  <div>
    <div ref="handle">
      <el-dialog
        :visible.sync="dialogVisible"
        :fullscreen="true"
        :title="tenderName"
        custom-class="el-dialog__body-p0"
        append-to-body
        @close="handleCancel"
      >
        <el-form ref="form" :model="form" label-width="140px">
          <el-scrollbar
            class="scrollbar"
            :class="{'viewHeightShowHandleAudit' : isShowHandleAudit==='00',
                     'viewHeightShowBtn':routePathStatus==='02',
                     'viewHeight':isShowHandleAudit==='01'}"
          >
            <router-view ref="workView" class="p8" />
          </el-scrollbar>
          <!--审批信息-->
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>审批信息</span>
            </div>
            <div class="p8">
              <flowAuditList :biz-id="bizId" flow-type="01" />
            </div>
            <template v-if="isShowHandleAudit==='00'">
              <!--工作流选择下一节点组件-->
              <processNextNod-com
                ref="processNode"
                @getActModeUser="getActModeUser"
                @isGateway="isGateway"
                @conditionExpression="conditionExpression"
                @processNodeData="processNodeData"
              />
              <el-form-item label="批复意见">
                <el-input v-model="form.comment" type="textarea" />
              </el-form-item>
            </template>
          </el-card>
          <el-row v-if="isShowHandleAudit==='00' || routePathStatus==='02'" type="flex" class="row-bg m24-0" justify="center">
            <template v-if="isShowHandleAudit==='00'">
              <el-button v-if="informId===''" :loading="confirmLoading" type="primary" @click="handleAgree">
                同意
              </el-button>
              <el-button v-if="currentSteps !=='0' && informId===''" :loading="confirmLoading" type="danger" @click="handleDisagree">
                驳回
              </el-button>
              <el-button @click="handleCancel">
                关闭
              </el-button>
            </template>
            <!--办结进入查看显示关闭按钮-->
            <template v-if="routePathStatus==='02'">
              <el-button @click="handleCancel">
                关闭
              </el-button>
            </template>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
    <!--工作流流程节点/获取审核用户-->
    <depart-dialog
      ref="departDialog"
      @isSingleUser="isSingleUser"
      @processInitData="processInitData"
      @submit="submit"
    />
  </div>
</template>

<script>
/* api*/
import { completeTask } from '@/api/work/work'
import { getActModeUserByNodeIdProcessDefinitionKey } from '@/api/work/work'
/* 组件*/
import processNextNodeCom from '@views/work/processNextNodeCom'
import departDialog from '@views/work/depart-dialog'
import flowAuditList from './flowAudit-list'
/* 混入公共方法*/
import { workCommonMixins } from '@views/work/mixins/workCommonMixins'
import { workCommonGroup } from '../mixins/workCommonGroup'

export default {
  components: {
    'processNextNod-com': processNextNodeCom,
    'depart-dialog': departDialog,
    flowAuditList // 审核信息组件
  },
  mixins: [workCommonMixins, workCommonGroup],
  data() {
    return {
      confirmLoading: false, // 控制按钮重复点击Loding
      dialogVisible: true, // 弹框是否打开状态
      currentSteps: '', // 是否显示驳回
      routePathStatus: this.$route.query.routePathStatus, // 办结进入查看详情
      tenderName: this.$route.query.tenderName, // 业务名称
      flag: '', // 同意驳回区分字段
      // 流程网关 nodeKey nodeValue信息
      nodeKeyValueInfo: {
        nodeKey: '',
        nodeValue: ''
      },
      // 批复意见
      form: {
        comment: ''
      },
      isCreateUser: '', // 是否指定人员01指定  00不指定
      isArtificial: '', // 是否00人工  01智能
      /* 地址栏取值*/
      processDefinitionId: this.$route.query.processDefinitionId,
      processDefinitionKey: this.$route.query.processDefinitionKey,
      processNodeCode: this.$route.query.processNodeCode, // 当前节点id
      gatewayValue: this.$route.query.gatewayValue, // 网关值
      isShowHandleAudit: this.$route.query.isCreateUser, // 根据是否指定创建人判断是否为审批驳回 01为驳回不显示审批操作 00显示
      taskId: this.$route.query.taskId, // 任务id
      processInstanceId: this.$route.query.processInstanceId,
      ruTaskId: this.$route.query.ruTaskId,
      businessKey: this.$route.query.businessKey,
      bizId: this.$route.query.bizId,
      informId: this.$route.query.informId
    }
  },
  created() {
    // 是否显示驳回
    this.currentSteps = sessionStorage.getItem('currentSteps')
  },
  mounted() {
    this.$nextTick(function() {
      // 初始化工作流选择下一节点
      if (this.$refs.processNode) {
        this.$refs.processNode.initNextTasks(this.taskId, this.processNodeCode, this.gatewayValue, this.processDefinitionId, this.processDefinitionKey)
      }
    })
  },
  destroyed() {
    sessionStorage.removeItem('routePathStatus')
    sessionStorage.removeItem('projectDriveBackType')
    sessionStorage.removeItem('bizId')
  },
  methods: {
    // 同意/驳回保存接口
    submit(passNode) {
      this.confirmLoading = true
      new Promise((resolve, reject) => {
        /**
         * 使用promise进行转接 是为解决提交之前，如果还有其他操作 则先执行业务操作再执行工作流提交
         * @param {resolve} function 执行成功
         * @param {reject} function 执行失败
         * */
        // flag === 'ok' 提交
        if (this.flag === 'ok' && this.$refs.workView.beforeWorkSubmit) {
          this.$refs.workView.beforeWorkSubmit(resolve, reject)
        } else {
          resolve()
        }
      }).then(() => {
        const params = {
          taskId: this.taskId,
          ruTaskId: this.ruTaskId,
          processInstanceId: this.processInstanceId,
          comment: this.form.comment,
          flag: this.flag,
          ...this.processInitDto,
          ...passNode,
          ...this.nodeKeyValueInfo
        }
        // 提交时
        if (params.flag === 'ok') {
          params.comment = params.comment || '同意'
        }
        completeTask(params).then(res => {
          const data = res.data
          if (data.success) {
            this.confirmLoading = false
            this.$message.success(data.msg)
            this.handleCancel() // 关闭页面
          } else {
            this.confirmLoading = false
            this.$message.error(data.msg || '提交失败')
          }
        }).catch(() => {
          this.confirmLoading = false
        })
        this.confirmLoading = false
      }).catch(() => {
        this.confirmLoading = false
      })
    },
    // 操作同意前的判断（校验是否人工|| 智能）
    beforeAgreedVerify() {
      // 网关人工 && 智能校验选择节点
      if (this.isArtificial === '00' && this.gatewayType === '01') {
        // 校验是否选择节点
        if (!this.$refs.processNode.validate()) {
          return // 校验是否选择流程
        }
      }
      // 网关
      if (this.gatewayType === '01') {
        // 网关节点key value取值
        this.nodeKeyValueInfo.nodeKey = this.processNode.nodeKey
        this.nodeKeyValueInfo.nodeValue = this.processNode.nodeValue
      }
    },
    // 同意
    handleAgree() {
      // 网关人工 智能校验
      this.beforeAgreedVerify()
      this.$confirm('确认同意?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        this.flag = 'ok'
        this.handleAgreeConfiguration()
      }).catch(() => {
      })
    },
    // 点击同意根据是否指定创建人，人工智能判断
    handleAgreeConfiguration() {
      // 网关节点
      if (this.passNode.gatewayType === '01') {
        // 网关 processNode为选择的节点信息
        if (this.passNode.isCreateUser === '00') {
          this.$refs.departDialog.getUserDepart(this.passNode)// 审核人信息
        } else {
          this.submit(this.passNode)
        }
      } else { // 正常节点
        // 正常节点
        // 没有网关并且不是结束节点  passNode 传值为通过节点信息
        // 同意最后一个节点
        if (this.passNode.nodeId.indexOf('end') !== -1) {
          this.submit(this.passNode)
        } else {
          /* 同意会提交两次*/
          // if (this.passNode.isCreateUser === '00') {
          //   this.$refs.departDialog.getUserDepart(this.passNode)// 审核人信息
          // } else {
          //   this.submit(this.passNode)
          // }
          // 获取配置
          this.getActModeUserConfig(this.passNode)
        }
      }
    },
    // 驳回
    handleDisagree() {
      if (!this.form.comment) {
        this.$message.warning('请先填写批复意见')
        return
      }
      this.$confirm('确认驳回?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        this.flag = ''
        this.handleDisagreeConfiguration()
      }).catch(() => {
      })
    },
    // 点击驳回根据是否指定创建人，人工智能判断
    handleDisagreeConfiguration() {
      // 正常节点
      if (this.noPassNode.gatewayType === '00') {
        // 没有网关并且不是结束节点  noPassNode 传值为通过节点信息
        // 驳回最后一个节点
        if (this.noPassNode.nodeId.indexOf('end') !== -1 || this.noPassNode.isCreateUser === '01') {
          this.submit(this.noPassNode)
        } else {
          // 获取配置
          this.submit(this.noPassNode)
        }
      } else {
        if (this.noPassNode.nodeId.indexOf('end') !== -1 || this.noPassNode.isCreateUser === '01') {
          this.submit(this.passNode)
        } else {
          this.submit(this.passNode)
          // this.$refs.departDialog.getUserDepart(this.passNode) // 获取审核人信息
        }
      }
    },
    // 工作流流程节点/根据processDefinitionId和节点id 查询当前配置
    getActModeUserConfig(paramsNodeId) {
      getActModeUserByNodeIdProcessDefinitionKey(paramsNodeId.nodeId, paramsNodeId.processDefinitionKey)
        .then(res => {
          const { data } = res.data
          this.isCreateUser = data.isCreateUser // 是否指定人员01指定  00不指定
          this.isArtificial = data.isArtificial // 是否人工 智能
          // 指定人员
          if (this.isCreateUser === '01') {
            this.submit(paramsNodeId)
          } else {
            this.$refs.departDialog.getUserDepart(paramsNodeId) // 获取审核人信息
          }
        }).catch(() => {

        })
    },
    // 关闭
    handleCancel() {
      const routePathStatus = sessionStorage.getItem('routePathStatus') // 工作流处理 00桌面进入 01待办列表进入
      let path = ''
      // 桌面进入
      if (routePathStatus === '00') {
        path = '/home'
      }
      // 待办进入
      if (routePathStatus === '01') {
        path = '/work/todo'
      }
      // 办结进入
      if (routePathStatus === '02') {
        path = '/work/done'
      }
      this.$router.push({
        path: path
      })
      this.dialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
  /deep/.el-dialog.is-fullscreen{
    .el-dialog__body{
      .viewHeightShowHandleAudit{
        height: calc(100vh - 224px - 38px);
      }
      .viewHeightShowBtn{
        height: calc(100vh - 80px  - 38px);
      }
      .viewHeight{
        height: calc(100vh  - 38px);
      }
    }
  }
</style>
