<template>
  <i-form :model="bean" label-position="left" :label-width="100" :rules="rules" ref="applyForm" >
    <Row>
      <!--<Form-item label="下一环节" prop="next">
        <Select v-model="bean.next_step" filterable style="width: 240px">
          <Option v-for="item in nextSteps" :value="item.value" :key="item.value">{{ item.name }}</Option>
        </Select>
      </Form-item>-->
      <i-col :span="24" v-if="showSelectProcessDefinition">
        <Form-item label="选择流程" prop="processDefinitionKey" style="margin-left: 20px;">
          <Select v-model="bean.processDefinitionKey" filterable style="width: 240px"
                  @on-change="changeProcessDefinition">
            <Option v-for="item in processDefinitions" :value="item.processDefinitionKey"
                    :key="item.processDefinitionKey">{{ item.processDefinitionName }}</Option>
          </Select>
        </Form-item>
      </i-col>
      <i-col :span="24">
        <Form-item label="下一环节" prop="nextTask" style="margin-left: 20px;">
          <Select v-model="bean.nextTask" filterable style="width: 240px" @on-select="nextTaskSelect">
            <Option v-for="item in nextTasks" :value="item.id" :label="item.name"
                    :key="item.name" :tag="item.category">
              <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="审批人"  style="margin-left: 20px;">
          <Select v-model="bean.nextAssignee" filterable style="width: 240px" @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="抄送人" style="margin-left: 20px;">
          <Select v-model="bean.copyId" filterable style="width: 240px">
            <Option v-for="item in copyUsers" :value="item.candidateId" :key="item.candidateId">{{ item.candidateName }}</Option>
          </Select>
        </Form-item>-->
      </i-col>
      <i-col :span="24">
        <Form-item label="申请说明" style="margin-left: 20px;margin-top: 30px;">
          <Input v-model="bean.applyReason" maxlength="100" show-word-limit style="width: 240px" type="textarea"
                 :rows="4"
                 placeholder="请输入备注信息"></Input>
        </Form-item>
      </i-col>
      <i-col :span="24" style="text-align: center;margin-top: 50px;">
        <Button type="primary" size="large" :loading="saveLoading" @click="ok('applyForm')" v-if="showSaveBtn" :disabled="submitDisabled">{{submitButtonText}}
        </Button>
        <Button size="large" @click="cancel" style="margin-left: 10px;">关闭</Button>
      </i-col>
    </Row>
  </i-form>
</template>

<script>

  import { getNextTaskAndCandidate, doApply, getDefinitionByBusCode,checkHaveUserOfCandidate } from './workflow-api'

  let $this
  export default {
    name: 'workflowApply',
    components: {},
    props: {
      busCode: String,
      callBackUrl: String,
      busData: Object,
    },
    data () {
      return {
        showSelectProcessDefinition: true,
        showModalApply: false,
        bean: {nextTask: '', nextAssignee: ''},
        //processDefinitionKey: {},//流程定义key
        processDefinitions: [],//可发起的流程集合
        nextTasks: [],//任务节点集合
        candidates: [],//审批候选人集合
        copyUsers: [],//抄送候选人集合
        nextSteps: [],//下一步
        submitButtonText: '',//提交按钮文本
        submitDisabled: false,//提交按钮状态
        saveLoading: false,
        disabled: false,
        showSaveBtn: true,
        rules: {
          processDefinitionKey: [
            { required: true, message: '流程不能为空!', trigger: 'change' },
          ],
          nextTask: [
            { 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
          this.bean.userId = this.$store.state.user.userId
          this.bean.userName = this.$store.state.user.userName
          this.bean.busCode = this.busCode
          this.bean.busData = this.busData
          //flowBean.callBackUrl = 'http://192.168.0.119:8088/khgxmanage/api/v1/buyRecord/CompanyCallBack';
          this.bean.callBackUrl = this.$config.server_url + this.callBackUrl
          doApply(this.bean).then(data => {
            if (data.data.state == true && data.data.startResult == true) {
              this.$Message.success(data.data.msg)
              this.returnCallBack(data.data);
              this.$emit('cancel','refresh')
              this.$emit('reload-data')
            } else {
              this.$Message.error({content: data.data.msg, duration: 10})

            }
            this.saveLoading = false
          }).catch(err => {
            this.saveLoading = false
            this.$Message.error('技术错误！<br>' + err)
          })
        })
      },
      cancel () {
        this.$emit('cancel')
      },
      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
        //查询一下，看看有没有符合条件的人，有就没事，没有就不能提交
        let params = {}
        params.companyId = this.busData.companyId
        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("on-success", data)
      },
      changeProcessDefinition (e) {//选择了流程定义触发
        this.bean.processDefinitionKey = e
        //初始化候选人
        this.initNextTaskAndCandidate()
        //初始化抄送候选人
        this.initCopyUsers()
      },
      //查询并初始化候选人
      initNextTaskAndCandidate() {
        if (!this.bean.processDefinitionKey) return
        let params = { processDefinitionKey: this.bean.processDefinitionKey }
        if (this.busData && this.busData.companyId){
          params.companyId = this.busData.companyId;
        }
        getNextTaskAndCandidate(params).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})
          }
        }).catch(err => {
          this.$Message.error('操作失败！')
          console.log(err)
        })
      },
      //查询并初始化抄送人
      initCopyUsers () {
        if (!this.bean.processDefinitionKey) return
        let params = { processDefinitionKey: this.bean.processDefinitionKey }
        if (this.busData && this.busData.companyId){
          params.companyId = this.busData.companyId;
        }
        getNextTaskAndCandidate(params).then(data => {
          this.copyUsers = data.data
        }).catch(err => {
          this.$Message.error('操作失败！')
          console.log(err)
        })
      },
    },
    watch: {
      busCode: {
        immediate: true,
        handler: function () {
          //根据业务编码来获取能够发起的流程定义
          if (this.busCode && this.busCode.length > 0) {
            getDefinitionByBusCode(this.busCode).then(data => {
              this.processDefinitions = data.data.result
              if (this.processDefinitions.length===1){
                this.bean.processDefinitionKey=this.processDefinitions[0].processDefinitionKey
                //初始化候选人
                this.initNextTaskAndCandidate()
                //初始化抄送候选人
                this.initCopyUsers()
                this.showSelectProcessDefinition=false
                //初始化提交按钮状态
                this.submitDisabled = true
                this.submitButtonText = '请选择'
              }else {
                this.showSelectProcessDefinition=true
              }
            }).catch(err => {
              this.$Message.error('操作失败！')
              console.log(err)
            })
          }
        }
      }
    },
    mounted () {
      $this = this
      //初始化候选人
      //this.initNextTaskAndCandidate();
      //初始化抄送候选人
      //this.initCopyUsers();
    }

  }
</script>

<style>
</style>
