<template>
<div>
  <h4 style="text-align:center">{{title}}</h4>

  <el-tabs type="border-card" v-model="taskSelectedTab" @tab-click="onTabChange">
    <el-tab-pane :key="1" label="表单信息" name="form-first">
      <component id="printForm" :status="status" :formReadOnly="formReadOnly" v-if="formType === '2'" :class="formReadOnly?'readonly':''" ref="form" :businessId="businessId" :is="form" @callBackFunc="callBackFunc" @changeLoading="changeLoading"></component>

      <PreviewForm  id="printForm"   v-if="formType !== '2'"  :processDefinitionId="procDefId" :edit="true" :taskFormData="taskFormData" ref="form"/>
    </el-tab-pane>
    <el-tab-pane :key="2" label="流程信息" v-if="procInsId"  name="form-second">
      <flow-time-line :historicTaskList="historicTaskList"/>
    </el-tab-pane>
    <el-tab-pane :key="3" label="流程图"  name="form-third">
       <el-card class="box-card"  shadow="hover">
          <div slot="header" class="clearfix">
            <span>流程图</span>
          </div>
          <flow-chart ref="chart1" v-if="procInsId" :processInstanceId="procInsId" />
          <flow-chart ref="chart2" v-if="!procInsId" :processDefId="procDefId" />
        </el-card>
    </el-tab-pane>
    <el-tab-pane :key="4" label="流转记录" v-if="procInsId" name="form-forth">
          <flow-step :historicTaskList="historicTaskList"/>
     </el-tab-pane>
    <el-tab-pane :key="5" label="入库修改历史" v-if="commonJS.isNotEmpty(wareHouseId)" name="form-sixth">
      <vxe-table
        ref="wareHouseTable"
        border="inner"
        size="mini"
        :key="222"
        max-height="1000px"
        class="vxe-table-element"
        :data="dataListHi">
        <vxe-column type="seq" width="60" title="序号"></vxe-column>
        <vxe-column min-width="120" align="center" title="修改类型" field="updateTradeType">
          <template v-slot="scope">
            <span v-if="commonJS.isNotEmpty(scope.row.updateTradeType)"> {{scope.row.updateTradeType}} </span>
            <span v-else> -- </span>
          </template>
        </vxe-column>
        <vxe-column min-width="160" align="center" title="修改商品" field="updateTradeName">
          <template v-slot="scope">
            <span v-if="commonJS.isNotEmpty(scope.row.updateTradeName)"> {{scope.row.updateTradeName}} </span>
            <span v-else> -- </span>
          </template>
        </vxe-column>
        <vxe-column min-width="160" align="center" title="修改人" field="updateUser">
          <template v-slot="scope">
            <span v-if="scope.row.endflag === '2'">(创建人) {{scope.row.updateUser}} </span>
            <span v-else>{{scope.row.updateUser}} </span>
          </template>
        </vxe-column>
        <vxe-column min-width="160" align="center" title="修改时间" field="createDate"></vxe-column>
        <vxe-column title="操作" width="150px" fixed="right" align="center">
          <template  slot-scope="scope">
            <el-button type="text" size="small" @click="hiDetail(scope.row)">修改详情</el-button>
          </template>
        </vxe-column>
      </vxe-table>
    </el-tab-pane>
    <el-tab-pane :key="6" label="领用退回历史" v-if="returnId" name="form-seventh">
      <vxe-table
        ref="returnTable"
        border="inner"
        :key="111"
        size="mini"
        class="vxe-table-element"
        max-height="1000px"
        :data="dataListHiCollect">
        <vxe-column type="seq" width="60" title="序号"></vxe-column>
        <vxe-column min-width="160" align="center" title="退回物品" field="returnGoods">
          <template v-slot="scope">
            <span v-if="commonJS.isNotEmpty(scope.row.returnGoods)"> {{scope.row.returnGoods}} </span>
            <span v-else> -- </span>
          </template>
        </vxe-column>
        <vxe-column min-width="160" align="center" title="退回申请人" field="returnUserName"></vxe-column>
        <vxe-column min-width="160" align="center" title="退回时间" field="createDate"></vxe-column>
        <vxe-column title="操作" width="150px" fixed="right" align="center">
          <template  slot-scope="scope">
            <el-button type="text" size="small" @click="hiDetailCollect(scope.row)">退回详情</el-button>
          </template>
        </vxe-column>
      </vxe-table>
    </el-tab-pane>
  </el-tabs>



