<template>
  <div v-if="showFlow" class="aos-flow">
    <div class="aos-flow-horizontal" v-if="showType === 'horizontal'">
      <!-- 步骤区 -->
      <div class="aos-flow-step clearfix">
        <!-- <el-steps :active="active" :space="286" finish-status="success">
          <el-step title="">
            <template slot="icon">
              <i class="el-icon-more" title="查看历史信息" @click="handleCheckHistory"></i>
            </template>
          </el-step>
          <el-step title="">
            <template slot="icon">
              <i class="el-icon-edit" title=""></i>
            </template>
          </el-step>
        </el-steps> -->
        <div class="aos-flow-task">
          <span class="aos-flow-task-title">任务名称 : </span>
          <span class="aos-flow-task-name" :title="taskDetail.processInstanceName">{{taskDetail.processInstanceName}}</span>
        </div>
        <div class="aos-flow-task">
          <span class="aos-flow-task-title">当前环节 : </span>
          <span class="aos-flow-task-name" :title="taskDetail.name">{{taskDetail.name}}</span>
        </div>
      </div>
      <!-- 按钮区 -->
      <div class="aos-flow-button clearfix">
        <el-button type="text" @click="handleCheckHistory" icon="el-icon-tickets">审批意见</el-button>
        <slot name="flow-button"></slot>
        <el-button :disabled="disabled" type="primary" @click="handleAgree">提交</el-button>
        <el-button :disabled="disabled" v-if="showReject" @click="handleReject">退回</el-button>
        <el-button :disabled="disabled" v-if="showRefuse" @click="handleRefuse">拒绝</el-button>
        <el-button v-if="showBackBtn" @click="handleBack">返回</el-button>
      </div>
      <el-dialog
        :title="messageTitle"
        :visible.sync="showMessage"
        width="30%"
        :before-close="handleCloseMessage"
        :append-to-body="true">
        <div class="aos-flow-message">
          <!-- <div>
            <span class="aos-flow-message-title">审批意见</span>
            <el-input type="textarea" v-model="auditRecord"></el-input>
          </div>
          <div>
            <span class="aos-flow-message-title">内部意见</span>
            <el-input type="textarea" v-model="message"></el-input>
          </div> -->
          <div>
            <span class="aos-flow-message-title">意见</span>
            <el-input type="textarea" :autosize="{minRows:2}" v-model="outMessage"></el-input>
          </div>
          <!-- <div v-if="reasonList && reasonList.length > 0">
            <span class="aos-flow-message-title">意见</span>
            <el-select v-model="reason" placeholder="请选择原因" style="display:block">
              <el-option
                v-for="item in reasonList"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </div>
          <div v-if="showRejectRadio && rejectActivitys.length > 0">
            <span class="aos-flow-message-title">选择驳回环节</span>
            <div>
              <el-radio-group v-model="rejectNode" class="aos-flow-reject-group">
                <el-radio class="aos-flow-reject-radio" v-for="item in rejectActivitys" :key="item.activityId" :label="item.activityId">{{item.activityName}}</el-radio>
              </el-radio-group>
              </div>
          </div> -->
        </div>
        <span slot="footer">
          <el-button @click="handleCloseMessage">取消</el-button>
          <el-button type="primary" @click="handleHorizontalSubmitMessage">确定</el-button>
        </span>
      </el-dialog>
    </div>
    <div v-else class="aos-flow-vertical">
      <div class="aos-part">
        <el-button type="text" @click="changeType" icon="el-icon-setting">审批</el-button>
        <span style="margin: 0 8px;">/</span>
        <el-button style="margin-left: 0px;" type="text" @click="handleCheckHistory" icon="el-icon-tickets">审批意见</el-button>
      </div>
      <div v-show="!showApprovalMessage">
        <div class="aos-part">审批类型 : </div>
        <div class="aos-part">
          <el-radio-group v-model="approvalCheckedType" @change="handleApprovalCheckChange">
            <el-radio :disabled="disabled" :label="0">通过</el-radio>
            <el-radio :disabled="disabled" :label="1" v-if="showReject">驳回</el-radio>
            <el-radio :disabled="disabled" :label="2" v-if="showRefuse">拒绝</el-radio>
          </el-radio-group>
        </div>
        <div class="aos-part" v-if="(reasonList && reasonList.length > 0) || Object.keys(reasonGroupObject).length > 0">
          <span class="aos-flow-message-title">意见 : </span>
        </div>
        <div class="aos-part" v-if="Object.keys(reasonGroupObject).length === 0 && reasonList && reasonList.length > 0">
          <el-select v-model="reason" @change="handleReasonChange" placeholder="请选择原因" style="display:block">
            <el-option
              v-for="item in reasonList"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </div>
        <div class="aos-part" v-if="reasonGroupObject && Object.keys(reasonGroupObject).length > 0">
          <el-select v-model="reason" @change="handleReasonChange" placeholder="请选择原因" style="display:block">
            <el-option-group v-for="(item,index) in reasonGroupObject" :key="index" :label="index">
              <el-option
                v-for="child in item"
                :key="child"
                :label="child"
                :value="child">
              </el-option>
            </el-option-group>
          </el-select>
        </div>
        <div class="aos-part"  v-if="showRejectRadio && rejectActivitys.length > 0">
          <span class="aos-flow-message-title">选择驳回环节 : </span>
        </div>
        <div class="aos-part" v-if="showRejectRadio && rejectActivitys.length > 0">
          <div>
            <el-radio-group v-model="rejectNode" class="aos-flow-reject-group">
              <el-radio class="aos-flow-reject-radio" v-for="item in rejectActivitys" :key="item.activityId" :label="item.activityId">{{item.activityName}}</el-radio>
            </el-radio-group>
          </div>
        </div>
        <!-- <div class="aos-part">
          <span class="aos-flow-message-title">审批意见 : </span>
        </div>
        <div class="aos-part">
          <el-input type="textarea" v-model="auditRecord" placeholder="请在此输入审批意见"></el-input>
        </div> -->
        <div class="aos-part">
          <span class="aos-flow-message-title">内部意见 : </span>
        </div>
        <div class="aos-part">
          <el-input type="textarea" :autosize="{minRows:2}" v-model="message"  placeholder="请在此输入内部意见"></el-input>
        </div>
        <div class="aos-part">
          <span class="aos-flow-message-title">外部意见 : </span>
        </div>
        <div class="aos-part">
          <el-input type="textarea" :autosize="{minRows:2}" v-model="outMessage" placeholder="请在此输入外部意见"></el-input>
        </div>
        <div class="aos-images">
          <div class="aos-image-box" v-for="(item,index) in imagesList" :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
            class="aos-flow-upload"
            :action='"/bpm/api/task/upload/"+taskId'
            :on-success="handleUploadSuccess"
            :show-file-list="false">
            <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>
        <el-dialog :visible.sync="dialogVisible" :append-to-body="true" title="流程附件预览">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <div class="aos-part aos-submit-btn">
          <el-button type="primary" @click="handleVerticalSubmitMessage">确定</el-button>
        </div>
      </div>
      <div v-show="showApprovalMessage">
        <!-- <el-timeline>
          <el-timeline-item v-for="(item,index) in translateHistoryDetailList" :key="index" color="#0bbd87"  :timestamp="item.date" placement="top">
            <el-card>
              <div class="aos-flow-history-title">
                <span>{{item.taskType}}</span>
                <span>{{item.userCode}}</span>
                <span>{{item.userName}}</span>
              </div>
              <div class="aos-flow-histoory-detail">
                <span>{{item.messageType}} : </span>
                <span>{{item.message}}</span>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline> -->
        <el-timeline :reverse="reverse">
          <el-timeline-item
            v-for="(ele,key) in translateHistoryDetailList"
            :key="key"
            :timestamp="$time.formatTime(ele.date)"
            placement="top"
            :color="ele.color"
          >
            <el-card v-if="!ele.startEnd">
              <h4>
                【{{ele.taskName}}】{{ele.userName}}
                <span>{{$time.formatTime(ele.date)}}</span>
              </h4>
              <p v-if="ele.url && ele.url.length > 0">
                <template v-for="(item,index) in ele.url">
                  <img v-if="item.type !== 'pdf'" :key="index" :src="item.url" alt="" style="width:150px;cursor: pointer;" title="点击预览大图" @click="handleViewTimeLineImage(item.url)"/>
                  <span v-else :key="index"><i class="el-icon-pdf"></i></span>
                </template>
              </p>
              <p><span style="font-weight:600;">{{ele.operate}}</span><span v-if="ele.reason"><span style="font-weight:600;">原因：</span>{{ele.reason}}</span></p>
              <p v-if="ele.remind"><span style="font-weight:600;">意见：</span>{{ele.remind}}</p>
              <p v-if="ele.innerRemind"><span style="font-weight:600;">内部意见：</span>{{ele.innerRemind}}</p>
              <p v-if="ele.auditRecord"><span style="font-weight:600;">备注：</span>{{ele.auditRecord}}</p>
              <div v-if="ele.changeRecord && ele.changeRecord.length > 0">
                <span style="font-weight:600;">任务人变更记录：</span>
                <p style="padding-left:16px" v-for="(item,index) in ele.changeRecord" :key="index">{{item.record}}</p>
              </div>
            </el-card>
            <el-card v-if="ele.startEnd">
              <h4>
                <span>{{ele.startEndName}}</span>
              </h4>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>
    
    <el-dialog
      title="历史审批"
      :visible.sync="showHistory"
      width="50%"
      :before-close="handleCloseHistory"
      :append-to-body="true">
      <div class="aos-flow-history">
        <el-timeline :reverse="reverse">
          <el-timeline-item
            v-for="(ele,key) in translateHistoryDetailList"
            :key="key"
            :timestamp="$time.formatTime(ele.date)"
            :color="ele.color"
            placement="top"
          >
            <el-card v-if="!ele.startEnd">
              <h4>
                【{{ele.taskName}}】{{ele.userName}}
                <span>{{$time.formatTime(ele.date)}}</span>
              </h4>
              <p v-if="ele.url && ele.url.length > 0">
                <template v-for="(item,index) in ele.url">
                  <img v-if="item.type !== 'pdf'" :key="index" :src="item.url" alt="" style="width:150px;cursor: pointer;" title="点击预览大图" @click="handleViewTimeLineImage(item.url)"/>
                  <span v-else :key="index" ><i class="el-icon-pdf"></i></span>
                </template>
              </p>
              <p><span style="font-weight:600;">{{ele.operate}}</span><span v-if="ele.reason"><span style="font-weight:600;">原因：</span>{{ele.reason}}</span></p>
              <p v-if="ele.remind"><span style="font-weight:600;">意见：</span>{{ele.remind}}</p>
              <p v-if="ele.innerRemind"><span style="font-weight:600;">内部意见：</span>{{ele.innerRemind}}</p>
              <p v-if="ele.auditRecord"><span style="font-weight:600;">备注：</span>{{ele.auditRecord}}</p>
              <div v-if="ele.changeRecord && ele.changeRecord.length > 0">
                <span style="font-weight:600;">任务人变更记录：</span>
                <p style="padding-left:16px" v-for="(item,index) in ele.changeRecord" :key="index">{{item.record}}</p>
              </div>
            </el-card>
            <el-card v-if="ele.startEnd">
              <h4>
                <span>{{ele.startEndName}}</span>
              </h4>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
  </div>
