<template>
  <Modal v-model="showMe" :mask-closable="false" :closable="true" :title="'审批'"
          :width="800" v-draggable="options" @on-cancel="cancel">
    <i-form label-position="right" :label-width="100" ref="workflowApprovalForm" style="height: 520px;"
            :model="bean" :rules="rules" inline>
      <Row>
        <i-col :span="24">
          <Form-item label="审批结果：" prop="verify_result" class="ivu-form-item-search">
            <Select v-model="bean.verify_result" style="width:200px" placeholder="审批结果" :disabled="disabled" @on-change="changeVerifyResult">
              <Option :value="'true'" :key="1">同意</Option>
              <Option :value="'false'" :key="0">不同意</Option>
              <Option :value="'back'" :key="2">退回</Option>
            </Select>
          </Form-item>
        </i-col>
        <i-col :span="24" v-if="bean.verify_result == 'back'">
          <Form-item label="退回到：" prop="back_target" class="ivu-form-item-search">
            <Select v-model="bean.back_target" style="width:200px" placeholder="选择退回节点" :disabled="disabled" @on-select="changeBackTarget">
              <Option v-for="item in backSteps" :value="item.taskKey" :label="item.taskName"
                      :key="item.taskId" :tag="item.taskId"  >{{ item.taskName }}</Option>
            </Select>
          </Form-item>
        </i-col>
        <i-col :span="24" v-if="bean.verify_result == 'true' && showSelectNextTask">
          <Form-item label="下一环节：" prop="nextTask" class="ivu-form-item-search" >
            <Select v-model="bean.nextTask" style="width:200px" placeholder="下一环节" :disabled="disabled" @on-select="nextTaskSelect">
              <Option v-for="item in nextTasks" :value="item.id" :label="item.name"
                      :key="item.name" :tag="item.category">{{ item.name }}</Option>
            </Select>
          </Form-item>
        </i-col>
        <i-col :span="24" v-show="showSelectNextAssignee">
          <Form-item label="下一步处理人："  class="ivu-form-item-search">
            <Select v-model="bean.nextAssignee" style="width:200px" placeholder="下一步处理人" :disabled="disabled" @on-select="nextAssigneeSelect">
              <Option v-for="item in candidates"  :value="item.id" :label="item.name"
                      :key="item.id" :tag="item.level">
                <span>{{ item.name }}</span>
                <!--<span style="float:right;color:#ccc">{{ item.candidateName }}</span>-->
              </Option>
            </Select>
          </Form-item>
        </i-col>
        <!--<i-col :span="24">
          <Form-item label="抄送人：" class="ivu-form-item-search">
            <Select v-model="bean.copy_for" style="width:200px" placeholder="抄送人" :disabled="disabled">
              <Option v-for="item in users" :value="item.id" :key="item.id">{{ item.userName }}</Option>
            </Select>
          </Form-item>
        </i-col>-->
        <i-col :span="24">
          <Form-item label="审批意见：" class="ivu-form-item-search">
            <Input v-model="bean.verify_remark" type="textarea" :autosize="{minRows: 10,maxRows: 10}" style="width:600px" :disabled="disabled"></Input>
         
          </Form-item>
        </i-col>
      </Row>
      <i-col :span="24" style="text-align: center">
        <Button type="primary" size="large" :loading="saveLoading" @click="ok('workflowApprovalForm')" v-if="showSaveBtn" :disabled="submitDisabled">{{submitButtonText}}</Button>
      </i-col>
    </i-form>
    <template #footer>
    <div>
      <Button size="large" @click="cancel">关闭</Button>
    </div>
    </template>
  </Modal>
</template>