<el-card style="margin-top:10px; padding-bottom:66px" v-if="!procInsId || taskId">
    <el-form size="small" :model="auditForm"  :loading="loading" ref="auditForm" label-width="120px">
      <el-col :span="16">
        <!--<el-form-item  v-if="!procInsId && isShow !== 'false'"  label="流程标题" prop="title">
          <el-input
            placeholder="请输入流程标题"
            v-model="title">
          </el-input>
      </el-form-item>
        <el-form-item  v-if="!procInsId && isShow === 'false'" label="流程标题" prop="title">
          <el-input
            placeholder="请输入流程标题"
            v-model="this.contractTitle">
          </el-input>
        </el-form-item>-->
      <el-form-item  v-if="taskId"  label="审批信息" prop="message">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入审批意见"
            v-model="auditForm.message">
          </el-input>
      </el-form-item>
    </el-col>
    <el-col :span="16">
      <el-form-item>
        <el-checkbox v-model="isCC">是否抄送</el-checkbox>
      </el-form-item>
    </el-col>
    <el-col :span="16">
      <el-form-item v-if="isCC"  :rules="[
              {required: true, message: '用户不能为空', trigger: 'blur'},
              {required: true, message: '用户不能为空', trigger: 'change'}
            ]"  prop="userIds" label="抄送给">
            <user-select :readonly="true" :value="auditForm.userIds"  @getValue='(value) => {auditForm.userIds=value}'>></user-select>
      </el-form-item>
    </el-col>
    <el-col :span="16">
      <el-form-item v-if="isShow === 'true'">
        <el-checkbox v-model="isAssign">指定下一步处理者(不设置就使用默认处理人)</el-checkbox>
      </el-form-item>
    </el-col>
    <el-col :span="16">
      <el-form-item v-if="isAssign"  :rules="[
              {required: true, message: '用户不能为空', trigger: 'blur'}
            ]"  prop="assignee" label="指定">
            <user-select :limit="1" :value="auditForm.assignee"  @getValue='(value) => {auditForm.assignee=value}'>></user-select>
      </el-form-item>
    </el-col>

   </el-form>
</el-card>

<div class="FlowFormFooter" v-if="!procInsId || taskId">

  <template v-for="(button, index) in buttons">
      <template v-if="button.isHide === '0'">
        <el-button type="primary"  v-if="button.code !== '_flow_print'"  :key="index" @click="submit(button, buttons)" :loading="loading"  v-noMoreClick plain>{{button.name}}</el-button>
        <el-button type="primary" v-if="button.code === '_flow_print'" v-print="printObj" :key="index" @click="submit(button, buttons)" :loading="loading" v-noMoreClick plain>{{button.name}}</el-button>
      </template>
  </template>
</div>
<task-back-nodes ref="taskBackNodes" @getBackTaskDefKey="back"/>
<user-select-dialog title="选择转办用户" ref="transferUserSelectDialog" :limit="1" @doSubmit="selectUsersToTransferTask"></user-select-dialog>
<user-select-dialog title="选择委派用户" ref="delegateUserSelectDialog" :limit="1" @doSubmit="selectUsersToDelateTask"></user-select-dialog>
<user-select-dialog title="选择加签用户" ref="addSignTaskUserSelectDialog" @doSubmit="selectUsersToAddSignTask"></user-select-dialog>
<WareHouseHi ref="wareHouseHi"></WareHouseHi>
<CollectReturnHi ref="collectReturnHi"></CollectReturnHi>
</div>
</template>