</template>
<script>
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有异步请求
    agreeAsycHttp: {
      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
      }
    }
  },
  data(){
    return {
      showFlow: false, // 是否显示流程审批按钮
      active: 0,
      showReject: false, //是否显示驳回按钮
      showRefuse: false, // 是否显示拒绝按钮
      showRejectRadio: false, // 是否显示驳回环节
      rejectActivitys: '', // 驳回信息(包含环节等)
      refuseReasons: [], // 拒绝原因
      rejectReasons: [], // 驳回原因
      completeReasons: [], // 通过原因
      completeGroupReasons: {}, // 通过的组原因
      refuseGroupReasons: {}, // 通过的组原因
      rejectGroupReasons: {}, // 通过的组原因
      reasonList: [], //原因
      reasonGroupObject: {}, //组原因
      taskId: '', // 当前任务id
      processInstanceId: '', //流程id
      startEndMessage: '', // 审批开始结束信息
      showHistory: false, // 显示历史信息
      taskDetail: '', // 任务详细
      historyDetailList: '', // 历史审批意见,
      translateHistoryDetailList: '', // 转换过类型的历史审批意见
      messageTitle: '', //意见dailog名称
      operationType: true, // 操作的类型,true为通过,false为驳回
      // showMessage: false, // 是否显示意见dialog 改为双向数据绑定
      message: '', // 内部意见
      outMessage: '', //外部意见
      reason:'', // 选择的原因
      rejectNode: '', //驳回节点
      auditRecord: '', // 审批意见
      messageSuccess: false, // 通过或拒绝是否成功
      approvalCheckedType: '',
      rejectType:'',
      showApprovalMessage: false, // 切换审批和审批意见,默认为审批
      approvalType: '', // 当前审批类型
      reverse: false,
      dialogImageUrl: '', // 图片的url
      dialogVisible: false, // 图片预览
      imagesList: [],
      activeItemIndex: ''
    }
  },
  methods: {
    getImageList(){
      this.$http({
        url: '/bpm/api/task/files/' +this.taskId,
        method: 'get'
      }).then((res) => {
        this.imagesList = res.data;
      }).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.imagesList.push(response)
    },
    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
          if(resData.rejectAble){
            this.showReject = true;
          }
          if(resData.refuseAble){
            this.showRefuse = 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.rejectActivitys){
            this.rejectActivitys = resData.rejectActivitys; 
          }
          if(resData.rejectGroupReasons){
            this.rejectGroupReasons = resData.rejectGroupReasons;
          }
        }
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '请求流程按钮配置出错'
        })
      });
    },
    // 获取审批意见
    getApprovalMessage(){
      this.$http({
        method: 'get',
        url: '/bpm/api/task/comment-by-taskid/' + this.taskId
      }).then((res) => {
        const resData = res;
        const that = this;
        let getStartEnd = that.getStartEnd();
        window.Promise.all([getStartEnd]).then(() => {
          that.historyDetailList = resData.data;
          that.translateHistoryDetailList = JSON.parse(JSON.stringify(resData.data));
          let commentsTemp = {};
          if (that.startEndMessage.endTime) {
            that.$set(commentsTemp, '00000000000000', {});
            that.$set(commentsTemp['00000000000000'], 'color', '#67C23A');
            that.$set(commentsTemp['00000000000000'], 'startEnd', true);
            that.$set(commentsTemp['00000000000000'], 'startEndName', '结束');
            that.$set(commentsTemp['00000000000000'], 'date', that.startEndMessage.endTime);
          }
          that.translateHistoryDetailList.forEach(element => {
            if (commentsTemp[element.taskId] === undefined) {
              that.$set(commentsTemp, element.taskId, {});
            }
            that.translateHistoryDetailList.forEach(element => {
              if (commentsTemp[element.taskId] == undefined) {
                that.$set(commentsTemp, element.taskId, {});
              }
              that.$set(commentsTemp[element.taskId],'taskName',element.taskName);
              if(element.type !== "claim"){
                that.$set(commentsTemp[element.taskId],'color','#67C23A');
                that.$set(commentsTemp[element.taskId], "userCode", element.userCode);
                if(element.userName){
                  that.$set(commentsTemp[element.taskId], "userName", element.userName);
                }
                that.$set(commentsTemp[element.taskId], "date", element.date);
                that.$set(commentsTemp[element.taskId],'startEnd',false);
              }
  
              // 意见内容
              if (element.type.indexOf("|remind") > -1){
                that.$set(commentsTemp[element.taskId], "remind", element.message);
              }else if (element.type.indexOf("|innerRemind") > -1){
                that.$set(commentsTemp[element.taskId], "innerRemind", element.message);
              }else if (element.type.indexOf("|auditRecord") > -1){
                that.$set(commentsTemp[element.taskId], "auditRecord", element.message);
              }else if (element.type.indexOf("|reason") > -1){
                that.$set(commentsTemp[element.taskId], "reason", element.message);
              }
  
              // 操作类型
              if(element.type === "optype"){
                if(element.message === 'complete'){
                  that.$set(commentsTemp[element.taskId], "operate", '同意');
                }else if (element.message === 'reject'){
                  that.$set(commentsTemp[element.taskId], "operate", '驳回');
                }else if (element.message === 'refuse'){
                  that.$set(commentsTemp[element.taskId], "operate", '拒绝');
                }
              } else if(element.type === "file"){
                that.$set(commentsTemp[element.taskId],'type','file');
                if(!commentsTemp[element.taskId].url){
                  that.$set(commentsTemp[element.taskId],'url',[]);
                }
                commentsTemp[element.taskId].url.push({
                  type: element.message.split('.')[1],
                  url: '/bpm/api/task/file-download/'+ this.taskId + '/'+ element.id
                })
              }else if(element.type === "claim"){
                if(!commentsTemp[element.taskId].changeRecord){
                  that.$set(commentsTemp[element.taskId],'changeRecord',[]);
                }
                commentsTemp[element.taskId].changeRecord.push({
                  record: that.$time.formatTime(element.date) + ' ' + element.message
                })
              }else{
                if(element.type.indexOf("complete") > -1){
                  that.$set(commentsTemp[element.taskId], "operate", '同意');
                }else if (element.type.indexOf("reject") > -1){
                  that.$set(commentsTemp[element.taskId], "operate", '驳回');
                }else if (element.type.indexOf("refuse") > -1){
                  that.$set(commentsTemp[element.taskId], "operate", '拒绝');
                }
              }
            });
            if(that.startEndMessage.startTime){
              that.$set(commentsTemp,'start',{});
              that.$set(commentsTemp.start,'color','#67C23A');
              that.$set(commentsTemp.start,'startEnd',true);
              that.$set(commentsTemp.start,'startEndName','开始');
              that.$set(commentsTemp.start,'date',that.startEndMessage.startTime);
            }
            that.translateHistoryDetailList = commentsTemp;
          })
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '请求审批意见出错'
        })
      });
      })
    },
    // 获取任务详细
    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
      }
    },
    getStartEnd(){
      return this.$http({
        method: 'get',
        url: '/bpm/api/process/' + this.processInstanceId
      }).then((res) => {
        if(res.status === 200){
          this.startEndMessage = res.data;
        }
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '请求审批开始结束信息出错'
        })
      });
    },
    // 查看历史
    handleCheckHistory(){
      if(this.showType === 'horizontal'){
        this.showHistory = true;
      } else {
        this.showApprovalMessage = true;
      }
      this.getApprovalMessage();
    },
    // 关闭历史
    handleCloseHistory(){
      // this.$confirm('确认关闭?','关闭',{
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      // }).then(() => {
        this.showHistory = false;
      // });
    },
    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.agreeAsycHttp) {
        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;
    },
    // 选择的审批类型: 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.showRejectRadio = false;
        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.showRejectRadio = true;
          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.showRejectRadio = true;
        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.showRejectRadio = false;
          // this.$emit('update:showMessage',true);
        }
    } else {
      this.reasonList = this.refuseReasons;
      this.reasonGroupObject = this.refuseGroupReasons
      this.showRejectRadio = false;
    }
    },
    handleBack(){
      this.$router.push(this.confirmBackRouter);
    },
    // 关闭意见
    handleCloseMessage(){
      // this.$confirm('确认关闭?','关闭',{
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      // }).then(() => {
        this.$emit('update:showMessage',false);
      // });
    },
    handleVerticalSubmitMessage(){
      if(this.approvalCheckedType === ''){
        this.$message({
          type:'error',
          message: '请选择审批类型'
        })
        return;
      } else if(this.approvalCheckedType === 1){
        if(!this.rejectNode){
          this.$message({
            type:'error',
            message: '请选择驳回环节'
          })
          return;
        }
      }
      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.agreeBefore && this.approvalType === 'agree'){
        if(this.autoOperate){
          if(this.agreeAsycHttp){
            this.agreeBeforeAction().then((valid) => {
              if(valid){
                this.handleSubmitMessage();
              }
            })
          }else {
            if(this.handleAgreeBeforeAction()){
              this.handleSubmitMessage();
            }
          }
        } else {
          this.handleAgreeBeforeAction();
        }
      }
      if(this.approvalType === 'reject'){
       if(this.autoReject){
         if(this.rejectBeforeAction()){
           this.handleSubmitMessage();
         }
       } else {
         this.rejectBeforeAction()
       }
      }
      if(this.approvalType === 'refuse'){
       if(this.autoRefuse){
         if(this.refuseBeforeAction()){
           this.handleSubmitMessage();
         }
        } 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(){
      let submit = this.submitMessage();
      window.Promise.all([submit]).then(() => {
        this.$emit('after-action', this.messageSuccess);
        if (this.messageSuccess) {
          this.$router.push(this.backRouter);
        }
      }).catch((error) => {
        console.log(error);
      })
    },
    // 意见提交,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.outMessage,
            reason: this.reason,
            taskId: this.taskId
          }
        }else if(this.approvalType === 'reject'){
          url = '/bpm/api/task-reject';
          submitData = {
            targetActivityId: this.rejectActivitys[0].activityId,
            remind: this.outMessage,
            taskId: this.taskId
          }
        } else if(this.approvalType === 'refuse'){
          url = '/bpm/api/task-refuse';
          submitData = {
            remind: this.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.outMessage,
            reason: this.reason,
            taskId: this.taskId
          }
        }else if(this.approvalType === 'reject'){
          url = '/bpm/api/task-reject';
          submitData = {
            auditRecord: this.auditRecord,
            innerRemind: this.message,
            remind: this.outMessage,
            targetActivityId: this.rejectNode,
            reason: this.reason,
            taskId: this.taskId,
          }
        } else if(this.approvalType === 'refuse'){
          url = '/bpm/api/task-refuse';
          submitData = {
            auditRecord: this.auditRecord,
            innerRemind: this.message,
            remind: this.outMessage,
            reason: this.reason,
            taskId: this.taskId,
          }
        }
      }
        
      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>