<script>
  import {doApproval, closeWorkflow, getNextTaskAndCandidate, getBackSteps, getNowCandidate,checkHaveUserOfCandidate} from './workflow-api'
  let $this;
  export default {
    name: "workflowApproval",
   
    props: {
      show: Boolean,
      taskId: String,
    },
    data() {
      return {
        showMe: false,
        showSelectNextTask: false,
        showSelectNextAssignee: true,
        candidates: [],
        users: [],
        nextTasks: [],
        backSteps: [],
        bean: {},
        initBean: {verify_result: 'true', verify_remark: '', nextAssignee:''},
        flag: '',
        submitButtonText: '',//提交按钮文本
        submitDisabled: false,//提交按钮状态
        saveLoading: false,
        modalTitle: '',
        disabled: false,
        showSaveBtn: true,
        rules: {
          verify_result: [
            {required: true, message: '审批结果不能为空!', trigger: 'change'},
          ],
          /*back_target: [
            {required: true, message: '退回节点不能为空!', trigger: 'change'},
          ],*/
          nextAssignee: [
            { required: true, message: '下一步处理人不能为空!', trigger: 'change' },
          ],
        },
        options: {
          trigger: '.ivu-modal-header',
          body: '.ivu-modal',
          recover: true
        }
      }
    }, methods: {
      ok(name) {
        this.$refs[name].validate((valid) => {
          if (!valid) {
            return;
          }//表单校验失败则返回
          this.saveLoading = true;
          //if (this.flag == 'approval') {
            this.bean.taskId = this.taskId;
            let parmas = this.bean;
            //执行提交操作
            doApproval(parmas).then(data => {
              if (data.state == true && data.completeResult == true) {
                this.$Message.success(data.msg);
                this.saveLoading = false;
                this.returnCallBack(data);
              }else {
                this.$Message.error({content: data.msg, duration: 10});
                this.saveLoading = false;
              }
              this.saveLoading = false;
              localStorage.editorCache = '';//提交完了就清空编辑器的缓存
            }).catch(err => {
              this.$Message.error('技术错误！<br>'+err);
              this.saveLoading = false;
              console.log(err);
            })
          //}
        })

      },
      cancel() {
        this.showMe = false
        this.$emit('update:show', false)
      },
      nextTaskSelect (e){
        this.bean.nextTask = e.value
        for(let task of this.nextTasks){
          if (e.value === task.id){
            this.candidates = task.candidates
            this.nextAssigneeSelect({value: this.candidates[0].id})
          }
        }
      },
      nextAssigneeSelect (e){
        this.bean.nextAssignee = e.value
        //如果是退回到发起人那里,就不需要长符合条件的人了
        if (e.value == 'fqr'){
          this.submitDisabled = false
          this.submitButtonText = "提交审批"
          return
        }
        //查询一下，看看有没有符合条件的人，有就没事，没有就不能提交
        let params = {}
        params.taskId = this.taskId
        params.candidateId = e.value
        checkHaveUserOfCandidate(params).then(data => {
          let flag = data.data.result
          if (flag === true){//如果是true,意味着有人,如果是false,意味着没人
            this.submitDisabled = false
            this.submitButtonText = "提交审批"
          }else {
            this.submitDisabled = true
            this.submitButtonText = "无符合人员"
          }
        }).catch(err => {
          this.$Message.error('操作失败！')
          console.log(err)
        })
      },
      returnCallBack (data){
        //this.$emit('cancel','refresh');
        this.cancel()
        this.$emit('reload-data');
        this.$emit("on-success", data)
        this.$emit("cancel", data)
      },
      changeVerifyResult (e){
        this.bean.verify_result = e
        this.showSelectNextAssignee = false
        //初始化候选人
        if (e === 'true'){
          this.initNextTaskAndCandidate()
        }else if (e === 'back'){
          this.initBackSteps()
        }
      },
      changeBackTarget(e){
        this.bean.back_target = e.value
        //初始化候选人
        this.initNowCandidate(e.tag)

      },
      //获得当前选择节点的候选人
      initNowCandidate(targetTaskId){
        if (!targetTaskId)return;
        getNowCandidate(targetTaskId).then( data => {
          this.candidates = data.data
          this.nextAssigneeSelect({value: this.candidates[0].id})
        }).catch(err =>{
          this.$Message.error( "操作失败！");
          console.log(err);
        })
      },
      //获得当前节点的下一个节点的候选人
      initNextTaskAndCandidate(){
        if (!this.taskId)return;
        getNextTaskAndCandidate({processDefinitionKey: null, taskId: this.taskId, verifyResult: this.bean.verify_result}).then( data => {
          this.nextTasks = data.data
          //如果下一环节集合不是空的,默认选择第一个
          if (this.nextTasks && this.nextTasks.length>0){
            this.nextTaskSelect({name: this.nextTasks[0].name, value: this.nextTasks[0].id})
            this.showSelectNextTask = true
            this.showSelectNextAssignee = true
          }else {
            this.showSelectNextTask = false
            this.showSelectNextAssignee = false
          }
        }).catch(err =>{
          this.$Message.error( "操作失败！");
          console.log(err);
        })
      },
      initBackSteps(){
        if (!this.taskId)return;
        getBackSteps(this.taskId).then( data => {
          this.backSteps = data.data
          if (this.backSteps && this.backSteps.length>0){
            this.changeBackTarget({name: this.backSteps[0].taskName,
              value: this.backSteps[0].taskKey,
              tag: this.backSteps[0].taskId})
            this.showSelectNextAssignee = true
          }else {
            this.showSelectNextAssignee = false
          }
          /*this.bean.back_target = this.backSteps[0].taskId
          this.initNowCandidate(this.bean.back_target)*/
        }).catch(err =>{
          this.$Message.error( "操作失败！");
          console.log(err);
        })
      },
    },
    mounted() {
      $this = this;
      this.bean = this.initBean;
      //初始化选择结果
      this.changeVerifyResult('true')
      //初始化候选人
      //this.initNextTaskAndCandidate();
      //初始化退回节点集合
      //this.initBackSteps();
      //初始化提交按钮状态
      this.submitDisabled = false
      this.submitButtonText = '提交审批'
    },
    watch: {
      show: {
        immediate: true,
        handler: function () {
          this.showMe = this.show
        }
      },
    }

  }
</script>

<style scoped>
  .ivu-form-item-search {
    margin-bottom: 21px;
  }
</style>
