<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('spare.applyDate')" borderBottom prop="setDate" @click="showSetDateCalendar = true">
          <u-input readonly v-model="form.setDate" border="none" :placeholder="$t('base.common.placeholderS')+$t('spare.applyDate')" />
        </u-form-item>
        <!-- 订单编号 -->
        <u-form-item :label="$t('spare.orderCode')" borderBottom prop="code">
          <u-input readonly v-model="form.code" border="none" :placeholder="$t('base.common.placeholderS')+$t('spare.orderCode')" />
        </u-form-item>
        <!-- 供应商 -->
        <u-form-item :label="$t('order.purveyId')" borderBottom prop="purveyId" @click="showPopup('purveyId')">
          <u-input readonly v-model="textForm.purveyId" border="none" :placeholder="$t('base.common.placeholderS')+$t('order.purveyId')" />
        </u-form-item>
        <!-- 申请人员 -->
        <u-form-item :label="$t('spare.buyer')" borderBottom prop="buyer" @click="showPopup('buyer')">
          <u-input readonly v-model="textForm.buyer" border="none" :placeholder="$t('base.common.placeholderS')+$t('spare.buyer')" />
        </u-form-item>
        <!-- 采购明细 -->
        <u-form-item :label="$t('spare.buyDetail')" borderBottom prop="dtoList" @click="toPage" v-if="!isCheckView">
          <u-input readonly border="none" :placeholder="$t('spare.buyDetail')" />
          <u-icon
            slot="right"
            name="arrow-right"
          ></u-icon>
        </u-form-item>
        <!-- 备注 -->
        <u-form-item label="备注" borderBottom prop="remark">
          <u-input :readonly="isCheckView" type="textarea" v-model="form.remark" border="none" placeholder="备注信息" />
        </u-form-item>
      </u-form>
    </view>
    <view class="title">{{$t('spare.buyDetail')}}</view>
     <template v-if="form.dtoList.length">
        <view class="order-card" v-for="(item, index) in form.dtoList" :key="index">
          <view class="order-info">
            <p class="info-line">
              <text class="label">{{$t('spare.spareName')}}:</text>
              <text class="info">
                <template >
                  {{`${item.materialCode}_${item.materialName}_${item.materialSpec}`}}
                </template>
              </text>
            </p>
             <p class="info-line">
              <text class="label">{{$t('spare.orderNum')}}:</text>
              <text class="info">{{item.number}}</text>
            </p>
          </view>
        </view>
      </template>
      <template v-else>
        <u-empty mode="list" :text="$t('spare.setBuyDetail')" icon="https://cdn.uviewui.com/uview/empty/list.png">
        </u-empty>
      </template>
    
    <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="purveyId" kind="purveyId" :option="purveyIdOptions" @onConfirm="onConfirm"/>
     <!-- 申请人员 -->
    <PopupSelect ref="buyer" kind="buyer" :option="buyerOptions" @onConfirm="onConfirm"/>
    <!-- 申请日期 -->
    <u-calendar 
    color="#4680F9" 
    round='25' 
    :show="showSetDateCalendar" 
    @confirm="onSetDateConfirm" 
    @close="showSetDateCalendar=false">
    </u-calendar>
    <u-toast ref="loadingToast" />
  </view>
</template>

