<template>
<view class="apply-credit">
  <view class="title">{{$t('approval.formInfo')}}</view>
  <view class="form-wrap">
    <u-form labelPosition="left" :model="form" :rules="rules" ref="form1" labelWidth='90'>
      <!-- 流程编码 -->
      <u-form-item :label="$t('approval.approvalCode')" borderBottom prop="wfCode">
        <u-input readonly v-model="form.wfCode" border="none" />
      </u-form-item>
      <!-- 流程标题 -->
      <u-form-item :label="$t('approval.approvalTitle')" borderBottom prop="flowTitle">
        <u-input :readonly="isCheckView" v-model="form.flowTitle" border="none" :placeholder="$t('base.common.placeholderI')+$t('approval.approvalTitle')" />
      </u-form-item>
      <!-- 紧急程度 -->
      <u-form-item :label="$t('approval.urgency')" borderBottom prop="flowUrgent" @click="showPopup('flowUrgent')">
        <u-input readonly @change="resetFlow('flowUrgent')" v-model="textForm.flowUrgent" border="none" :placeholder="$t('base.common.placeholderS')+$t('approval.urgency')" />
      </u-form-item>
      <!-- 申请人员 -->
      <u-form-item :label="$t('approval.applicant')" borderBottom prop="applicant" @click="showPopup('applicant')">
        <u-input readonly @change="resetFlow('applicant')" v-model="textForm.applicant" border="none" :placeholder="$t('base.common.placeholderS')+$t('approval.applicant')" />
      </u-form-item>
      <!-- 授信客户 -->
      <u-form-item :label="$t('approval.creditCustom')" borderBottom prop="companyId" @click="showPopup('companyId')">
        <u-input readonly @change="resetFlow('companyId')" v-model="textForm.companyId" border="none" :placeholder="$t('base.common.placeholderS')+$t('approval.creditCustom')" />
      </u-form-item>
      <!-- 授信金额 -->
      <u-form-item :label="$t('approval.creditMoney')" borderBottom prop="amount">
        <u-input :readonly="isCheckView" type="number" @change="resetFlow('amount')" v-model="form.amount" border="none" :placeholder="$t('base.common.placeholderI')+$t('approval.creditMoney')" />
      </u-form-item>
      <!-- 授信类型 -->
      <u-form-item :label="$t('approval.creditType')" borderBottom prop="type" @click="showPopup('type')">
        <u-input readonly @change="resetFlow('type')" v-model="textForm.type" border="none" :placeholder="$t('base.common.placeholderS')+$t('approval.creditType')" />
      </u-form-item>
      <!-- 授信日期 -->
      <u-form-item :label="$t('approval.creditDate')" borderBottom prop="setDate" @click="isCheckView?'':showSetDateCalendar = true">
        <u-input readonly @change="resetFlow('setDate')" v-model="form.setDate" border="none" :placeholder="$t('base.common.placeholderS')+$t('approval.creditDate')" />
      </u-form-item>
      <!-- 授信天数 -->
      <u-form-item :label="$t('approval.creditDays')" borderBottom prop="amountDay">
        <u-input type="number" @change="resetFlow('amountDay')" @blur="changeCancelDate" v-model="form.amountDay" border="none" :placeholder="$t('base.common.placeholderI')+$t('approval.creditDays')" />
      </u-form-item>
      <!-- 到期日期 -->
      <u-form-item :label="$t('approval.finishDate')" borderBottom prop="cancelDate" @click="isCheckView?'':showCancelDateCalendar = true">
        <u-input readonly @change="resetFlow('cancelDate')" v-model="form.cancelDate" border="none" :placeholder="$t('base.common.placeholderS')+$t('approval.finishDate')" />
      </u-form-item>
      <!-- 备注 -->
      <u-form-item :label="$t('approval.remark')" borderBottom prop="remark">
        <u-input :readonly="isCheckView" type="textarea" v-model="form.remark" border="none" :placeholder="$t('approval.remark')" />
      </u-form-item>
    </u-form>
  </view>
  <view class="title">{{$t('approval.approvalInfo')}}</view>
  <view class="flow-wrap">
    <u-steps direction="column" :current="currentIndex">
      <u-steps-item
      v-for="item,index in flowList"
      :key="index"
      :title="item.title" 
      :desc="item.content+(item.handleOpinion?` (${item.handleOpinion})`:'')">
        <span slot="time" class="time">{{item.time}}</span>
      </u-steps-item>
    </u-steps>
  </view>
  <view class="btn-wrap" v-if="!isCheckView">
    <button type="primary" color='#4680F9' @click="submit('form1')">{{$t('base.common.submit')}}</button>
  </view>
  
  <!-- 紧急程度 -->
  <PopupSelect ref="flowUrgent" kind="flowUrgent" :option="flowUrgentOptions" @onConfirm="onConfirm"/>
  <!-- 申请人员 -->
  <PopupSelect ref="applicant" kind="applicant" :option="applicantOptions" @onConfirm="onConfirm"/>
  <!-- 授信客户 -->
  <PopupSelect ref="companyId" kind="companyId" :option="clientOptions" @onConfirm="onConfirm"/>
  <!-- 授信类型 -->
  <PopupSelect ref="type" kind="client" :option="typeOptions" @onConfirm="onConfirm"/>
  <!-- 授信日期 -->
    <u-calendar 
    color="#4680F9" 
    round='25' 
    :show="showSetDateCalendar" 
    @confirm="onSetDateConfirm" 
    @close="showSetDateCalendar=false">
    </u-calendar>
    <!-- 到期日期 -->
    <u-calendar 
    color="#4680F9" 
    round='25' 
    :show="showCancelDateCalendar" 
    @confirm="onCancelDateConfirm" 
    @close="showCancelDateCalendar=false">
    </u-calendar>
    <u-toast ref="loadingToast" />
