import Api from '~/service/Api';
import Utils from '~/utils';
import Pts from '~/components/business/commonModel/Pts';
import commonFunctions from '~/mixin/commonFunctions.js';
import buildFn from "../event/buildCommons.js";
import BigNumber from "bignumber.js";
import commonDepend from "~/mixin/commonDepend";
import Default from "../model/default"

export default {
  mixins: [commonFunctions,commonDepend,buildFn,Default],
  methods: {

    // model.bedgrp.rec.docprbrol change, re-calculate PRB
    docprbrolChange() {
      //  re-calculate PRB

      // store the ref
      let  ref = this.model.bedgrp.prb.pts.ref;
      switch (this.model.bedgrp.rec.docprbrol) {
        case "BEN":
          Utils.copyValueFromVoData(this.model.bedgrp.prb.pts, this.model.bedgrp.ben.pts);
          break;
        case "PRB":
          this.model.bedgrp.prb.pts = new Pts().data;
          break;
      }
      this.model.bedgrp.prb.pts.ref = ref;

      // 设置prb的rol
      if(this.model.bedgrp.prb.pts.extkey!=''){
        this.model.bedgrp.prb.pts.rol = "PRB";
      }

    },
    // 获取单据编号编号
    async getBedgrpOwnRef() {

      let params = {
        businessType: "LC",
        bettyp: "LC",
        ptainr: this.model.bedgrp.apl.pts.ptainr,
        ownref: this.model.bedgrp.rec.ownref,
      };
      const loading = this.loading();
      let res = await Api.post("/Lc/ref/bed", params);
      if (res.respCode == SUCCESS) {
        loading.close();
        this.model.bedgrp.rec.ownref = res.data;
      } else {
        loading.close();
      }
    },

    nom1AmtChange(){
      this.calculateMaxamt();
      // 按照业务老师建议,收单金额默认为空,并且设为必输项,缺陷ID-284730
      // this.calculateBedMaxamt()
    },

    calculateBedMaxamt(){
      this.model.bedgrp.cbs.max.amt = this.model.ledgrp.cbs.opn1.amt;
    },

    calculateMaxamt(){
      if(this.model.ledgrp.rec.nomtop==null || this.model.ledgrp.rec.nomtop===''){
        this.model.ledgrp.rec.nomtop = 0;
      }

      if(this.model.ledgrp.rec.nomtop==null || this.model.ledgrp.rec.nomtop===''){
        this.model.ledgrp.rec.nomtop = 0;
      }
      let _maxamt =new BigNumber(this.model.ledgrp.cbs.nom1.amt).multipliedBy(new BigNumber(1).plus(new BigNumber(this.model.ledgrp.rec.nomtop).dividedBy(new BigNumber(100))) ) ;
      let _currency = this.model.ledgrp.cbs.max.cur;
      // 如果是 韩元或者日元,小数位不保留,其它保留两位小数
      // TD上,nom1:611.23,tolerance-top:2,maxamt 623.4546,letnot最后是623.46,letopn 最后是623.45,暂时以letopn为准
      if (_currency === "KRW" || _currency === "JPY") {
        _maxamt = _maxamt.toFixed(0);
      }else {
        _maxamt = _maxamt.toFixed(2);
      }
      this.model.ledgrp.cbs.max.amt = _maxamt;

      // 默认将将max的值赋值给opn1
      this.model.ledgrp.cbs.opn1.amt = this.model.ledgrp.cbs.max.amt;
    },

    nomtopChange(){
      let exp=/^\d+$/;
      if(!exp.test(this.model.ledgrp.rec.nomtop)){
        this.model.ledgrp.rec.nomtop = 0;
      }else{
        this.model.ledgrp.rec.nomtop = Number(this.model.ledgrp.rec.nomtop);
      }
      this.calculateMaxamt();
    },

    nomtonChange(){
      let exp=/^\d+$/;
      if(!exp.test(this.model.ledgrp.rec.nomton)){
        this.model.ledgrp.rec.nomton = 0;
      }else{
        this.model.ledgrp.rec.nomton = Number(this.model.ledgrp.rec.nomton);
      }
      //this.calculateMaxamt();
    },

    // bed max amt 改变,同时改变opn1的值
    maxamtChange(){
      this.model.bedgrp.cbs.opn1.amt = this.model.bedgrp.cbs.max.amt;

      this.defaultBedgrpBlkDocdis();

      this.folwupoptModify();
    },

    // 发票号改变后,直接赋值给prb的ref
    invrefChange(){
      this.model.bedgrp.prb.pts.ref  = this.model.bedgrp.rec.invref;
    },


    //获取信用证编号
    async onLetpButgetref(transName) {
      let params = {
        businessType: "LC",
        lettyp: "LC",
        transName:transName,
        ptainr: this.model.ledgrp.ben.pts.ptainr,
        ownref: this.model.ledgrp.rec.ownref,
      };
      const loading = this.loading();
      let res = await Api.post("/Lc/ref/led", params);
      if (res.respCode == SUCCESS) {
        loading.close();
        this.model.ledgrp.rec.ownref = res.data;
      } else {
        loading.close();
      }
    },

    // 如果adv,con,iss,rmb,trb的值有变动,同时更新avb的值
    async rmbbankChanged(){
      this.avbwthFlg();
      this.defaultBedgrpRmbN1000();
    },



    // 如果adv,con,iss,rmb,trb的值有变动,同时更新avb的值
    async bankChanged(){
      this.avbwthFlg();
    },


    // 如果a2b的值被清空,则清空cnfins的值
    async a2bBankChange(){
      if(this.model.ledgrp.a2b.pts.extkey==''){
        this.model.ledgrp.rec.cnfins = ''
      }
    },

    //指定银行
    async avbwthFlg() {


      switch (this.model.ledgrp.rec.avbwth) {
          // Advising bank,adv
        case "A":
          // Utils.copyValueFromVoData(this.model.ledgrp.avb.pts, this.model.ledgrp.adv.pts);
          let ptsptaList = Utils.formatPtspta(this.model.ledgrp, this.buildPtspta);

          let data = {
            ptsList:ptsptaList,
            avbwth: this.model.ledgrp.rec.avbwth,
          };
          const loading = this.loading();
          let res = await Api.post("/Lc/letopn/avbwth", data);
          loading.close();
          if (res.respCode === SUCCESS) {
            Utils.copyValueFromVoData(this.model.ledgrp.avb.pts, res.data.pts);
          }
          break;

          // Confirming Bank,con
        case "C":
          Utils.copyValueFromVoData(this.model.ledgrp.avb.pts, this.model.ledgrp.con.pts);
          break;

          // Issuing Bank,iss
        case "I":
          Utils.copyValueFromVoData(this.model.ledgrp.avb.pts, this.model.ledgrp.iss.pts);
          break;

          //Reimbursing Bank,rmb
        case "R":
          Utils.copyValueFromVoData(this.model.ledgrp.avb.pts, this.model.ledgrp.rmb.pts);
          break;

          //Specified Bank,
        case "S":
          this.model.ledgrp.avb.pts = new Pts().data;
          break;

          //Transferring Bank, trb
        case "T":
          Utils.copyValueFromVoData(this.model.ledgrp.avb.pts, this.model.ledgrp.trb.pts);
          break;

          //Any Bank, no role
        case "O":
          // if any bank is empty or is not modified, then default value is 'Any Bank'
          if(this.model.ledgrp.blk.avbwthtxt ===''||(this.model.ledgrp.blk.modifySet && !this.model.ledgrp.blk.modifySet.includes('avbwthtxt'))){
            this.model.ledgrp.blk.avbwthtxt = 'Any Bank';
          }
          break;

        default:
          this.model.ledgrp.avb.pts = new Pts().data;
          break;

      }

      // 如果avb被赋值的话,设置avb角色为AVB
      if(this.model.ledgrp.avb.pts.ptainr!==''){
        this.model.ledgrp.avb.pts.rol ="AVB";
      }


    },

    openAddAmount(val) {
      if (val === '' && !((new BigNumber(this.model.ledgrp.cbs.max2.amt).comparedTo(new BigNumber("0"))==0) && this.model.ledgrp.blk.addamtcov === '')) {
        this.$confirm('是否确定要删除此合同的附加金额?', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
          showClose: false
        }).then(() => {//yes的执行在这里写
          this.model.letp.addamtflg = ''

          this.model.ledgrp.cbs.max2.amt ='0.00';
          this.model.ledgrp.blk.addamtcov = '';
          this.customRemoveModify(this.model.ledgrp.blk,"addamtcov");
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {//No的功能在这里写
          this.model.letp.addamtflg = 'X'
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      }
    },


    apprulChange(v) {
      if (v !== 'OTHR') {
        this.model.ledgrp.rec.apprultxt = ''
      }
    },


    defaultBedgrpRecDoctypcod1500() {
      // default BEDGRP\REC\DOCTYPCOD order 1500
      switch(this.model.ledgrp.rec.avbby){
        case "M":
        case "A":
        case "D":
          this.model.bedgrp.rec.doctypcod = this.model.ledgrp.rec.avbby;
          break;
        case "N":
        case "P":
          if(this.model.ledgrp.rec.tenmaxday!=''&& new BigNumber(this.model.ledgrp.rec.tenmaxday).comparedTo(0)>0){
            this.model.bedgrp.rec.doctypcod = "A";
          }else{
            this.model.bedgrp.rec.doctypcod = "P";
          }
          break;
        default:
          this.model.bedgrp.rec.doctypcod = "";

      }
    },


    async avbbyChange() {

      // mixdet为disable时,清除其内容
      if(this.model.ledgrp.rec.avbby != 'M'){
        this.model.ledgrp.blk.mixdet = '';
      }

      // draft at为disable时,清除draftat内容,同时清除drawee
      if(  this.model.ledgrp.rec.avbby == 'D' ||
          this.model.ledgrp.rec.avbby == 'M' ||
          this.model.ledgrp.rec.avbby == ''){
        this.model.ledgrp.blk.dftat = '';

        // 清除drawee的内容
        this.model.ledgrp.drw.pts = new Pts().data;
      }

      // defdet 为disable时,清除其内容
      if(this.model.ledgrp.rec.avbby != 'D' &&
          this.model.ledgrp.rec.avbby != 'N'){
        this.model.ledgrp.blk.defdet = '';
      }

      // by payment时,tenor day为disable,清空tenor day
      if(this.model.ledgrp.rec.avbby == 'P'){
        this.model.ledgrp.rec.tenmaxday=0;
      }

      if( !(this.model.bedgrp.rec.modifySet != null && this.model.bedgrp.rec.modifySet.includes("doctypcod")) )
      {
        this.model.bedgrp.rec.doctypcod = this.model.ledgrp.rec.avbby;
      }

      this.defaultBedgrpRecDoctypcod1500();

    },

    // 当iss改变时,如果stacty没有哦被修改过,则默认将iss所在地区的赋值给stacty字段
    changeStacty() {
      // ledgrp.rec.stacty not modified, when change iss, change the stacty.
      if (!(this.model.ledgrp.rec.modifySet != null && this.model.ledgrp.rec.modifySet.includes("stacty"))) {
        Api.post('/Lc/adr/getloccty', this.model.ledgrp.iss.pts.ptainr).then(res => {
          if (res.respCode == SUCCESS) {
            this.model.ledgrp.rec.stacty = res.data;
          }
        })
      }
    },


    nom1curChange(){
      this.changeBlkAddamtcov();
    },


    // 当max2 amt改变时,同时拼接addamtcov的值
    changeBlkAddamtcov(){

      // if addmatcov not modified, then automatic connect it.
      if(!this.model.ledgrp.blk.modifySet
          || !(this.model.ledgrp.blk.modifySet!=null&&this.model.ledgrp.blk.modifySet.includes("addamtcov"))){

        if(new BigNumber(this.model.ledgrp.cbs.max2.amt).comparedTo(new BigNumber("0"))>0){
          this.model.ledgrp.cbs.max2.cur = this.model.ledgrp.cbs.nom1.cur;

          let _currency = this.model.ledgrp.cbs.max2.cur;
          let _opn2amt =  this.model.ledgrp.cbs.max2.amt;
          if (_currency === "KRW" || _currency === "JPY") {
            _opn2amt = new BigNumber(_opn2amt).toFixed(0);
          }else {
            _opn2amt = new BigNumber(_opn2amt).toFixed(2);
          }
          this.model.ledgrp.blk.addamtcov = _currency + " " +_opn2amt;
        }
      }
    },


    addMax2Change(){
      this.model.ledgrp.cbs.opn2.amt = this.model.ledgrp.cbs.max2.amt;
      this.changeBlkAddamtcov();

      // 单据的max2初始化
      this.model.bedgrp.cbs.max2.amt = this.model.ledgrp.cbs.opn2.amt;
    },

    prepers18Change(){
      let exp=/^\d+$/;
      if(!exp.test(this.model.ledgrp.rec.prepers18)){
        this.model.ledgrp.rec.prepers18 = 0;
      }else{
        this.model.ledgrp.rec.prepers18 = Number(this.model.ledgrp.rec.prepers18);
      }
    },


    // 跟defaultFolwupopt还有区别,默认的modify的判断逻辑与TD上不同,TD上是与原来的值是否一样,现有逻辑是判断是否有过修改
    // 所以使用一个单独的函数来更新folwupopt的值
    folwupoptModify(){
      if (this.model.bedgrp.blk.docdis!=null && this.model.bedgrp.blk.docdis.trim()!='') {
        this.model.betp.folwupopt = "S";//# Send Advice of Discrepancy
      } else {
        this.model.betp.folwupopt = "W"; // # Wait for Response
      }
    },

    shpdatChange(){
      this.defaultBedgrpBlkDocdis();
      this.folwupoptModify();
    },

    rcvdatChange(){
      this.defaultBedgrpBlkDocdis();
      this.folwupoptModify();
    },

  },
};