<script>
import PopupSelect from '../../components/popup-select/index'
import dayjs from 'dayjs'
import { getLabel,getTreeList } from '../../utils/util'
import {request} from '../../utils/request'
import {
  getApprovalFlow,
  BillNumber,
  getApprovalInfo,
  createApproval,
  getApprovalFlowInfo
} from "../../api/approval"
import {
  getCode,
  getClientList,
  getUserListByType
} from "../../api/receivable"
export default {
  components:{
    PopupSelect
  },
  data(){
    return {
      id:'',
      getLabel,
      showSetDateCalendar:false,
      isCheckView:false,
      enCode:'applyOrder',
      currentIndex:0,
      flowList:[],
      flow:{},
      form:{
        flowId: '',
        id: '',
        wfCode: '',
        billNo: '',
        flowTitle: '',
        flowUrgent: 1,
        setDate:dayjs().format('YYYY-MM-DD'), //登记日期
        code:'',
        purveyId:'',
        buyer:'',
        remark:undefined, //备注
        dtoList:[],
        fileList:[],
      },
      textForm:{
        flowUrgent:this.$t('approval.ordinary'),//紧急程度
        purveyId: '', 
        buyer:'',
      },
      rules: {
        setDate:[{ required: true, message: this.$t('base.common.placeholderS')+this.$t('spare.applyDate'), trigger: "change" }],
        purveyId:[{ required: true, message: this.$t('base.common.placeholderS')+this.$t('order.purveyId'), trigger: "change" }],
        code:[{ required: true, message:this.$t('base.common.placeholderS')+this.$t('spare.orderCode'), trigger: "change" }],
        dtoList:[{
          required: true,
          message: "采购明细不能为空",
          validator:(rule,value,callback)=>{
            if(this.form.detailList.length){
              callback()
            }else{
              callback(new Error("采购明细不能为空"))
            }
          }
        }],
        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')},
        ],
      },
      formcondition:{
        flowUrgent: false, //紧急程度
      },
      flowUrgentOptions:[
        {text:this.$t('approval.ordinary'),value:1},
        {text:this.$t('approval.urgent'),value:2},
        {text:this.$t('approval.important'),value:3},
      ],
      purveyIdOptions:[
        {text:this.$t('order.noData'),value:null}
      ],
      buyerOptions:[
        {text:this.$t('order.noData'),value:null}
      ],
      unitList:[],
    }
  },
  onLoad(options) {
    this.form.flowId = options.flowId
    if(options.id){
      this.isCheckView = true
      this.id = options.id
      this.getOptions()
      this.getApprovalFlowInfo()
    }else{
      this.userInfo = uni.getStorageSync("userInfo");
      this.getOptions()
      this.getApprovalFlow()
    }
    
  },
  methods:{
      
    //提交审批
    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: _this.$t('base.common.loading'),
          duration:'100000',
				})
        createApproval(key,this.form).then(res=>{
          if(res.data.code == 0){
            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,
            })
          }
        })
      })
    },
    toPage(){
      uni.navigateTo({ url: `/subpages/approval/summary?encode=applyOrder` })
    },
    //获取详情
    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?this.$t('approval.ordinary'):(data.flowUrgent == 2?this.$t('approval.urgent'):this.$t('approval.important')) //紧急程度
            this.purveyIdOptions.forEach(item=>{
              if(item.value == data.purveyId){
                this.textForm.purveyId = item.text
              }
            })
            this.buyerOptions.forEach(item=>{
              if(item.value == data.buyer){
                this.textForm.buyer = item.text
              }
            })
            
        }
      })
      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
              }
            })
          })
        }
      })
    },
    //显示选择
    showPopup(refs){
      if(this.isCheckView){
        return
      }
      this.$refs[refs].showPicker=true
    },
    //获取选项
    getOptions(){
      //流程编码
      if(this.id){

      }else{
        BillNumber(this.enCode,dayjs().format('YYYY-MM-DD')).then(res => {
          if(res.data.code==0){
            this.form.wfCode = res.data.msg
          }
        })
        //订单编码
        getCode(dayjs().format('YYYY-MM-DD')).then(res=>{
          if(res.data.code == 0){
            this.form.code = res.data.data
          }
        })
      }
      //获取单位
      request({
        url:'/admin/dict/type/spare_unit',
        method:'get',
      })
      .then(res=>{
        if(res.data.code == 0){
          this.unitList = res.data.data
        }
      })
       //获取供应商
      getClientList( {type:'103'}).then(res=>{
        let arr=[]
        res.data.data.forEach(item=>{
          arr.push({
            text:item.name,
            value:item.id
          })
        })
        if(arr.length){
          arr.unshift({text:this.$t('order.notSelected'),value:null})
        }else{
          arr.unshift({text:this.$t('order.noData'),value:null})
        }
        this.purveyIdOptions = arr
      })
      //获取采购员
      getUserListByType('101').then(res=>{
        let arr=[]
        res.data.data.forEach(item=>{
          arr.push({
            text:item.name,
            value:item.userId
          })
        })
        if(arr.length){
          arr.unshift({text:this.$t('order.notSelected'),value:null})
        }else{
          arr.unshift({text:this.$t('order.noData'),value:null})
        }
        this.buyerOptions = arr
      })
      
    },
   
    //确定选择
    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]){
          this.forFlowObj(this.flow)
        }
      }
    },
    //获取审批流程
    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)
        }
      })
    },
    //选择申请日期
    onSetDateConfirm(date){
      this.form.setDate = dayjs(date).format('YYYY-MM-DD');
      this.showSetDateCalendar = false;
    },
    //循环对象
    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)
      }
    },
    //计算方法
    eval(conditions){
      let boo=false
      let booList = []
      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';
@import '../../common/css/approval.scss';
/deep/ .u-form-item__body__right__content__slot{
  display: block !important;
  // flex-direction: column !important;
  // align-items: baseline;
 }
/deep/ .input-value-border{
  border: none !important;
 }
 /deep/ .input-arrow{
  border:none !important;
 }
 /deep/ .input-value{
   line-height: 24px !important;
 }
</style>