</view>
 
</template>

<script>
import PopupSelect from '../../components/popup-select/index'
import {
  getUserList,
  getApprovalFlow,
  BillNumber,
  createApproval,
  getApprovalInfo,
  getApprovalFlowInfo
} from "../../api/approval"
import {
  getClientList
} from "../../api/receivable"
import dayjs from 'dayjs'
export default {
  components:{
    PopupSelect,
  },
  data() {
    return {
      id:'',
      isCheckView:false,
      enCode:'applyCredit',
      userInfo: {},
      showSetDateCalendar:false,
      showCancelDateCalendar:false,
      flow:{},
      flowList:[],
      currentIndex:0,
      form:{
        flowId: '',
        // id: '',
        wfCode: '',
        flowTitle: '',
        flowUrgent: 1, //紧急程度
        applicant:'', //申请人
        remark: '',
        amount:undefined, //授信金额
        amountDay:1, //授信天数
        companyId:undefined, //授信单位
        cancelDate:dayjs().add(1,'day').format('YYYY-MM-DD'), //结束日期
        setDate:dayjs().format('YYYY-MM-DD'), //登记日期
        type:'101',
      },
      formcondition:{
        flowTitle: false,
        flowUrgent: false, //紧急程度
        applicant:false, //申请人
        amount:false, //授信金额
        amountDay:false, //授信天数
        companyId:false, //授信单位
        cancelDate:false, //结束日期
        setDate:false, //登记日期
        type:false,
      },
      textForm:{
        flowUrgent: this.$t('approval.ordinary'), //紧急程度
        applicant:'', //申请人
        companyId:'', //授信单位
        type:this.$t('approval.temporaryCredit'),
      },
      rules:{
        flowTitle: [
          { required: true, message:this.$t('base.common.placeholderI')+this.$t('approval.approvalTitle') },
        ],
        flowUrgent: [
          { required: true, message: this.$t('base.common.placeholderS')+this.$t('approval.urgency') },
        ],
        companyId:[{ required: true, message: this.$t('base.common.placeholderS')+this.$t('approval.creditCustom') }],
        setDate:[{ required: true, message: this.$t('base.common.placeholderS')+this.$t('approval.creditDate') }],
        amount:[{ required: true, message: this.$t('base.common.placeholderI')+this.$t('approval.creditMoney') }],
        type:[{ required: true, message: this.$t('base.common.placeholderS')+this.$t('approval.creditType') }],
        applicant:[{ required: true, message: this.$t('base.common.placeholderS')+this.$t('approval.applicant') }]
      },

      flowUrgentOptions:[
        {text:this.$t('approval.ordinary'),value:1},
        {text:this.$t('approval.urgent'),value:2},
        {text:this.$t('approval.important'),value:3},
      ],
      typeOptions:[
        {text:this.$t('approval.temporaryCredit'),value:'1'},
        {text:this.$t('approval.fixedCredit'),value:'2'},
      ],
      applicantOptions:[{text:this.$t('order.noData'),value:null}], //申请人员选项
      clientOptions:[{text:this.$t('order.noData'),value:null}], //授信客户选项
    };
  },
  onLoad(options) {
    this.form.flowId = options.flowId
    if(options.id){
      this.id = options.id
      this.isCheckView = true
      this.getOptions()
    }else{
      this.getOptions()
      this.getApprovalFlow() 
      this.userInfo = uni.getStorageSync("userInfo");
      this.form.applicant = this.userInfo.userId
      this.textForm.applicant = this.userInfo.userName
      this.textForm.applicant = this.userInfo.name
    }
   
  },
  methods:{
    //获取详情
    async getApprovalFlowInfo(){
      let encode = this.enCode[0].toUpperCase()+this.enCode.slice(1)
      getApprovalInfo(encode,this.id).then(res=>{
        if(res.data.code == 200){
          this.form = res.data.data
          let data = res.data.data
            this.textForm.flowUrgent=data.flowUrgent==1?'普通':(data.flowUrgent == 2?'紧急':'重要') //紧急程度
            this.applicantOptions.forEach(item=>{
              if(item.value == data.applicant){
                this.textForm.applicant = item.text
              }
            })
            this.clientOptions.forEach(item=>{
              if(item.value == data.companyId){
                this.textForm.companyId = item.text
              }
            })
            this.textForm.type=data.type=="101"?this.$t('approval.temporaryCredit'):this.$t('approval.fixedCredit')
        }
      })
      getApprovalFlowInfo(this.id).then(res=>{
         if(res.data.code == 200){
          let flow = JSON.parse(res.data.data.flowTaskInfo.flowTemplateJson)
          this.flow = flow
          this.forFlowObj(flow)
          this.flowList.forEach((item,index)=>{
            res.data.data.flowTaskOperatorRecordList.forEach(i=>{
              if(i.nodeCode == item.nodeId){
                item.time = i.handleTime || ''
                item.handleOpinion = i.handleOpinion || ''
                this.currentIndex = index
              }
            })
            res.data.data.flowTaskNodeList.forEach(i=>{
              if(i.nodeCode == item.nodeId){
                item.content = i.userName || item.content
              }
            })
          })
        }
      })
    },
    //提交审批
    submit(ref){
      let _this = this
      this.$refs[ref].validate().then(() => {
        let key = this.enCode[0].toUpperCase()+this.enCode.slice(1)
        this.$refs.loadingToast.show({
          type:"loading",
          message: "正在加载",
          duration:'100000',
				})
        createApproval(key,this.form).then(res=>{
          if(res.data.code == 200){
            this.$refs.loadingToast.hide()
            uni.showModal({
              title: _this.$t('settings.tips'),
              content: _this.$t('approval.creditApprovalSuccess'),
              showCancel: false,
              success: ({ confirm, cancel }) => {
                if(confirm){
                  uni.navigateBack({ delta: 1 })
                }
              }
            })
          }else{
            this.$refs.loadingToast.hide()
            uni.showModal({
              title: _this.$t('settings.tips'),
              content: res.data.msg || _this.$t('approval.creditApprovalFail'),
              showCancel: false,
            })
          }
        })
      })
    },
    //获取审批流程
    getApprovalFlow(){
      getApprovalFlow(this.form.flowId).then(res=>{
        if(res.data.code == 200){
          this.form.flowTitle=this.userInfo.username+'的'+res.data.data.fullName
          let flow = JSON.parse(res.data.data.flowTemplateJson)
          this.flow = flow
          console.log(this.flow);
          this.forFlowObj(flow)
        }
      })
    },
    //获取选项
    async getOptions(){
      //获取用户
      await getUserList().then(res=>{
        if(res.data.code == 0){
          this.applicantOptions = this.formatOption(res.data.data)
        }
      })
      //获取授信客户
      await getClientList({type:'102'}).then(res=>{
        if(res.data.code == 0){
          this.clientOptions = this.formatOption(res.data.data)
        }
        console.log(this.clientOptions,'------------');
      })
      if(this.isCheckView){
        this.getApprovalFlowInfo()
      }else{
        //流程编码
        BillNumber(this.enCode,dayjs().format('YYYY-MM-DD')).then(res => {
          if(res.data.code==0){
            this.form.wfCode = res.data.msg
          }
        })
      }
      
    },
    //确定选择
    onConfirm(value,kind){
      if(value.value){
        this.form[kind]=value.value
        this.textForm[kind]=value.text
      }else{
        this.form[kind]=''
        this.textForm[kind]=''
      }
    },
    //根据条件重新设置流程
    resetFlow(value){
      if(this.isCheckView){
        return
      }
      if(this.formcondition[value]){
        this.flowList=[]
        if(this.form[value] !=undefined){
          this.forFlowObj(this.flow)
        }
      }
    },
    //选择授信日期
    onSetDateConfirm(date){
      this.form.setDate = dayjs(date).format('YYYY-MM-DD');
      this.showSetDateCalendar = false;
    },
    //选择到期日期
    onCancelDateConfirm(date){
      this.form.cancelDate = dayjs(date).format('YYYY-MM-DD');
      this.showCancelDateCalendar = false;
    },
    //选项格式
    formatOption(data){
      let arr=[]
      data.forEach(item=>{
        arr.push(
          {
            text:item.name || item.label,
            value:item.value || item.id || item.userId
          }
        )
      })
      if(arr.length){
        arr.unshift({text:this.$t('order.notSelected'),value:null})
      }else{
        arr.unshift({text:this.$t('order.noData'),value:null})
      }
      return arr
    },
    changeCancelDate(){
      this.form.cancelDate = dayjs(this.form.setDate).add(this.form.amountDay,'day').format('YYYY-MM-DD')
    },
    //循环对象
    forFlowObj(flow){
      this.flowList.push(
        {
          title:flow.properties.title,
          content:flow.content,
          nodeId:flow.nodeId,
          time:'',
          handleOpinion:"",
        }
      )
      if(flow.conditionNodes && flow.conditionNodes.length){
        flow.conditionNodes.forEach(item=>{
          let math = item.properties.conditions
          if(this.eval(math)){
            this.flowList.push(
              {
                title:item.properties.title,
                content:item.content,
                nodeId:item.nodeId,
                time:'',
                handleOpinion:"",
              }
            )
            this.forFlowObj(item.childNode)
          }
        })
      }
      if(flow.childNode){
        this.forFlowObj(flow.childNode)
      }
    },
    //显示选择
    showPopup(refs){
      if(this.isCheckView){
        return
      }
      this.$refs[refs].showPicker=true
    },
    //计算方法
    eval(conditions){
      let boo=false
      let booList = []
      console.log(conditions);
      conditions.forEach((item,index)=>{
        switch (item.symbol) {
          case '>=':
           booList.push( this.form[item.field] >= Number(item.filedValue))
           if(index != conditions.length-1){
             booList.push(item.logic)
           }
          break;
          case '>':
           booList.push(this.form[item.field] > Number(item.filedValue))
           if(index != conditions.length-1){
             booList.push(item.logic)
           }
          break;
          case '==':
           booList.push(this.form[item.field] == Number(item.filedValue))
           if(index != conditions.length-1){
             booList.push(item.logic)
           }
          break;
          case '<=':
           booList.push(this.form[item.field] <= Number(item.filedValue))
           if(index != conditions.length-1){
             booList.push(item.logic)
           }
          break;
          case '<':
           booList.push(this.form[item.field] < Number(item.filedValue))
           if(index != conditions.length-1){
             booList.push(item.logic)
           }
          break;
          case '<>':
           booList.push(this.form[item.field] != Number(item.filedValue))
           if(index != conditions.length-1){
             booList.push(item.logic)
           }
          break;
        }
        this.formcondition[item.field] = true
      })
      let booList2=[]
      if(booList.length>1){
        booList.forEach((item,index)=>{
          if(index%2 != 0){
            switch (item) {
              case "&&":
                booList2.push(booList[index-1] && booList[index+1])
              break;
            }
          }else{
            if(booList[index+1] !="&&" && booList[index-1] !="&&"){
              booList2.push(item)
            }
          }
        })
      }else{
        boo=booList[0]
      }
      if(booList2.length>1){
        booList2.forEach(item=>{
          if(item){
            boo = true
          }
        })
      }else if(booList2.length==1){
        boo = booList2[0]
      }
      return boo
    },
  }
};
</script>

<style lang="scss" scoped>
@import '../../common/css/apply.scss';
</style>