<template>
  <div class="aos-flow">
    <div class="aos-flow__body">
      <div class="aos-flow__taskName">
        <div class="aos-flow__icon">
          <div class="aos-flow__icon__center"></div>
        </div>
        <div class="aos-flow__taskName__name">
          {{ taskName }}
        </div>
      </div>
      <div v-if="['addSign', 'hangup', 'turnto', 'transfer'].indexOf(actionType) < 0" class="aos-flow__type">
        <div class="aos-flow__part" v-if="actionType === 'reject' && showReject && rejectActivitys.length > 0">
          <span class="aos-flow__message-title">驳回至</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message" v-if="actionType === 'reject' && showReject && rejectActivitys.length > 0">
          <div>
            <el-select v-model="rejectNode" class="aos-flow-reject-group" clearable>
              <el-option class="aos-flow-reject-radio" v-for="item in rejectActivitys" :key="item.activityId" :value="item.activityId" :label="item.activityName"></el-option>
            </el-select>
          </div>
        </div>
        <div class="aos-flow__part" v-if="actionType === 'reject' && showReject && showRejectNonstop">
          <span class="aos-flow__flow-message-title">点对点驳回</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message" v-if="actionType === 'reject' && showReject && showRejectNonstop">
          <el-switch v-model="rejectNonstop"></el-switch>
        </div>
        <!-- <div class="aos-flow__part"> -->
        <!-- <div class="aos-flow__part">
          <span class="aos-flow__flow-message-title">审批意见</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message">
          <el-input type="textarea" :autosize="{minRows:2}" v-model="outMessage" placeholder="请输入审批意见"></el-input>
        </div> -->
        <div class="aos-flow__part aos-flow__part-message"> 
          <el-form 
              :model="flowMessageModel"
              :rules="flowMessageRules"
              ref="flowMessageRef"
              label-position="top"
              >
              <el-form-item prop="outMessage" label="审批意见">
                <el-input 
                  type="textarea" 
                  :autosize="{minRows:2}" 
                  v-model="flowMessageModel.outMessage" 
                  placeholder="请输入审批意见"
                  @input="handleOutMessageChange"
                  >
                </el-input>
              </el-form-item>
            </el-form>
        </div>
        <div class="aos-flow__part aos-flow__part-message" v-if="actionType === 'reject' && rejectReasonDictIdsFlat.length > 0">
          <div class="aos-flow__option-tree">
            <el-form
              :model="rejectReasonDictIdsModel"
              :rules="rejectReasonDictIdsRules"
              ref="rejectReasonDictIdsRef"
              label-position="top">
              <el-form-item prop="rejectReasonDictIds" label="驳回意见">
                <el-select
                  v-model="rejectReasonDictIdsModel.rejectReasonDictIds"
                  multiple
                  class="aos-flow__option-tree-option"
                  clearable
                  filterable
                  :filter-method="rejectReasonDictIdsFilterMethod"
                  @remove-tag="handleRemoveRejectReasonDictIds"
                  @clear="handleRemoveRejectReasonDictIds">
                  <el-option
                    style="height: 0px;"
                    v-for="item in rejectReasonDictIdsFlat"
                    :key="'tree_'+item.id"
                    :label="item.reason"
                    :value="item.id"
                    >
                  </el-option>
                  <el-option class="aos-flow__option-tree-option">
                    <el-tree
                      class="aos-flow__option-tree-main"
                      ref="rejectReasonDictIdsFilterTree"
                      node-key="id"
                      :data="rejectReasonDictIdsTree"
                      :props="defaultProps"
                      :default-expand-all="false"
                      :filter-node-method="filterNode"
                      :default-checked-keys="rejectReasonDictIdsDefaultCheckedKeys"
                      :show-checkbox="true"
                      @check="handlerejectReasonDictIdsCheck"
                      :expand-on-click-node="true"
                      >
                      <span class="aos-flow__option-tree-main-item" slot-scope="{ node }">
                        <span>{{ node.label }}</span>
                      </span>
                    </el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            
          </div>
        </div>
        <!-- <div class="aos-flow__part" v-if="actionType === 'refuse' && refuseReasonDictIdsFlat.length > 0">
          <span class="aos-flow__flow-message-title">拒绝意见</span>
        </div> -->
        <div class="aos-flow__part aos-flow__part-message" v-if="actionType === 'refuse' && refuseReasonDictIdsFlat.length > 0">
          <div class="aos-flow__option-tree">
            <el-form
              :model="refuseReasonDictIdsModel"
              :rules="refuseReasonDictIdsRules"
              ref="refuseReasonDictIdsRef"
              label-position="top">
              <el-form-item prop="refuseReasonDictIds" label="拒绝意见">
                <el-select
                  v-model="refuseReasonDictIdsModel.refuseReasonDictIds"
                  multiple
                  class="aos-flow__option-tree-option"
                  clearable
                  filterable
                  :filter-method="refuseReasonDictIdsFilterMethod"
                  @remove-tag="handleRemoveRefuseReasonDictIds"
                  @clear="handleRemoveRefuseReasonDictIds">
                  <el-option
                    style="height: 0px;"
                    v-for="item in refuseReasonDictIdsFlat"
                    :key="'tree_'+item.id"
                    :label="item.reason"
                    :value="item.id"
                    >
                  </el-option>
                  <el-option class="aos-flow__option-tree-option">
                    <el-tree
                      class="aos-flow__option-tree-main"
                      ref="refuseReasonDictIdsFilterTree"
                      node-key="id"
                      :data="refuseReasonDictIdsTree"
                      :props="defaultProps"
                      :default-expand-all="false"
                      :filter-node-method="filterNode"
                      :default-checked-keys="refuseReasonDictIdsDefaultCheckedKeys"
                      :show-checkbox="true"
                      @check="handleRefuseReasonDictIdsCheck"
                      :expand-on-click-node="true"
                      >
                      <span class="aos-flow__option-tree-main-item" slot-scope="{ node }">
                        <span>{{ node.label }}</span>
                      </span>
                    </el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="aos-flow__part" v-if="showInnerMessage">
          <span class="aos-flow__flow-message-title">内部意见</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message" v-if="showInnerMessage">
          <el-input type="textarea" :autosize="{minRows:2}" v-model="message"  placeholder="请输入内部意见,该意见仅内部人员可见"></el-input>
        </div>
        <div class="aos-flow__part" v-if="showConditionMessage && actionType !== 'reject'">
          <span class="aos-flow__flow-message-title">有条件通过意见</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message" v-if="showConditionMessage && actionType !== 'reject'">
          <el-input type="textarea" :autosize="{minRows:2}" v-model="conditionMessage"  placeholder="请输入有条件通过意见"></el-input>
        </div>
        <div class="aos-flow__images aos-flow__part-message">
          <!-- <div class="aos-flow__image-box" v-for="(item,index) in filesList" :key="index" @mouseout="handleImageMouseOut(index)" @mouseover="handleImageMouseOver(index)">
            <img :src="'/bpm/api/task/file-download/'+ taskId + '/'+ item.id" alt="流程附件图片">
            <span v-show="activeItemIndex === index">
              <i class="el-icon-search aos-flow__icon" title="查看" @click="handleViewImage(item)"></i>
              <a class="aos-flow__icon" title="下载" :href="'/bpm/api/task/file-download/'+ taskId + '/'+ item.id"  @click="handleDownload(item)">
                <i class="el-icon-download"></i>
              </a>
              <i class="el-icon-delete aos-flow__icon" title="删除" @click="handleDeleteImage(item)"></i>
            </span>
          </div> -->
          <el-upload
            drag
            multiple
            class="aos-flow__upload"
            :file-list="filesList"
            :action='"/bpm/api/task/upload/"+taskId'
            :on-success="handleUploadSuccess"
            :on-preview="handlePreviewClick"
            :before-remove="handleBeforeRemove">
            <i class="el-icon-upload" style="font-size: 40px;margin:0;"></i>
            <div class="el-upload__text" style="font-size: 12px;margin:0 8px;">将文件拖到此处或<em>点击上传</em></div>
          </el-upload>
        </div>
      </div>
      <!-- <div v-if="actionType === 'countersign'" class="aos-flow__type aos-flow__countersign">
        <div class="aos-flow__part">
          <span class="aos-flow__message-title">加签说明</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message">
          <el-input type="textarea" :autosize="{minRows:2}" v-model="countersignMessage" placeholder="请在此输入加签说明"></el-input>
        </div>
        <div class="aos-flow__part">
          <span class="aos-flow__message-title">加签人</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message">
          <el-select></el-select>
        </div>
      </div>
      <div v-if="actionType === 'return-countersign'" class="aos-flow__type aos-flow__return-countersign">
        <div class="aos-flow__part">
          <span class="aos-flow__message-title">回复加签说明</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message">
          <el-input type="textarea" :autosize="{minRows:2}" v-model="returnCountersignMessage" placeholder="请在此输入回复加签说明"></el-input>
        </div>
      </div> -->
      <div v-if="actionType === 'hangup'" class="aos-flow__type aos-flow__hangup">
        <div class="aos-flow__part">
          <span class="aos-flow__message-title">挂起原因</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message">
          <el-input type="textarea" :autosize="{minRows:2}" v-model="hangUpMessage" placeholder="请在此输入挂起原因"></el-input>
        </div>
        <div class="aos-flow__part aos-flow__part-message" v-if="actionType === 'hangup' && suspendedaReasonDictIdsFlat.length > 0">
          <div class="aos-flow__option-tree">
            <el-form
              :model="suspendedaReasonDictIdsModel"
              :rules="suspendedaReasonDictIdsRules"
              ref="suspendedaReasonDictIdsRef"
              label-position="top">
              <el-form-item prop="suspendedaReasonDictIds" label="挂起意见">
                <el-select
                  v-model="suspendedaReasonDictIdsModel.suspendedaReasonDictIds"
                  multiple
                  class="aos-flow__option-tree-option"
                  clearable
                  filterable
                  :filter-method="suspendedaReasonDictIdsFilterMethod"
                  @remove-tag="handleRemoveSuspendedaReasonDictIds"
                  @clear="handleRemoveSuspendedaReasonDictIds">
                  <el-option
                    style="height: 0px;"
                    v-for="item in suspendedaReasonDictIdsFlat"
                    :key="'tree_'+item.id"
                    :label="item.reason"
                    :value="item.id"
                    >
                  </el-option>
                  <el-option class="aos-flow__option-tree-option">
                    <el-tree
                      class="aos-flow__option-tree-main"
                      ref="suspendedaReasonDictIdsFilterTree"
                      node-key="id"
                      :data="suspendedaReasonDictIdsTree"
                      :props="defaultProps"
                      :default-expand-all="false"
                      :filter-node-method="filterNode"
                      :default-checked-keys="suspendedaReasonDictIdsDefaultCheckedKeys"
                      :show-checkbox="true"
                      @check="handleSuspendedaReasonDictIdsCheck"
                      :expand-on-click-node="true"
                      >
                      <span class="aos-flow__option-tree-main-item" slot-scope="{ node }">
                        <span>{{ node.label }}</span>
                      </span>
                    </el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div v-if="actionType === 'turnto'" class="aos-flow__type aos-flow__turnto">
        <div class="aos-flow__part">
          <span class="aos-flow__message-title">转办说明</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message">
          <el-input type="textarea" :autosize="{minRows:2}" v-model="turntoMessage" placeholder="请在此输入转办说明"></el-input>
        </div>
        <div class="aos-flow__part">
          <span class="aos-flow__message-title">转办人</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message">
          <el-select v-model="turnToUser" placeholder="请选择">
            <el-option
              v-for="item in turnTowardUsers"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <div v-if="actionType === 'transfer'" class="aos-flow__type aos-flow__turnto">
        <div class="aos-flow__part">
          <span class="aos-flow__message-title">转移说明</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message">
          <el-input type="textarea" :autosize="{minRows:2}" v-model="transferData.reason" placeholder="请输入转移说明"></el-input>
        </div>
        <!-- <div class="aos-flow__part">
          <span class="aos-flow__message-title">转移任务名称</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message">
          <el-input type="textarea" :autosize="{minRows:2}" v-model="transferData.transferTaskName" placeholder="默认取原任务名称,并自动追加后缀"></el-input>
        </div> -->
        <div class="aos-flow__part aos-flow__part-message">
          <el-switch
            style="display: block"
            v-model="transferData.type"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="候选人"
            inactive-text="候选组"
            @change="handleTransferTypeChange">
          </el-switch>
        </div>
        <div class="aos-flow__part" v-if="transferData.type">
          <span class="aos-flow__message-title">候选人</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message" v-if="transferData.type">
          <aos-ref
            refCode="user"
            :value="transferData.candidateUsers"
            :editable="true"
            :multiple="true"
            placeholder="请选择候选人员"
            @change="handelCandidateUsersChange">
          </aos-ref>
        </div>
        <div class="aos-flow__part" v-if="!transferData.type">
          <span class="aos-flow__message-title">候选组</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message" v-if="!transferData.type">
          <aos-ref
            refCode="bpm_group_ref"
            :value="transferData.candidateGroups"
            :editable="true"
            placeholder="请选择候选组"
            @change="handelCandidateGroupsChange">
          </aos-ref>
        </div>
        <div class="aos-flow__part aos-flow__part-message">
          <el-upload
            drag
            multiple
            class="aos-flow__upload"
            :file-list="filesList"
            :action='"/bpm/api/task/upload/"+taskId'
            :on-success="handleUploadSuccess"
            :on-preview="handlePreviewClick"
            :before-remove="handleBeforeRemove">
            <i class="el-icon-upload" style="font-size: 40px;margin:0;"></i>
            <div class="el-upload__text" style="font-size: 12px;margin:0 8px;">将文件拖到此处或<em>点击上传</em></div>
          </el-upload>
        </div>
      </div>
      <div v-if="actionType === 'addSign'" class="aos-flow__type aos-flow__turnto">
        <div class="aos-flow__part">
          <span class="aos-flow__message-title">加签意见</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message">
          <el-input type="textarea" :autosize="{minRows:2}" v-model="addSignData.remind" placeholder="请在此输入加签意见"></el-input>
        </div>
        <div class="aos-flow__part">
          <span class="aos-flow__message-title">指定加签人</span>
        </div>
        <div class="aos-flow__part aos-flow__part-message">
          <aos-ref
            refCode="user"
            :value="addSignData.signUserId"
            :editable="true"
            placeholder="请选择加签人员"
            @change="handelAddSignChange">
          </aos-ref>
        </div>
        <div class="aos-flow__part aos-flow__part-message">
          <el-upload
            drag
            multiple
            class="aos-flow__upload"
            :file-list="filesList"
            :action='"/bpm/api/task/upload/"+taskId'
            :on-success="handleUploadSuccess"
            :on-preview="handlePreviewClick"
            :before-remove="handleBeforeRemove">
            <i class="el-icon-upload" style="font-size: 40px;margin:0;"></i>
            <div class="el-upload__text" style="font-size: 12px;margin:0 8px;">将文件拖到此处或<em>点击上传</em></div>
          </el-upload>
        </div>
      </div>
    </div>
    <div class="aos-flow__footer">
      <div v-if="['addSign','hangup', 'turnto', 'reject','transfer', 'refuse'].indexOf(actionType) < 0">
        <el-button type="success" @click="agreeEvent" :loading="loading">通过</el-button>
        <!-- <el-button type="success" @click="handleBack">返回</el-button> -->
        <el-button type="warning" class="aos-flow__footer-button" :loading="loading" v-if="showReject" @click="rejectEvent">驳回</el-button>
        <el-button class="aos-flow__footer-button" :loading="loading" v-if="!showReject && showTurnto && !showTransfer" @click="handleTurnTo">转办</el-button>
        <el-button class="aos-flow__footer-button" :loading="loading" v-if="!showReject && !showTurnto && showTransfer" @click="handleTransfer">转移</el-button>
        <el-dropdown class="aos-flow__footer-button" type="primary" trigger="click" @command="handleMoreCommand">
          <el-button>
            更多<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-if="showReject && showTurnto && !showTransfer" command="turnto">转办</el-dropdown-item>
            <el-dropdown-item v-if="showReject && showTransfer && !showTurnto" command="transfer">转移</el-dropdown-item>
            <el-dropdown-item command="refuse" v-if="showRefuse" :disabled="loading">拒绝</el-dropdown-item>
            <!-- <el-dropdown-item command="countersign">加签</el-dropdown-item> -->
            <el-dropdown-item command="hangup">挂起</el-dropdown-item>
            <el-dropdown-item v-if="showAddSign" command="addSign">加签</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="aos-flow__footer-inline" v-else>
        <el-button @click="handleInlineBack">返回</el-button>
        <el-button class="aos-flow__footer-button" type="primary" :loading="loading" @click="handleInlineSubmit">确定</el-button>
      </div>
    </div>
    <el-dialog title="播放器" :visible.sync="showVideDialog" append-to-body destroy-on-close width="30%"
      @close="handleVideoClose">
      <div class="aos-files__video">
        <aos-video ref="aos-flow-history-video" :options="videoOptions"></aos-video>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import cloneDeep from 'lodash/cloneDeep'