<script>
  // import FlowChart from '../modeler/FlowChart'
  import UserSelect from '@/components/userSelect'
  import PreviewForm from '@/views/modules/flowable/form/GenerateFlowableForm'
  import TaskBackNodes from '@/views/modules/flowable/components/TaskBackNodes'
  import FlowStep from '@/views/modules/flowable/components/FlowStep'
  import FlowTimeLine from '@/views/modules/flowable/components/FlowTimeLine'
  import UserSelectDialog from '@/components/userSelect/UserSelectDialog'
  import TaskService from '@/api/flowable/TaskService'
  import TaskDefExtensionService from '@/api/flowable/TaskDefExtensionService'
  import FormService from '@/api/flowable/FormService'
  import FlowCopyService from '@/api/flowable/FlowCopyService'
  import ProcessService from '@/api/flowable/ProcessService'
  import WorkContractForm2 from '@/views/modules/sys/workContract/WorkContractForm2'
  import NoticeService from '@/api/flowable/NoticeService'
  import WareHouseService from '@/api/materialManagement/WareHouseService'
  import WareHouseHi from '@/views/modules/materialManagement/wareHouse/WareHouseHi'
  import CollectService from '@/api/materialManagement/CollectService'
  import CollectReturnHi from '@/views/modules/materialManagement/collect/CollectReturnHiForm'
  const _import = require('@/router/import-' + process.env.NODE_ENV)
  export default {
    taskDefExtensionService: null,
    taskService: null,
    formService: null,
    flowCopyService: null,
    processService: null,
    noticeService: null,
    wareHouseService: null,
    collectService: null,
    created () {
      this.taskService = new TaskService()
      this.taskDefExtensionService = new TaskDefExtensionService()
      this.formService = new FormService()
      this.flowCopyService = new FlowCopyService()
      this.processService = new ProcessService()
      this.noticeService = new NoticeService()
      this.wareHouseService = new WareHouseService()
      this.collectService = new CollectService()
    },
    activated () {
      this.init()
      if (this.formType === '2') { // 读取外置表单
        if (this.formUrl === '/404') {
          this.form = null
          this.$message.info('没有关联流程表单!')
        } else {
          this.form = _import(`modules${this.formUrl}`)
        }
        if (this.status === 'reback') {
          this.reback()
        }
      } else { // 读取动态表单
        this.$nextTick(() => {
          if (this.formUrl === '/404') {
            this.$refs.form.createForm('')
          } else {
            this.$refs.form.createForm(this.formUrl)
          }
        })
        if (this.status === 'start') {
          // 读取启动表单配置
          this.formService.getStartFormData({processDefinitionId: this.procDefId}).then(({data}) => {
            this.taskFormData = data
          })
        } else {
          // 读取任务表单配置
          this.formService.getTaskFormData({taskId: this.taskId}).then(({data}) => {
            this.taskFormData = data
          })
        }
      }
       // 读取按钮配置
      // 先清除缓存按钮
      this.buttons = null
      if (this.status === 'start') {  // 送审
        this.buttons = [{code: '_flow_start', name: '启动', isHide: '0'}]
      } else if (this.status === 'startAndClose') { // 送审、关闭
        this.buttons = [{code: '_flow_start', name: '送审', isHide: '0'}, {code: '_flow_close', name: '关闭', isHide: '0'}]
      } else if (this.status === 'reapplyFlag') { // 重新申请、流程终止、关闭
        this.buttons = [{code: '_flow_reapply', name: '重新申请', isHide: '0'}, {code: '_flow_stop', name: '流程终止', isHide: '0'}, {code: '_flow_close', name: '关闭', isHide: '0'}]
      } else if (this.status === 'startAndHold') {  // 送审、暂存、关闭
        this.buttons = [{code: '_flow_start', name: '送审', isHide: '0'}, {code: '_flow_save', name: '暂存', isHide: '0'}, {code: '_flow_close', name: '关闭', isHide: '0'}]
      } else if (this.status === 'startAndCloseFiled') { // 送审、关闭
        this.buttons = [{code: '_flow_start', name: '送审', isHide: '0'}, {code: '_flow_close', name: '关闭', isHide: '0'}]
      } else if (this.status === 'startAndHoldFiled') {  // 送审、暂存、关闭
        this.buttons = [{code: '_flow_start', name: '送审', isHide: '0'}, {code: '_flow_save', name: '暂存', isHide: '0'}, {code: '_flow_close', name: '关闭', isHide: '0'}]
      } else if (this.status === 'startAndCloseBorrow') {
        this.buttons = [{code: '_flow_start', name: '送审', isHide: '0'}, {code: '_flow_close', name: '关闭', isHide: '0'}]
      } else if (this.status === 'reback') {
        this.buttons = [{code: '_flow_reback', name: '撤回', isHide: '0'}]
      } else if (this.status === 'agreeAndReject') {
        this.buttons = [{code: '_flow_agree', name: '同意', isHide: '0'}, {code: '_flow_reject', name: '驳回', isHide: '0'}]
        this.status = 'audit'
      } else if (this.procDefKey && this.taskDefKey) {
        // 读取按钮
        this.taskDefExtensionService.queryByDefIdAndTaskId({
          processDefId: this.procDefKey,
          taskDefId: this.taskDefKey
        }).then(({data}) => {
          data.flowButtonList.forEach(item => {
            if (item.code === '_flow_agree') {
              this.status = 'audit'
            }
          })
          this.buttons = data.flowButtonList
        })
      }
    // 读取历史任务列表
      if (this.procInsId) {
        this.taskService.historicTaskList(this.procInsId).then(({data}) => {
          this.historicTaskList = data
        })
      }
    },
    components: {
      UserSelect,
      UserSelectDialog,
      PreviewForm,
      TaskBackNodes,
      FlowStep,
      FlowTimeLine,
      WorkContractForm2,
      WareHouseHi,
      CollectReturnHi
    },
    watch: {
      isAssign (val) {
        if (!val) {
          this.assignee = null
        }
      },
      taskSelectedTab (val) {
        if (val === 'form-third') {
          if (this.procInsId) {
            this.$refs.chart1.init()
          } else {
            this.$refs.chart2.init()
          }
        }
      }
    },
    methods: {
      changeBusiness () {
        this.businessId = 'false'
        this.$refs.form.close()
      },
      init () {
        this.taskSelectedTab = 'form-first'
        this.procDefId = this.$route.query.procDefId
        this.procDefKey = this.$route.query.procDefKey
        this.formType = this.$route.query.formType
        this.formUrl = this.$route.query.formUrl
        this.taskId = this.$route.query.taskId
        this.taskDefKey = this.$route.query.taskDefKey
        this.status = this.$route.query.status
        this.title = this.$route.query.formTitle
        this.printObj.popTitle = this.title
        this.businessId = this.$route.query.businessId
        this.procInsId = this.$route.query.procInsId
        this.formReadOnly = this.$route.query.formReadOnly !== undefined && this.$route.query.formReadOnly !== 'false' && this.$route.query.formReadOnly !== false
        this.isCC = false
        this.isAssign = false
        this.auditForm.assignee = null
        this.auditForm.userIds = null
        this.auditForm.message = ''
        this.cUser = this.commonJS.isEmpty(this.$route.query.cUser) ? false : this.$route.query.cUser
        this.contractTitle = this.$route.query.contractTitle
        this.statusFlag = this.$route.query.statusFlag
        this.wareHouseId = this.$route.query.wareHouseId
        this.returnId = this.$route.query.returnId
        if (this.commonJS.isEmpty(this.$route.query.isShow)) {
          this.isShow = 'true'
        } else {
          this.isShow = this.$route.query.isShow
        }
        let _this = this
        // this.$nextTick(() => {
        //   try {
        //     _this.$refs.form.getKeyWatch(Math.random().toString())
        //   } catch (e) {
        //     console.log(e)
        //   }
        // })
        setTimeout(function () {
          try {
            _this.$refs.form.getKeyWatch(Math.random().toString())
          } catch (e) {
            console.log(e)
          }
        }, 500)
      },
      cc (procInsId) {
        if (this.isCC && this.auditForm.userIds) {
          this.$refs['auditForm'].validate((valid) => {
            if (valid) {
              this.flowCopyService.save({
                userIds: this.auditForm.userIds,
                procDefId: this.procDefId,
                procInsId: procInsId,
                procDefName: '',
                procInsName: this.title,
                taskName: ''
              })
            }
          })
        }
      },
      // 暂存草稿
      async save () {
        if (this.formType === '2') { // 外置表单
          this.$refs.form.saveForm(() => {
            this.$message.success('操作成功')
            // this.changeBusiness()
            this.businessId = 'false'
            this.$store.dispatch('tagsView/delView', {fullPath: this.$route.fullPath})
            this.$router.push(this.$route.query.routePath)
            this.$refs.form.close()
          })
        }
      },
      // 启动流程
      start (vars) {
        if (this.formType === '2') { // 外置表单
          this.$refs.form.startForm((businessTable, businessId, inputForm) => {
            vars = {...vars, ...inputForm}
            if (inputForm.procDefId) {
              this.procDefId = inputForm.procDefId
            }
            if (inputForm.procDefKey) {
              this.procDefId = inputForm.procDefKey
            }
            if (inputForm.title) {
              this.title = inputForm.title
            }
            if (inputForm.formTitle) {
              this.formTitle = inputForm.formTitle
            }
            let assignee = this.auditForm.assignee
            if (!this.commonJS.isEmpty(inputForm.assignee)) {
              assignee = inputForm.assignee
            }
            // console.log(this.procDefId)
            // console.log(this.procDefKey)
            this.taskService.start({
              procDefId: this.procDefId,
              procDefKey: this.procDefKey,
              businessTable: businessTable,
              businessId: businessId,
              ...vars,
              title: this.title,
              assignee: assignee
            }).then(({data}) => {
              this.$message.success('启动成功')
              this.changeBusiness()
              this.$refs.form.close()
              this.$store.dispatch('tagsView/delView', {fullPath: this.$route.fullPath})
              if (!this.commonJS.isEmpty(this.$route.query.routePath)) {
                this.$router.push(this.$route.query.routePath)
              } else {
                this.$router.push('/flowable/task/TodoList')
              }
              this.cc(data)
            })
          })
        } else { // 动态表单
          this.$refs.form.submitStartFormData({
            processDefinitionId: this.procDefId,
            ...vars,
            title: this.title,
            assignee: this.auditForm.assignee
          }, (data) => {
            this.changeBusiness()
            this.$refs.form.close()
            this.$store.dispatch('tagsView/delView', {fullPath: this.$route.fullPath})
            this.$router.push('/flowable/task/TodoList')
            this.cc(data)
          })
        }
      },
      // 同意
      async agree (vars) {
        vars = {...vars, agree: true}
        if (this.formType === '2') {
          this.commit(vars)
        }
      },
      // 重新申请
      reapply (vars) {
        vars = {...vars, agree: true}
        if (this.formType === '2') { // 外置表单
          let param = {
            num: this.$route.query.num,
            taskId: this.taskId,
            taskDefKey: this.taskDefKey,
            procInsId: this.procInsId,
            procDefId: this.procDefId,
            vars: vars,
            comment: this.auditForm,
            assignee: this.auditForm.assignee,
            cope: {
              userIds: this.auditForm.userIds,
              procDefId: this.procDefId,
              procInsId: '',
              procDefName: '',
              procInsName: this.title,
              taskName: ''
            }
          }
          this.$refs.form.reapplyForm((businessTable, businessId, inputForm) => {
            vars = {...vars, ...inputForm}
            console.log('param' + param)
            console.log('inputForm' + inputForm)
            if (inputForm.procDefId) {
              param.procDefId = inputForm.procDefId
            }
            let assignee = this.auditForm.assignee
            if (!this.commonJS.isEmpty(inputForm.assignee)) {
              assignee = inputForm.assignee
            }
            this.taskService.audit({
              taskId: this.taskId,
              taskDefKey: this.taskDefKey,
              procInsId: this.procInsId,
              procDefId: this.procDefId,
              vars: vars,
              comment: this.auditForm,
              assignee: assignee
            }).then(({data}) => {
              this.$message.success('提交成功')
              this.changeBusiness()
              this.$refs.form.close()
              // 我的通知
              let createDate = ''
              this.myNotice(data, this.procDefId, this.title, vars.userName, createDate)
              this.$store.dispatch('tagsView/delView', {fullPath: this.$route.fullPath})
              // this.$router.push('/flowable/task/TodoList')
              // this.cc(data)
              if (this.$route.query.routePath) {
                this.$router.push(this.$route.query.routePath)
              } else {
                var num = this.$route.query.num
                if (num === '2') {
                  this.$router.push('/sys/dashboard/workBench/Pending')
                  this.cc(data)
                } else if (num === '3') {
                  this.$router.push('/sys/dashboard/workBench/PendingList')
                  this.cc(data)
                } else {
                  this.$router.push('/flowable/task/TodoList')
                  this.cc(data)
                }
              }
            })
          }, param)
        } else { // 动态表单
          this.$refs.form.submitTaskFormData(vars, this.procInsId, this.taskId, this.auditForm.assignee, this.auditForm, (data) => {
            this.changeBusiness()
            this.$refs.form.close()
            this.$store.dispatch('tagsView/delView', {fullPath: this.$route.fullPath})
            // this.$router.push('/flowable/task/TodoList')
            // this.cc(data)
            if (this.$route.query.routePath) {
              this.$router.push(this.$route.query.routePath)
            } else {
              var num = this.$route.query.num
              if (num === '2') {
                this.$router.push('/sys/dashboard/workBench/Pending')
                this.cc(data)
              } else if (num === '3') {
                this.$router.push('/sys/dashboard/workBench/PendingList')
                this.cc(data)
              } else {
                this.$router.push('/flowable/task/TodoList')
                this.cc(data)
              }
            }
          })
        }
      },
      // Process_1667978088459 客户修改
      // Process_1668394732246 项目登记
      // Process_1668503117077 报告质控管理员审核
      // Process_1669014216650 报告签章-公章
      // Process_1669087010742 报告签章-公章+执业章
      // Process_1668677901585 项目报告归档
      // Process_1670486210438 报告复核
      // Process_1668759076824 报告作废申请
      // Process_1670548572652 报告作废归档
      // Process_1669700915383 合同登记纸质归档
      // Process_1669271524486 报销审批
      // Process_1669275081328 发票申请
      // Process_1669275380218 发票作废
      // Process_1672738002595 发起通知
      // Process_1662628133027 评估-合同登记新建
      // Process_1663743217785 评估-合同登记归档
      // Process_1664370362499 评估-项目登记流程
      // Process_1666169509264 评估-项目一级校审
      // Process_1666266316011 评估-项目二级校审
      // Process_1666266494837 评估-项目三级校审
      // Process_1666331430821 评估-报告签发审批
      // Process_1666332258192 评估-项目登记归档
      // Process_1665383385070 评估-报销申请
      // Process_1665628043339 评估-发票作废
      // Process_1665458731435 评估-发票申请
      // Process_1669961023358 物资管理-采购申请
      // Process_1672729521837 物资管理-领用申请  Process_1673513775015
      // Process_1673332958749 财务-报告签章-实体章  Process_1673513595904
      // Process_1673514092406 物资管理-入库修改
      // Process_1673600899831 物资管理-合同
      // Process_1673924346231 中审-报销审批
      // Process_1667894339167 会计-合同登记
      // Process_1678692643340 会计-项目报告归档-苏州分部
      // Process_1683767097901 物资管理-领用退回申请
      // 驳回
      reject (vars) {
        if (this.procDefId.includes('Process_1667978088459') ||
          this.procDefId.includes('Process_1668394732246') ||
          this.procDefId.includes('Process_1668503117077') ||
          this.procDefId.includes('Process_1669014216650') ||
          this.procDefId.includes('Process_1669087010742') ||
          this.procDefId.includes('Process_1668677901585') ||
          this.procDefId.includes('Process_1670486210438') ||
          this.procDefId.includes('Process_1668759076824') ||
          this.procDefId.includes('Process_1670548572652') ||
          this.procDefId.includes('Process_1669700915383') ||
          this.procDefId.includes('Process_1669271524486') ||
          this.procDefId.includes('Process_1669275081328') ||
          this.procDefId.includes('Process_1669275380218') ||
          this.procDefId.includes('Process_1672738002595') ||
          this.procDefId.includes('Process_1662628133027') ||
          this.procDefId.includes('Process_1663743217785') ||
          this.procDefId.includes('Process_1664370362499') ||
          this.procDefId.includes('Process_1666169509264') ||
          this.procDefId.includes('Process_1666266316011') ||
          this.procDefId.includes('Process_1666266494837') ||
          this.procDefId.includes('Process_1666331430821') ||
          this.procDefId.includes('Process_1666332258192') ||
          this.procDefId.includes('Process_1665383385070') ||
          this.procDefId.includes('Process_1665628043339') ||
          this.procDefId.includes('Process_1665458731435') ||
          this.procDefId.includes('Process_1669961023358') ||
          this.procDefId.includes('Process_1673513775015') ||
          this.procDefId.includes('Process_1673513595904') ||
          this.procDefId.includes('Process_1673514092406') ||
          this.procDefId.includes('Process_1673600899831') ||
          this.procDefId.includes('Process_1673924346231') ||
          this.procDefId.includes('Process_1667894339167') ||
          this.procDefId.includes('Process_1678692643340') ||
          this.procDefId.includes('Process_1683767097901')
        ) {
          console.log('进入新版驳回')
          this.$confirm(`确定驳回流程吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            if (this.formType === '2') {
              vars = {...vars, agree: false}
              // await this.commit(vars) // 驳回
              this.$refs.form.updateStatusById('reject', () => {
                this.taskService.audit({
                  taskId: this.taskId,
                  taskDefKey: this.taskDefKey,
                  procInsId: this.procInsId,
                  procDefId: this.procDefId,
                  vars: vars,
                  comment: this.auditForm,
                  assignee: this.auditForm.assignee
                }).then(({data}) => {
                  this.$message.success('提交成功')
                  this.changeBusiness()
                  this.$refs.form.close()
                  // 我的通知
                  let createDate = ''
                  this.myNotice(data, this.procDefId, this.title, vars.userName, createDate)
                  this.$store.dispatch('tagsView/delView', {fullPath: this.$route.fullPath})
                  // this.$router.push('/flowable/task/TodoList')
                  // this.cc(data)
                  if (this.$route.query.routePath) {
                    this.$router.push(this.$route.query.routePath)
                  } else {
                    var num = this.$route.query.num
                    if (num === '2') {
                      this.$router.push('/sys/dashboard/workBench/Pending')
                      this.cc(data)
                    } else if (num === '3') {
                      this.$router.push('/sys/dashboard/workBench/PendingList')
                      this.cc(data)
                    } else {
                      this.$router.push('/flowable/task/TodoList')
                      this.cc(data)
                    }
                  }
                })
              })
            }
          })
        } else {
          console.log('进入旧版驳回')
          this.$confirm(`确定驳回流程吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            if (this.formType === '2') {
              if (this.cUser === true || this.cUser === 'true') { // cUser为true则页面审核人为自定义多选，驳回时要将审核人重新定义一次
                await this.$refs.form.updateStatusById('reject', (businessTable, businessId, inputForm) => {
                  this.auditForm.candidateUserList = inputForm.assignee
                })
                setTimeout(() => {
                  this.taskService.backNodes(this.taskId).then(({data}) => {
                    let backNodes = data
                    if (backNodes.length > 0) {
                      let backTaskDefKey = backNodes[backNodes.length - 1].taskDefKey
                      this.back(backTaskDefKey)
                    }
                  })
                }, 100)
              } else {
                await this.$refs.form.updateStatusById('reject')
                this.taskService.backNodes(this.taskId).then(({data}) => {
                  let backNodes = data
                  if (backNodes.length > 0) {
                    let backTaskDefKey = backNodes[backNodes.length - 1].taskDefKey
                    this.back(backTaskDefKey)
                  }
                })
              }
            }
          })
        }
      },
      // 驳回至指定节点(节点是从0开始)
      rejectToPointNum (num) {
        this.$confirm(`确定驳回流程吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.taskService.backNodes(this.taskId).then(({data}) => {
            let backNodes = data
            if (backNodes.length > 0 && backNodes.length > num) {
              let backTaskDefKey = backNodes[num].taskDefKey
              this.back(backTaskDefKey)
            }
          })
        })
        if (this.formType === '2') {
          this.$refs.form.updateStatusById('reject')
        }
      },
      // 撤回
      reback () {
        this.$confirm(`确定撤回流程吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await this.$refs.form.updateStatusById('reback')
          this.taskService.backNodes(this.taskId).then(({data}) => {
            let backNodes = data
            this.changeBusiness()
            this.$store.dispatch('tagsView/delView', {fullPath: this.$route.fullPath})
            this.$router.push(this.$route.query.routePath)
            if (backNodes.length > 0) {
              let backTaskDefKey = backNodes[0].taskDefKey
              this.back(backTaskDefKey)
            }
            this.$refs.form.close()
          })
        })
      },
      // 驳回到任意节点
      turnBack () {
        this.$refs.taskBackNodes.init(this.taskId)
      },
      // 回退到任意节点
      back (backTaskDefKey) {
        this.taskService.back({
          taskId: this.taskId,
          backTaskDefKey: backTaskDefKey,
          ...this.auditForm
        }).then(({data}) => {
          this.$message.success('回退成功')
          this.changeBusiness()
          this.$refs.form.close()
          this.$store.dispatch('tagsView/delView', {fullPath: this.$route.fullPath})
          var num = this.$route.query.num
          if (num === '2') {
            this.$router.push('/sys/dashboard/workBench/Pending')
          } else if (num === '3') {
            this.$router.push('/sys/dashboard/workBench/PendingList')
          } else {
            this.$router.push('/flowable/task/TodoList')
          }
          this.cc(data)
        })
      },
      // 加签
      addMultiInstance () {
        // this.$refs.addSignTaskUserSelectDialog.init()
      },
      selectUsersToAddSignTask (users) {
        let userIds = users.map((user) => {
          return user.id
        }).join(',')
        this.taskService.addSignTask({taskId: this.taskId, userIds: JSON.stringify(userIds), comment: '', flag: false}).then(({data}) => {
          this.$message.success(data)
        })
      },
      // 减签
      delMultiInstance () {

      },
      // 转办
      transfer () {
        this.$refs.transferUserSelectDialog.init()
      },
      selectUsersToTransferTask (user) {
        this.taskService.transfer(this.taskId, user[0].id).then(({data}) => {
          this.$message.success(data)
          this.$router.push('/flowable/task/TodoList')
        })
      },
      // 委托
      delegate () {
        this.$refs.delegateUserSelectDialog.init()
      },
      selectUsersToDelateTask (user) {
        this.taskService.delegate(this.taskId, user[0].id).then(({data}) => {
          this.$message.success(data)
          this.$router.push('/flowable/task/TodoList')
        })
      },
      // 终止
      stop () {
        this.$confirm(`确定终止流程吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 将数据状态更改为暂存状态
          this.$refs.form.updateStatusById('hold', () => {
            // this.auditForm.candidateUserList = inputForm.assignee
            this.processService.stop(this.procInsId, this.auditForm.message).then(({data}) => {
              this.$message.success(data)
              if (this.$route.query.routePath) {
                this.$router.push(this.$route.query.routePath)
              } else {
                var num = this.$route.query.num
                if (num === '2') {
                  this.$router.push('/sys/dashboard/workBench/Pending')
                  this.cc(data)
                } else if (num === '3') {
                  this.$router.push('/sys/dashboard/workBench/PendingList')
                  this.cc(data)
                } else {
                  this.$router.push('/flowable/task/TodoList')
                  this.cc(data)
                }
              }
            })
          })
        })
      },
      // 打印
      print () {

      },
      // 关闭
      close () {
        this.changeBusiness()
        this.$store.dispatch('tagsView/delView', {fullPath: this.$route.fullPath})
        if (this.$route.query.routePath) {
          this.$router.push(this.$route.query.routePath)
        } else {
          var num = this.$route.query.num
          if (num === '2') {
            this.$router.push('/sys/dashboard/workBench/Pending')
          } else if (num === '3') {
            this.$router.push('/sys/dashboard/workBench/PendingList')
          } else {
            this.$router.push('/flowable/task/TodoList')
          }
        }
        this.$refs.form.close()
      },
      // 自定义按钮提交
      commit (vars) {
        if (this.formType === '2') { // 外置表单
          let param = {
            num: this.$route.query.num,
            taskId: this.taskId,
            taskDefKey: this.taskDefKey,
            procInsId: this.procInsId,
            procDefId: this.procDefId,
            vars: vars,
            comment: this.auditForm,
            assignee: this.auditForm.assignee,
            cope: {
              userIds: this.auditForm.userIds,
              procDefId: this.procDefId,
              procInsId: '',
              procDefName: '',
              procInsName: this.title,
              taskName: ''
            }
          }
          this.$refs.form.agreeForm((businessTable, businessId, inputForm) => {
            if (this.commonJS.isNotEmpty(inputForm)) {
              if (this.commonJS.isNotEmpty(inputForm.assignee)) {
                this.auditForm.assignee = inputForm.assignee
              }
            }
            vars = {...vars, ...inputForm}
            this.taskService.audit({
              taskId: this.taskId,
              taskDefKey: this.taskDefKey,
              procInsId: this.procInsId,
              procDefId: this.procDefId,
              vars: vars,
              comment: this.auditForm,
              assignee: this.auditForm.assignee
            }).then(({data}) => {
              this.$message.success('提交成功')
              this.changeBusiness()
              this.$refs.form.close()
              // 我的通知
              let createDate = ''
              this.myNotice(data, this.procDefId, this.title, vars.userName, createDate)
              this.$store.dispatch('tagsView/delView', {fullPath: this.$route.fullPath})
              // this.$router.push('/flowable/task/TodoList')
              // this.cc(data)
              if (this.$route.query.routePath) {
                this.$router.push(this.$route.query.routePath)
              } else {
                var num = this.$route.query.num
                if (num === '2') {
                  this.$router.push('/sys/dashboard/workBench/Pending')
                  this.cc(data)
                } else if (num === '3') {
                  this.$router.push('/sys/dashboard/workBench/PendingList')
                  this.cc(data)
                } else {
                  this.$router.push('/flowable/task/TodoList')
                  this.cc(data)
                }
              }
            })
          }, param)
        } else { // 动态表单
          this.$refs.form.submitTaskFormData(vars, this.procInsId, this.taskId, this.auditForm.assignee, this.auditForm, (data) => {
            this.changeBusiness()
            this.$refs.form.close()
            this.$store.dispatch('tagsView/delView', {fullPath: this.$route.fullPath})
            // this.$router.push('/flowable/task/TodoList')
            // this.cc(data)
            if (this.$route.query.routePath) {
              this.$router.push(this.$route.query.routePath)
            } else {
              var num = this.$route.query.num
              if (num === '2') {
                this.$router.push('/sys/dashboard/workBench/Pending')
                this.cc(data)
              } else if (num === '3') {
                this.$router.push('/sys/dashboard/workBench/PendingList')
                this.cc(data)
              } else {
                this.$router.push('/flowable/task/TodoList')
                this.cc(data)
              }
            }
          })
        }
      },

      submit (currentBtn, buttons) {
        let vars = {} // 存储流程变量

        // 把当前操作对应的自定义按钮(以_flow_开头的是系统按钮，排除在外）的编码，存储为对应的流程变量，值设置为true，其余自定义按钮编码对应的流程变量值为false。
        buttons.forEach((btn) => {
          if (btn.code && !btn.code.startsWith('_flow_')) {
            vars[btn.code] = false
          }
        })
        if (currentBtn.code && !currentBtn.code.startsWith('_flow_')) {
          vars[currentBtn.code] = true
        }
        vars.title = this.title // 标题
        vars.assignee = this.auditForm.assignee // 指定的下一步骤处理人
        this.auditForm.type = currentBtn.code // 提交类型
        this.auditForm.status = currentBtn.name // 按钮文字
        switch (currentBtn.code) {
          case '_flow_start': // 自动流程
            this.start(vars)
            break
          case '_flow_save': // 保存草稿
            this.save()
            break
          case '_flow_agree': // 同意
            this.agree()
            break
          case '_flow_reject': // 驳回
            // if (this.title.includes('报销申请')) {
            //   this.rejectToPointNum(0)
            //   break
            // }
            this.reject()
            break
          case '_flow_back': // 驳回到任意步骤
            this.turnBack()
            break
          case '_flow_add_multi_instance': // 加签
            this.addMultiInstance()
            break
          case '_flow_del_multi_instance': // 减签
            this.delMultiInstance()
            break
          case '_flow_transfer': // 转办
            this.transfer()
            break
          case '_flow_delegate':// 外派
            this.delegate()
            break
          case '_flow_stop':// 终止
            this.stop()
            break
          case '_flow_print':// 打印
            this.print()
            break
          case '_flow_reapply':// 重新申请
            this.reapply()
            break
          case '_flow_close':// 关闭
            this.close()
            break
          case '_flow_reback':// 撤回
            this.reback()
            break
          default:
            this.commit(vars) // 自定义按钮提交
        }
      },
      myNotice (taskId, proDefId, title, userName, createDate) {
        this.inputForm = {
          taskId: '',
          title: '',
          defId: '',
          taskName: '',
          createUser: '',
          createTime: '',
          noticeName: '',
          noticeId: ''
        }
        this.taskService.historicTaskList(taskId).then(({data}) => {
          if (data[data.length - 1].comment.status === '结束') {
            this.inputForm.taskId = taskId
            // 实例标题
            this.inputForm.title = title
            // 流程id
            this.inputForm.defId = proDefId
            // 流程名称
            this.processService.getById(proDefId).then(({data}) => {
              this.inputForm.taskName = data.name
            })
            // 流程发起人
            this.inputForm.createUser = data[0].assigneeName
            // 创建时间
            this.inputForm.createTime = data[0].histIns.endTime
            // 通知人
            this.inputForm.noticeName = data[0].assigneeName
            // 通知人Id
            this.inputForm.noticeId = data[0].assigneeId
            this.noticeService.addInfo(this.inputForm)
          }
        })
      },
      callBackFunc (type) {
        // 隐藏同意按钮
        if (type === 'hide') {
          // 读取按钮
          this.taskDefExtensionService.queryByDefIdAndTaskId({
            processDefId: this.procDefKey,
            taskDefId: this.taskDefKey
          }).then(({data}) => {
            // console.log('buttons', data)
            data.flowButtonList.forEach(item => {
              if (item.code === '_flow_agree') {
                item.isHide = '1'
              }
            })
            this.buttons = data.flowButtonList
          })
        }
        // 展示同意按钮
        if (type === 'show') {
          // 读取按钮
          this.taskDefExtensionService.queryByDefIdAndTaskId({
            processDefId: this.procDefKey,
            taskDefId: this.taskDefKey
          }).then(({data}) => {
            // console.log('buttons', data)
            data.flowButtonList.forEach(item => {
              if (item.code === '_flow_agree') {
                item.isHide = '0'
              }
            })
            this.buttons = data.flowButtonList
          })
        }
      },
      // 开启/关闭taskForm页面的加载中状态
      changeLoading (loading) {
        if (this.commonJS.isNotEmpty(loading)) {
          this.loading = loading
        } else {
          this.loading = false
        }
      },
      onTabChange (event) {
        if (event.name === 'form-sixth') {
          if (this.commonJS.isNotEmpty(this.wareHouseId)) {
            this.wareHouseService.findHiById(this.wareHouseId).then(({data}) => {
              this.dataListHi = data
            })
          }
        }
        if (event.name === 'form-seventh') {
          if (this.commonJS.isNotEmpty(this.returnId)) {
            this.collectService.findByReturnId(this.returnId).then(({data}) => {
              this.collectService.findHiById(data.id).then(({data}) => {
                this.dataListHiCollect = data
              })
            })
          }
        }
      },
      // 打开入库修改历史详情页
      hiDetail (row) {
        if (this.commonJS.isNotEmpty(row.id)) {
          this.$refs.wareHouseHi.init(row.id)
        }
      },
      // 打开领用退回历史详情页
      hiDetailCollect (row) {
        if (this.commonJS.isNotEmpty(row.id)) {
          this.$refs.collectReturnHi.init(row.id)
        }
      }
    },
    data () {
      return {
        form: null,
        formType: '',
        formUrl: '',
        taskSelectedTab: 'frist',
        historicTaskList: [],
        procDefId: '',
        procInsId: '',
        formReadOnly: false,
        procDefKey: '',
        taskId: '',
        taskFormData: [],
        taskDefKey: '',
        status: '',
        title: '',
        businessId: '',
        buttons: [],
        isCC: false,
        isAssign: false,
        isShow: true,
        printObj: {
          id: 'printForm',
          popTitle: '',
          extraCss: '',
          extraHead: '<meta http-equiv="Content-Language" content="zh-cn"/>'
        },
        auditForm: {
          message: '',
          type: '',
          status: '',
          userIds: null,
          assignee: null
        },
        cUser: false,
        loading: false,
        wareHouseId: '',
        returnId: '',
        dataListHi: [],
        dataListHiCollect: []
      }
    }
  }
</script>