import Viewer from 'viewerjs-optimize';
import { PopupManager } from 'aos-element/src/utils/popup';
export default {
  name: 'AosFlow',
  props: {
    // 表单状态判断,true为表单已处理好,false为表单未处理好
    operation: {
      type: Boolean
    },
    // 表单未处理好的提示信息
    operationMessage: {
      type: String,
      default: '当前表单未处理'
    },
    // 是否显示操作按钮
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否显示意见框
    showMessage: {
      type: Boolean,
      default: false
    },
    // 点击操作之前
    beforeAction: {
      type: Function,
      default: function() {return true}
    },
    // 点击同意操作之前
    agreeBeforeAction: {
      type: Function,
      default: function() {return true}
    },
    rejectBeforeAction: {
      type: Function,
      default: function(){return true}
    },
    refuseBeforeAction: {
      type: Function,
      default: function(){return true}
    },
    // 点击提交按钮之前触发事件
    submitBeforeAction: {
      type: Function,
      default: function(){return true}
    },
    // 同意时是否走agreeBeforeAction方法
    agreeBefore: {
      type: Boolean,
      default: false
    },
    // // 驳回是否走rejectBeforeAction方法
    // rejectBefore: {
    //   type: Boolean,
    //   default: false
    // },
    // // 拒绝是否走refuseBeforeAction方法
    // refuseBefore: {
    //   type: Boolean,
    //   default: false
    // },
    // 提交时是否走submitBeforeAgree方法
    submitBefore: {
      type: Boolean,
      default: false
    },
    // 返回按钮返回的URL,默认返回任务中心
    backRouter: {
      type: String,
      default: '/bpm/task'
    },
    // 提交确认成功之后跳转的页面
    confirmBackRouter: {
      type: String,
      default: '/bpm/task'
    },
    // 是否显示返回按钮
    showBackBtn: {
      type: Boolean,
      default: true
    },
    // 显示的风格,horizontal:水平 vertical: 垂直
    showType:{
      type: String,
      default: 'horizontal'
    },
    // agreeBeforeAction方法:false同步请求,true有异步请求
    agreeAsyncHttp: {
      type: Boolean,
      default: false
    },
    // 控制refuseBeforeAction方法为同步还是异步： 
    refuseAsyncHttp: {
      type: Boolean,
      default: false
    },
    rejectAsyncHttp: {
      type: Boolean,
      default: false
    },
    // 是否自动触发提交,true为自动提交
    autoOperate:{
      type: Boolean,
      default: true
    },
    // 是否自动触发驳回
    autoReject: {
      type: Boolean,
      default: true
    },
    // 是否自动触发拒绝
    autoRefuse: {
      type: Boolean,
      default: true
    },
    // 是否水平版 自动拒绝
    autoHorizontalRefuse: {
      type: Boolean,
      default: true
    },
    // 水平版拒绝前的校验函数
    beforeHorizantalRefuseAction: {
      type: Function,
      default: function(){
        return true
      }
    },
    // 是否水平版 自动驳回
    autoHorizontalReject: {
      type: Boolean,
      default: true
    },
    // 水平版驳回前的校验函数
    beforeHorizantalRejectAction: {
      type: Function,
      default: function(){
        return true
      }
    },
    autoSubmit: {
      type: Boolean,
      default: true
    },
    // 弹框 点击确认前事件
    beforeSubmitAction: {
      type: Function,
      default: function(){
        return true
      }
    },
    //是否审批意见必填
    // isFlowMessageRequired:{
    //   type:Boolean,
    //   default:false 
    // },
    //是否通过审批意见必填
    completeMessageRequired:{
      type:Boolean,
      default:false 
    },
    //是否驳回审批意见必填
    rejectMessageRequired:{
      type:Boolean,
      default:false 
    },
    //是否拒绝审批意见必填
    refuseMessageRequired:{
      type:Boolean,
      default:false
    }
  },
  data(){
    return {
      showFlow: false, // 是否显示流程审批按钮
      active: 0,
      showReject: false, //是否显示驳回按钮
      showRefuse: false, // 是否显示拒绝按钮
      rejectActivitys: '', // 驳回信息(包含环节等)
      refuseReasons: [], // 拒绝原因
      rejectReasons: [], // 驳回原因
      completeReasons: [], // 通过原因
      completeGroupReasons: {}, // 通过的组原因
      refuseGroupReasons: {}, // 通过的组原因
      rejectGroupReasons: {}, // 通过的组原因
      reasonList: [], //原因
      reasonGroupObject: {}, //组原因
      taskId: '', // 当前任务id
      //taskId: '3a2ca94d-85ba-11ed-a8d9-005056893bc4',
      processInstanceId: '', //流程id
      startEndMessage: '', // 审批开始结束信息
      showHistory: false, // 显示历史信息
      taskDetail: '', // 任务详细
      historyDetailList: '', // 历史审批意见,
      translateHistoryDetailList: '', // 转换过类型的历史审批意见
      messageTitle: '', //意见dailog名称
      operationType: true, // 操作的类型,true为通过,false为驳回
      // showMessage: false, // 是否显示意见dialog 改为双向数据绑定
      message: '', // 内部意见
      conditionMessage: '', //有条件通过意见
      outMessage: '', //外部意见
      reason:'', // 选择的原因
      rejectNode: '', //驳回节点
      auditRecord: '', // 审批意见
      messageSuccess: false, // 通过或拒绝是否成功
      approvalCheckedType: '',
      rejectType:'',
      showApprovalMessage: false, // 切换审批和审批意见,默认为审批
      approvalType: '', // 当前审批类型
      reverse: false,
      dialogImageUrl: '', // 图片的url
      dialogVisible: false, // 图片预览
      filesList: [],
      activeItemIndex: '',
      moreActionList: [
        {
          label: '转办',
          key: 'turnto',
        },
        {
          label: '驳回',
          key: 'reject',
        },
        {
          lable: '加签',
          key: 'countersign'
        },
        {
          label: '挂起',
          key: 'hangup'
        }
      ],
      actionType: '',
      hangUpMessage: '',
      turntoMessage: '',
      returnCountersignMessage: '',
      countersignMessage: '',
      transferMessage: '',
      showTurnto: false,
      showTransfer: false,
      turnTowardUsers: [],
      turnToUser: '',
      // 是否显示内部意见
      showInnerMessage: false,
      // 是否显示有条件通过意见
      showConditionMessage: false,
      loading: false,
      transferData: {
        type: true,
        reason: '',
        transferTaskName: '',
        candidateUsers: '',
        candidateGroups: ''
      },
      showVideDialog: false,
      videoOptions: {},
      videoFileTypeList: ['.mp4', '.webm', '.mov', '.flv', '.mp3', '.wav', '.ogg'],
      otherFileTypeList: ['.docx', '.doc', '.xls', '.zip', '.xlsx', '.rar', '.txt'],
      imgFileTypeList: ['.png', '.jpg', '.jpeg', '.gif', '.tif', '.tiff', '.bmp', '.svg', '.webp', '.ico'],
      viewer: '',
      currentContainer: '',
      currentContainerId: '',
      taskName:'',
      startIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iMTRweCIgaGVpZ2h0PSIxNHB4IiB2aWV3Qm94PSIwIDAgMTQgMTQiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8dGl0bGU+5byA5aeLPC90aXRsZT4KICAgIDxnIGlkPSLpobXpnaItMSIgc3Ryb2tlPSJub25lIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+CiAgICAgICAgPGcgaWQ9IuivpuaDhS3pooTop4giIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0xNi4wMDAwMDAsIC0xMDQwLjAwMDAwMCkiPgogICAgICAgICAgICA8ZyBpZD0i5byA5aeLIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxNi4wMDAwMDAsIDEwNDAuMDAwMDAwKSI+CiAgICAgICAgICAgICAgICA8Y2lyY2xlIGlkPSJPdmFsIiBmaWxsPSIjRTJGMEZGIiBjeD0iNyIgY3k9IjciIHI9IjciPjwvY2lyY2xlPgogICAgICAgICAgICAgICAgPGNpcmNsZSBpZD0iT3ZhbOWkh+S7vSIgc3Ryb2tlPSIjNDA5RUZGIiBjeD0iNyIgY3k9IjciIHI9IjMiPjwvY2lyY2xlPgogICAgICAgICAgICA8L2c+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4=',
      showAddSign: false,
      addSignData: {
        remind: '',
        signUserId: '',
        taskId: ''
      },
      defaultProps: {
        children: 'children',
        label: 'reason'
      },
      rejectReasonDictIdsTree: [],
      rejectReasonDictIdsDefaultCheckedKeys: [],
      rejectReasonDictIdsFlat: [],
      rejectReasonDictIdsModel: {
        rejectReasonDictIds: '',
      },
      rejectReasonDictIdsRules: {
        rejectReasonDictIds: [
          { required: true, message: '请选择驳回意见', trigger: 'blur' },
        ]
      },
      suspendedaReasonDictIdsModel: {
        suspendedaReasonDictIds: '',
      },
      suspendedaReasonDictIdsRules: {
        suspendedaReasonDictIds: [
          { required: true, message: '请选择挂起意见', trigger: 'blur' },
        ]
      },
      suspendedaReasonDictIdsTree: [],
      suspendedaReasonDictIdsDefaultCheckedKeys: [],
      suspendedaReasonDictIdsFlat: [],
      refuseReasonDictIdsModel: {
        refuseReasonDictIds: '',
      },
      refuseReasonDictIdsRules: {
        refuseReasonDictIds: [
          { required: true, message: '请选择拒绝意见', trigger: 'blur' },
        ]
      },
      refuseReasonDictIdsTree: [],
      refuseReasonDictIdsDefaultCheckedKeys: [],
      refuseReasonDictIdsFlat: [],
      rejectNonstop: false,
      showRejectNonstop: false,
      flowMessageModel:{
        outMessage:'' //外部数据
      },
      flowMessageRules: {
        outMessage: [
          // { required: true, message: '请输入审批意见', trigger: 'blur' },
        ]
      },
    }
  },
  watch:{
    actionType:{
      handler:function(val){
        if(!val){
          if(this.completeMessageRequired){
            this.flowMessageRules.outMessage = [
              { required: true, message: '请输入审批意见', trigger: 'blur' },
             ]
            }else{
              this.flowMessageRules.outMessage = []
            }
        }else if(val==='reject'){
          if(this.rejectMessageRequired){
            this.flowMessageRules.outMessage = [
              { required: true, message: '请输入驳回审批意见', trigger: 'blur' },
             ]
          }else{
              this.flowMessageRules.outMessage = []
          }
        }else if(val==='refuse'){
          if(this.refuseMessageRequired){
            this.flowMessageRules.outMessage = [
              { required: true, message: '请输入拒绝审批意见', trigger: 'blur' },
             ]
          }else{
              this.flowMessageRules.outMessage = []
          }
        }
      },
      immediate:true
    }
  },
  beforeDestroy () {
    if (this.viewer) {
      this.viewer = null
    }
    this.removeContainer()
  },
  methods: {
    handleOutMessageChange(){
      this.$refs.flowMessageRef.clearValidate()
    },
    rejectReasonDictIdsFilterMethod (query) {
      this.getTreeFilter('rejectReasonDictIdsFilterTree', query)
    },
    refuseReasonDictIdsFilterMethod (query) {
      this.getTreeFilter('refuseReasonDictIdsFilterTree', query)
    },
    suspendedaReasonDictIdsFilterMethod (query) {
      this.getTreeFilter('suspendedaReasonDictIdsFilterTree', query)
    },
    getTreeFilter (ref, queryString) {
      this.$nextTick(() => {
        this.$refs[ref].filter(queryString);
      })
    },
    handlerejectReasonDictIdsCheck(data, checkedData) {
      const refValue = []
      checkedData.checkedNodes.forEach(item=> {
        if(item.isLeaf){
          refValue.push(item.id)
        }
      })
      this.rejectReasonDictIdsModel.rejectReasonDictIds = refValue
      this.rejectReasonDictIdsDefaultCheckedKeys = refValue
      this.$refs.rejectReasonDictIdsRef.clearValidate()
    },
    handleSuspendedaReasonDictIdsCheck(data, checkedData) {
      const refValue = []
      checkedData.checkedNodes.forEach(item=> {
        if(item.isLeaf){
          refValue.push(item.id)
        }
      })
      this.suspendedaReasonDictIdsModel.suspendedaReasonDictIds = refValue
      this.suspendedaReasonDictIdsDefaultCheckedKeys = refValue
      this.$refs.suspendedaReasonDictIdsRef.clearValidate()
    },
    handleRefuseReasonDictIdsCheck(data, checkedData) {
      const refValue = []
      checkedData.checkedNodes.forEach(item=> {
        if(item.isLeaf){
          refValue.push(item.id)
        }
      })
      this.refuseReasonDictIdsModel.refuseReasonDictIds = refValue
      this.refuseReasonDictIdsDefaultCheckedKeys = refValue
      this.$refs.refuseReasonDictIdsRef.clearValidate()
    },
    handleRemoveRefuseReasonDictIds () {
      this.refuseReasonDictIdsDefaultCheckedKeys = cloneDeep(this.refuseReasonDictIdsModel.refuseReasonDictIds)
      this.$refs.refuseReasonDictIdsFilterTree.setCheckedKeys(this.refuseReasonDictIdsDefaultCheckedKeys)
    },
    handleRemoveRejectReasonDictIds () {
      this.rejectReasonDictIdsDefaultCheckedKeys = cloneDeep(this.rejectReasonDictIdsModel.rejectReasonDictIds)
      this.$refs.rejectReasonDictIdsFilterTree.setCheckedKeys(this.rejectReasonDictIdsDefaultCheckedKeys)
    },
    handleRemoveSuspendedaReasonDictIds () {
      this.suspendedaReasonDictIdsDefaultCheckedKeys = cloneDeep(this.suspendedaReasonDictIdsModel.suspendedaReasonDictIds)
      this.$refs.suspendedaReasonDictIdsFilterTree.setCheckedKeys(this.suspendedaReasonDictIdsDefaultCheckedKeys)
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.reason.indexOf(value) !== -1;
    },
    handelAddSignChange (value) {
      this.addSignData.signUserId = value
    },
    handlePreviewClick(file) {
      if (file) {
        const message = JSON.parse(file.message)
        const fileSuffix = message.fileSuffix.toLowerCase()
        if (this.videoFileTypeList.indexOf(fileSuffix) > -1) {
          this.handleViewVideo(file, message)
        } else if (fileSuffix.indexOf('.pdf') > -1) {
          this.handleViewPdf(file)
        } else if (this.imgFileTypeList.indexOf(fileSuffix) > -1) {
          this.handleViewerImg(file, message)
        } else {
          this.handleDownloadFile(file, message)
        }
      }
    },
    handleDownloadFile(fileItem, data) {
      const fileName = fileItem.name
      this.$http({
        url: fileItem.url,
        responseType: 'blob',
      }).then((res) => {
        this.download(res.data, fileName)
      })
    },
    download(blob, name) {
      const a = document.createElement('a');
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = name
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a)
    },
    handleVideoClose() {
      this.$refs['aos-flow-history-video'].destory()
    },
    handleViewVideo(item, data) {
      this.showVideDialog = true
      const fileSuffix = data.fileSuffix.substring(1)
      this.videoOptions = {
        width: 400,
        sources: [
          {
            src: item.url,
            type: `video/${fileSuffix}`
          }
        ]
      }
    },
    handleViewPdf(item) {
      this.$openPdfViewer(item.url)
    },
    handleViewerImg(item,data) {
       this.removeContainer(data.id)
        let container = this.currentContainer
        if (this.viewer) {
          this.viewer.destroy();
          this.viewer = null;
        }
        if(!this.currentContainerId || (this.currentContainer && this.currentContainer !==item.id)){
           container =  this.createImgList(item,item.id)
         }
        this.currentContainerId = item.id
        this.currentContainer = container
        this.viewer = new Viewer(document.getElementById('aos-flow-'+this.currentContainerId), {
          className:  'aos-img-viewer-container '+('aos-flow-'+this.currentContainerId),
          zIndex: PopupManager.nextZIndex() + 101,
        });
        container.children[0].click()
    },
    createImgList(data,id){
      console.log('id',data,id)
      const container = document.createElement('div')
      container.id = 'aos-flow-'+id
      container.style.position = 'absolute'
      container.style.top = '-10000px'
      container.style.left = '-10000px'
      if(data){
        const imgItem = document.createElement('img')
        console.log('dataimg',data)
        imgItem.src = data.url
        imgItem.alt = data.name
        imgItem.title = data.name
        container.appendChild(imgItem)
      }
      document.body.appendChild(container)
      return container
    },
    removeContainer (id) {
      const dom = document.getElementById('aos-flow-' + this.currentContainerId)
      if (!id) {
        if (dom) {
          document.body.removeChild(dom)
        }
      } else if (this.currentContainerId && this.currentContainerId !== id) {
        if (dom) {
          document.body.removeChild(dom)
        }
      }
    },
    handleTransferTypeChange (val) {
      if (val) {
        this.transferData.candidateGroups = ''
      } else {
        this.transferData.candidateUsers = ''
      }
    },
    handelCandidateUsersChange (val) {
      this.transferData.candidateUsers = val
      this.transferData.candidateGroups = ''
    },
    handelCandidateGroupsChange (val) {
      this.transferData.candidateUsers = ''
      this.transferData.candidateGroups = val
    },
    handleInlineBack () {
      this.actionType = ''
      this.hangUpMessage = ''
      this.turntoMessage = ''
      this.returnCountersignMessage = ''
      this.countersignMessage = ''
    },
    handleMoreCommand (commond) {
      this.actionType = commond
      // if (commond === 'refuse') {
      //   this.refuseEvent()
      // }
    },
    handleTurnTo () {
      this.actionType = 'turnto'
    },
    handleTransfer () {
      this.actionType = 'transfer'
    },
    handleInlineSubmit () {
      if (this.actionType === 'hangup') {
        if (this.suspendedaReasonDictIdsFlat.length > 0) {
          this.$refs.suspendedaReasonDictIdsRef.validate(flag => {
            if (flag) {
              this.handleHangUp()
            }
          })
        } else {
          this.handleHangUp()
        }
      } else if (this.actionType ==='reject') {
        if(this.rejectMessageRequired){
          this.$refs.flowMessageRef.validate(flag => {
            if (flag) {
              this.handleRejectEvent()
            }
          })
        }else{
          this.handleRejectEvent()
        }
      } else if (this.actionType ==='turnto') {
        this.turnToEvent()
      } if (this.actionType ==='transfer') {
        this.transferEvent()
      } else if (this.actionType ==='addSign') {
        this.addSignEvent()
      } else if (this.actionType ==='refuse') {
        if(this.refuseMessageRequired){
          this.$refs.flowMessageRef.validate(flag => {
            if (flag) {
              this.refuseEvent()
            }
          })
        }else{
          this.refuseEvent()
        }
      }
    },
    handleRejectEvent() {
      this.handleApprovalCheckChange(1)
      if(!this.rejectNode){
        this.$message({
          type:'error',
          message: '请选择驳回环节'
        })
        return;
      }
      if (this.rejectReasonDictIdsFlat.length > 0) {
        this.$refs.rejectReasonDictIdsRef.validate(flag => {
          if (flag) {
            this.handleVerticalSubmitMessage()
          }
        })
      } else {
        this.handleVerticalSubmitMessage()
      }
    },
    handleHangUp () {
      this.$confirm('确认挂起？', '提示').then(async () => {
        try {
          const suspendedaReasonDictIds = this.suspendedaReasonDictIdsModel.suspendedaReasonDictIds
          const submitData = {
            reason: this.hangUpMessage,
            taskId: this.taskId,
            userId: '',
            auditRecord: '',
            innerRemind: '',
            remind: '',
            suspendedaReasonDictIds: suspendedaReasonDictIds ? suspendedaReasonDictIds : []
          }
          this.loading = true
          await this.hangup(submitData)
          this.loading = false
          this.$message({
            type: 'success',
            message: '挂起成功'
          })
          this.$emit('hangup')
          this.$utils.removeCurrentTab(this.$route)
          this.handleEmitRefresh()
          this.$router.push(this.backRouter)
        } catch (error) {
          console.error(error)
          this.loading = false
        }
      })
    },
    hangup (data) {
      return this.$http({
        url: '/bpm/api/task-suspendeda-ctivate',
        method: 'post',
        data
      }).then(res => {
        return res
      })
    },
    turnToEvent () {
      this.$confirm('确认转办？', '提示').then(async () => {
        try {
          const submitData = {
            reason: this.turntoMessage,
            taskId: this.taskId,
            auditRecord: '',
            innerRemind: '',
            remind: '',
            userId: '',
            turnTowardUserId: this.turnToUser
          }
          this.loading = true
          await this.turnto(submitData)
          this.$message({
            type: 'success',
            message: '转办成功'
          })
          this.loading = false
          this.$emit('turnto')
          this.$utils.removeCurrentTab(this.$route)
          this.handleEmitRefresh()
          this.$router.push(this.backRouter)
        } catch (error) {
          console.error(error)
          this.loading = false
        }
      })
    },
    turnto (data) {
      return this.$http({
        url: '/bpm/api/task-turn-toward',
        method: 'post',
        data
      }).then(res => {
        return res
      })
    },
    addSignEvent () {
      this.$confirm('确认加签？', '提示').then(async () => {
        try {
          const submitData = cloneDeep(this.addSignData)
          submitData.taskId = this.taskId
          this.loading = true
          await this.addSign(submitData)
          this.$message({
            type: 'success',
            message: '加签成功'
          })
          this.loading = false
          this.$emit('addSign')
          this.$utils.removeCurrentTab(this.$route)
          this.handleEmitRefresh()
          this.$router.push(this.backRouter)
        } catch (error) {
          console.error(error)
          this.loading = false
        }
      })
    },
    addSign (data) {
      return this.$http({
        url: '/bpm/api/task-after-addsign',
        method: 'post',
        data
      }).then(res => {
        return res
      })
    },
    transferEvent () {
      this.$confirm('确认转移？', '提示').then(async () => {
        try {
          const submitData = cloneDeep(this.transferData)
          submitData.taskId = this.taskId
          submitData.candidateGroups = submitData.candidateGroups ? submitData.candidateGroups.split(',') : []
          submitData.candidateUsers = submitData.candidateUsers ? submitData.candidateUsers.split(',') : []
          delete submitData.type;
          this.loading = true
          await this.transfer(submitData)
          this.$message({
            type: 'success',
            message: '转移发起成功'
          })
          this.loading = false
          this.$emit('transfer')
          this.$utils.removeCurrentTab(this.$route)
          this.handleEmitRefresh()
          this.$router.push(this.backRouter)
        } catch (error) {
          console.error(error)
          this.loading = false
        }
      })
    },
    transfer (data) {
      return this.$http({
        url: '/bpm/api/task-transfer',
        method: 'post',
        data
      }).then(res => {
        return res
      })
    },
    getImageList(){
      this.$http({
        url: '/bpm/api/task/files/' +this.taskId,
        method: 'get'
      }).then((res) => {
        this.filesList = res.data;
        if (this.filesList && this.filesList.length > 0) {
          this.filesList.forEach(item => {
            const message = JSON.parse(item.message)
            const url = '/bpm/api/task/file-download/'+ this.taskId + '/'+ item.id
            item.name = message.fileName + message.fileSuffix
            item.url = url
          })
        }
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '获取流程附件出错'
        })
      });
    },
    // 图片删除
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleUploadSuccess(response, file, fileLis){
      this.getImageList()
    },
    handleOnRemove (file) {
      return this.$http({
        url: '/bpm/api/task/file-delete/' + this.taskId + '/' + file.id,
        method: 'post'
      }).then((res) => {
        return res
      })
    },
    handleBeforeRemove (file) {
      return new Promise((resolve,reject) => {
        this.$confirm('确认删除当前附件？','删除提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(async () => {
          try {
            await this.handleOnRemove(file)
            this.getImageList();
            this.$message({
              type: 'success',
              message: '删除流程附件成功'
            })
            resolve(true)
          } catch (error) {
            reject(false)
            this.$message({
              type: 'error',
              message: '删除流程附件出错'
            })
          }
        }).catch(() => {
          reject(false)
        })
      })
    },
    handleImageMouseOut(index){
      this.activeItemIndex = '';
    },
    handleImageMouseOver(index){
      this.activeItemIndex = index;
    },
    handleViewImage(item){
      this.dialogVisible = true;
      this.dialogImageUrl = '/bpm/api/task/file-download/' + this.taskId + '/' + item.id;
    },
    handleViewTimeLineImage(url){
      this.dialogVisible = true;
      this.dialogImageUrl = url;
    },
    handleDownload(item){
      let a = document.createElement('a');
      if(typeof a.download === 'undefined'){
        let newUrl = window.location.protocol + "//" + window.location.host + '/bpm/api/task/file-download/'+ this.taskId + '/'+ item.id;
        window.open(newUrl);
      }
    },
    handleDeleteImage(item){
      this.$confirm('确认删除当前附件？','删除提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$http({
          url: '/bpm/api/task/file-delete/' + this.taskId + '/' + item.id,
          method: 'delete'
        }).then((res) => {
          this.getImageList();
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '删除流程附件出错'
          })
        });
      })
    },
    // 切换到审批
    changeType(){
      this.showApprovalMessage = false;
    },
    // 原因选择 
    handleReasonChange(val){
      this.reason = val;
    },
    // 获取驳回是否显示按钮,以及驳回的id
    getConfig(){
      this.$http({
        method: 'get',
        url: '/bpm/api/task-opconfig/' + this.taskId
      }).then((res) => {
        if(res.status === 200){
          const resData = res.data
          this.taskName = resData.taskName
          if(resData.refuseAble){
            this.showRefuse = true;
          }
          if(resData.reasonAble){
            this.showConditionMessage = true;
          }
          if(resData.innerRemindAble){
            this.showInnerMessage = true;
          }
          this.rejectReasons = resData.rejectReasons;
          if(resData.completeReasons){
            this.completeReasons = resData.completeReasons;
          }
          if(resData.completeGroupReasons){
            this.completeGroupReasons = resData.completeGroupReasons;
          }
          if(resData.refuseReasons){
            this.refuseReasons = resData.refuseReasons;
          }
          if(resData.refuseGroupReasons){
            this.refuseGroupReasons = resData.refuseGroupReasons;
          }
          if(resData.canRejectNodes){
            this.rejectActivitys = resData.canRejectNodes;
            if (this.rejectActivitys && this.rejectActivitys.length > 0) {
              this.rejectNode = this.rejectActivitys[0].activityId
            }
            this.showReject = true
          } else {
            this.showReject = false;
          }
          if(resData.rejectGroupReasons){
            this.rejectGroupReasons = resData.rejectGroupReasons;
          }
          if (resData.canTurnTowardUsers) {
            this.showTurnto = true
            this.turnTowardUsers = resData.canTurnTowardUsers
          } else {
            this.showTurnto = false
          }
          if (resData.transferTaskAble) {
            this.showTransfer = true
            this.showTurnto = false
          } else {
            this.showTransfer = false
          }
          if (resData.afterAddSignAble) {
            this.showAddSign = true
          }
          if (resData.rejectReasonDictIds) {
            this.rejectReasonDictIdsTree = this.$utils.flatToTree(resData.rejectReasonDictIds)
            this.rejectReasonDictIdsFlat = this.getFlatTreeData(this.rejectReasonDictIdsTree)
          }
          if (resData.suspendedaReasonDictIds) {
            this.suspendedaReasonDictIdsTree = this.$utils.flatToTree(resData.suspendedaReasonDictIds)
            this.suspendedaReasonDictIdsFlat = this.getFlatTreeData(this.suspendedaReasonDictIdsTree)
          }
          if (resData.refuseReasonDictIds) {
            this.refuseReasonDictIdsTree = this.$utils.flatToTree(resData.refuseReasonDictIds)
            this.refuseReasonDictIdsFlat = this.getFlatTreeData(this.refuseReasonDictIdsTree)
          }
          if (resData.opReject) {
            this.showRejectNonstop = true
          } else {
            this.showRejectNonstop = false
          }
        }
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '请求流程按钮配置出错'
        })
      });
    },
    getFlatTreeData (option, treeOptionFlat) {
      const treeOption = treeOptionFlat ? treeOptionFlat : []
      if (option && Array.isArray(option) && option.length > 0) {
        option.forEach(item => {
          if (item.children && Array.isArray(item.children) && item.children.length > 0) {
            this.getFlatTreeData(item.children, treeOption)
          } else {
            treeOption.push(item)
          }
        })
      }
      return treeOption
    },
    // 获取任务详细
    getTaskDetail(){
      this.$http({
        method: 'get',
        url: '/bpm/api/task/info/' + this.taskId
      }).then((res) => {
        if(res.data){
          this.taskDetail = res.data
        }
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '请求任务详细出错'
        })
      });
    },
    getTaskId(){
      if(this.$route.query && this.$route.query.taskId){
        this.taskId = this.$route.query.taskId;
        this.showFlow = true;
        this.getConfig();
        // this.getTaskDetail();
      }
      if(this.$route.query && this.$route.query.processInstanceId){
        this.processInstanceId = this.$route.query.processInstanceId
      }
    },
    handleAgreeBeforeAction() {
      if (this.operation) {
        if (this.showType === 'horizontal') {
          this.$emit('update:showMessage', true);
        }
      } else {
        this.$message({
          type: 'info',
          message: this.operationMessage
        })
      }
      if (!!this.agreeBeforeAction && this.agreeAsyncHttp) {
        return this.agreeBeforeAction;
      } else {
        if (!this.agreeBeforeAction()) {
          return false;
        }
        return true;
      }
    },
    handleBeforeAction(){
      if(!this.beforeAction()){
        return false;
      }
      if(this.operation){
        if(this.showType === 'horizontal'){
          this.$emit('update:showMessage',true);
        }
      } else {
        this.$message({
          type: 'info',
          message: this.operationMessage
        })
      }
      return true;
    },
    agreeEvent () {
      if(this.completeMessageRequired){
          this.$refs.flowMessageRef.validate(flag => {
            if (flag) {
              this.handleApprovalCheckChange(0)
              this.handleVerticalSubmitMessage()
            }
        })
      }else{
          this.handleApprovalCheckChange(0)
          this.handleVerticalSubmitMessage()
      }
    },
    refuseEvent () {
      if (this.refuseReasonDictIdsFlat.length > 0) {
        this.$refs.refuseReasonDictIdsRef.validate(flag => {
          if (flag) {
            this.handleApprovalCheckChange(2)
            this.handleVerticalSubmitMessage()
          }
        })
      } else {
        this.handleApprovalCheckChange(2)
        this.handleVerticalSubmitMessage()
      }
    },
    rejectEvent () {
      this.actionType = 'reject'
      // this.handleApprovalCheckChange(1)
      // if(!this.rejectNode){
      //   this.$message({
      //     type:'error',
      //     message: '请选择驳回环节'
      //   })
      //   return;
      // }
      // this.handleVerticalSubmitMessage()
    },
    // 选择的审批类型: 0:通过,1:驳回,2:拒绝
    handleApprovalCheckChange(label){
      this.approvalCheckedType = label;
      if(label === 0){
        this.handleAgree();
      } else if(label === 1){
        this.handleReject();
      } else if(label === 2){
        this.handleRefuse();
      }
      // this.reason = '';
      // this.auditRecord = '';
      // this.rejectNode = '';
      this.$emit('approval-change',label);
    },
    // 点击通过按钮
    handleAgree(){
      this.approvalType = 'agree';
      if(this.showType === 'horizontal'){
        this.$emit("change",'submit');
       if(this.submitBefore){
          this.submitBeforeAction();
        } else {
          this.handleBeforeAction()
        }
      } else {
        this.$emit("change",'agree');
        this.reasonList = this.completeReasons;
        this.reasonGroupObject = this.completeGroupReasons;
        this.operationType = true;
      }
    },
    // 点击驳回驳回按钮
    handleReject(){
       this.approvalType = 'reject';
      if(this.showType === 'horizontal'){
        this.$emit("change",'back');
        // if(this.handleBeforeAction()){
          this.reasonList = this.rejectReasons;
          this.reasonGroupObject = this.rejectGroupReasons
          this.messageTitle = "驳回";
          this.operationType = false;
          this.$emit('update:showMessage',true);
          // this.handleSubmitMessage();
        // }
      } else {
        this.$emit("change",'reject');
        this.reasonList = this.rejectReasons;
        this.reasonGroupObject = this.rejectGroupReasons
        this.messageTitle = "驳回";
        this.operationType = false;
      }
    },
    // 点击拒绝按钮
    handleRefuse(){
      this.approvalType = 'refuse';
      this.$emit("change",'refuse');
      if(this.showType === 'horizontal'){
        if(this.handleBeforeAction()){
          this.reasonList = this.refuseReasons;
          this.reasonGroupObject = this.refuseGroupReasons
          this.messageTitle = "拒绝";
          // this.$emit('update:showMessage',true);
        }
    } else {
      this.reasonList = this.refuseReasons;
      this.reasonGroupObject = this.refuseGroupReasons
    }
    },
    handleBack(){
      this.$utils.removeCurrentTab(this.$route)
      this.handleEmitRefresh()
      this.$router.push(this.confirmBackRouter);
    },
    handleEmitRefresh() {
      this.$eventBus.emit('refresh')
    },
    // 关闭意见
    handleCloseMessage(){
      // this.$confirm('确认关闭?','关闭',{
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      // }).then(() => {
        this.$emit('update:showMessage',false);
      // });
    },
    handleVerticalSubmitMessage(){
      if((this.reasonGroupObject && Object.keys(this.reasonGroupObject).length > 0) || (this.reasonList && this.reasonList.length > 0)){
        let message;
        if(this.approvalType === 'agree'){
          message = '请选择通过原因';
        } else if(this.approvalType === 'reject'){
          message = '请选择驳回原因';
        }else if(this.approvalType === 'refuse'){
          message = '请选择拒绝原因';
        }
        if(!this.reason){
          this.$message({
            type: 'error',
            message: message
          });
          return;
        }
      }
      // if(!this.outMessage){
      //     this.$message({
      //       type: 'error',
      //       message: '请输入审批意见'
      //     });
      //     return;
      //   }
      // if(!this.message){
      //   this.$message({
      //     type: 'error',
      //     message: '请输入内部意见'
      //   });
      //   return;
      // }
      if(this.agreeBefore && this.approvalType === 'agree'){
        if(this.autoOperate){
          this.loading = true
          if(this.agreeAsyncHttp){
            this.agreeBeforeAction().then((valid) => {
              if(valid){
                this.handleSubmitMessage();
              } else {
                this.loading = false
              }
            })
          }else {
            if(this.handleAgreeBeforeAction()){
              this.handleSubmitMessage();
            } else {
              this.loading = false
            }
          }
        } else {
          this.handleAgreeBeforeAction();
        }
      }
      if(this.approvalType === 'reject'){
        if(this.autoReject){
          this.loading = true
          if (this.rejectAsyncHttp) {
            this.rejectBeforeAction().then(valid => {
              if (valid) {
                this.handleSubmitMessage();
              } else {
                this.loading = false
              }
            })
          } else {
            if(this.rejectBeforeAction()) {
              this.handleSubmitMessage();
            } else {
              this.loading = false
            }
          }
       } else {
         this.rejectBeforeAction()
       }
      }
      if(this.approvalType === 'refuse'){
       if(this.autoRefuse){
        this.loading = true
        if (this.refuseAsyncHttp) {
          this.refuseBeforeAction().then(valid => {
            if (valid) {
              this.handleSubmitMessage();
            } else {
              this.loading = false
            }
          })
        } else {
          if(this.refuseBeforeAction()){
            this.handleSubmitMessage();
          } else {
              this.loading = false
            }
        }
        } else {
          this.refuseBeforeAction()
        }
      }
    },
    handleHorizontalSubmitMessage(){
      if(this.approvalType === 'agree'){
        if(!this.autoSubmit){
          this.beforeSubmitAction()
        } else {
          this.handleSubmitMessage();
        }
      }
      if(this.approvalType === 'refuse'){
        if(!this.autoHorizontalRefuse){
          this.beforeHorizantalRefuseAction()
        } else {
          this.handleSubmitMessage();
        }
      }
      if(this.approvalType === 'reject'){
        if(!this.autoHorizontalReject){
          this.beforeHorizantalRejectAction()
        } else {
          this.handleSubmitMessage();
        }
      } 
    },
    handleSubmitMessage(){
      this.loading = true
      let submit = this.submitMessage();
      window.Promise.all([submit]).then(() => {
        this.loading = false
        this.$emit('after-action', this.messageSuccess);
        if (this.messageSuccess) {
          this.$utils.removeCurrentTab(this.$route)
          this.handleEmitRefresh()
          this.$router.push(this.backRouter);
        }
      }).catch((error) => {
        console.log(error);
        this.loading = false
      })
    },
    // 意见提交,operationType: true 通过
    submitMessage(){
      let url;
      let submitData = {};
      // let success = false;
      if (this.showType === 'horizontal') {
        if (this.approvalType === 'agree') {
          url = '/bpm/api/task-complete';
          submitData = {
            auditRecord: this.auditRecord,
            innerRemind: this.message,
            remind: this.flowMessageModel.outMessage,
            reason: this.conditionMessage,
            taskId: this.taskId
          }
        }else if(this.approvalType === 'reject'){
          url = '/bpm/api/task-reject';
          submitData = {
            targetActivityId: this.rejectActivitys[0].activityId,
            rejectNonstop: this.rejectNonstop,
            remind: this.flowMessageModel.outMessage,
            taskId: this.taskId
          }
        } else if(this.approvalType === 'refuse'){
          url = '/bpm/api/task-refuse';
          submitData = {
            remind: this.flowMessageModel.outMessage,
            taskId: this.taskId
          }
        }
      }else {
        if((this.reasonGroupObject && Object.keys(this.reasonGroupObject).length > 0) || (this.reasonList && this.reasonList.length > 0)){
          let message;
          if(this.approvalType === 'agree'){
            message = '请选择通过原因';
          } else if(this.approvalType === 'reject'){
            message = '请选择驳回原因';
          }else if(this.approvalType === 'refuse'){
            message = '请选择拒绝原因';
          }
          if(!this.reason){
            this.$message({
              type: 'error',
              message: message
            });
            return;
          }
        }
        // if(!this.message){
        //   this.$message({
        //     type: 'error',
        //     message: '请输入内部意见'
        //   });
        //   return;
        // }
        // if(!this.outMessage){
        //   this.$message({
        //     type: 'error',
        //     message: '请输入外部意见'
        //   });
        //   return;
        // }
        if(this.approvalType === 'agree'){
          url = '/bpm/api/task-complete';
          submitData = {
            auditRecord: this.auditRecord,
            innerRemind: this.message,
            remind: this.flowMessageModel.outMessage,
            reason: this.conditionMessage,
            taskId: this.taskId
          }
        }else if(this.approvalType === 'reject'){
          url = '/bpm/api/task-reject';
          const rejectReasonDictIds = this.rejectReasonDictIdsModel.rejectReasonDictIds
          submitData = {
            auditRecord: this.auditRecord,
            innerRemind: this.message,
            remind: this.flowMessageModel.outMessage,
            targetActivityId: this.rejectNode,
            reason: this.reason,
            taskId: this.taskId,
            rejectReasonDictIds: rejectReasonDictIds ? rejectReasonDictIds : []
          }
        } else if(this.approvalType === 'refuse'){
          const refuseReasonDictIds = this.refuseReasonDictIdsModel.refuseReasonDictIds
          url = '/bpm/api/task-refuse';
          submitData = {
            auditRecord: this.auditRecord,
            innerRemind: this.message,
            remind: this.flowMessageModel.outMessage,
            reason: this.reason,
            taskId: this.taskId,
            refuseReasonDictIds: refuseReasonDictIds ? refuseReasonDictIds : []
          }
        }
      }
        
      return this.$http({
        method: 'post',
        url: url,
        data: submitData
      }).then((res) => {
        if(res.status === 200){
          let successMessage = '';
          if(this.approvalType === 'agree'){
            if(this.showType === 'horizontal'){
              successMessage = "提交成功";
            } else {
              successMessage = "通过成功";
            }
          } else if(this.approvalType === 'reject') {
            if(this.showType === 'horizontal'){
              successMessage = "驳回成功";
              this.$emit('update:showMessage',false);
            } else {
              successMessage = "驳回成功";
            }
          } else {
            successMessage = "拒绝成功";
          }
           this.$message({
            type: 'success',
            message: successMessage
          })
          this.messageSuccess = true;
        }
      }).catch(() => {
        let errorMessage = '';
        if(this.approvalType === 'agree'){
          if(this.showType === 'horizontal'){
            errorMessage = "提交失败";
          } else {
            errorMessage = "通过失败";
          }
        } else if(this.approvalType === 'reject'){
          if(this.showType === 'horizontal'){
            errorMessage = "驳回失败";
          } else {
            errorMessage = "驳回失败";
          }
        } else {
          errorMessage = "拒绝失败";
        }
        this.$message({
          type: 'error',
          message: errorMessage
        })
        this.messageSuccess = false;
      });
      
    },
  },
  created() {
    this.getTaskId();
    this.getImageList();
  }
}
</script>