import Api from "~/service/Api"

export default {
  async handleSearch() {
    if (this.activeTab === "bs") {
      if ((this.model.seaownref == '' || this.model.seaownref == null) && this.model.opndatfrom == null) {
        this.$notify.error({ title: '错误', message: '查询开始日期必输!' });
        return;
      }
      if ((this.model.seaownref == '' || this.model.seaownref == null) && this.model.opndatto == null) {
        this.$notify.error({ title: '错误', message: '查询结束日期必输!' });
        return;
      }
      if (this.model.opndatfrom != null && this.model.opndatto != null) {
        if (new Date(this.model.opndatfrom).getTime() > new Date(this.model.opndatto).getTime()) {
          this.$notify.error({ title: '错误', message: '开始日期应小于结束日期!' });
          return
        }
        if (new Date(this.model.opndatto).getTime() - new Date(this.model.opndatfrom).getTime() > 365 * 24 * 60 * 60 * 1000 * 5) {
          this.$notify.error({ title: '错误', message: '时间跨度不应超过5年!' });
          return
        }
      }
      if (this.model.hndtyps == null || this.model.hndtyps.length == 0) {
        this.model.hndtyps = ["FI", "FA", "FR"];
      }
      if (this.model.gidopentyps == null || this.model.gidopentyps.length == 0) {
        this.model.gidopentyps = ["GJBH", "GNBH"];
      }
      this.load = true;
      this.model.branch = JSON.parse(sessionStorage.getItem('currentOrg')).departmentNumber
      this.model.searol = 'BEN'
      let rtnmsg = await Api.post("/business/getsel/listId",
        {
          ...this.model,
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        });
      if (rtnmsg.respCode == SUCCESS) {
        this.load = false;
        this.tableData = rtnmsg.data.list || [];
        this.pagination = {
          pageNum: rtnmsg.data.pageNum || 1,
          pageSize: rtnmsg.data.pageSize || 10,
          total: rtnmsg.data.total
        };
      }
    } else if (this.activeTab === "sc") {
      // if ((this.model.claimownref == '' || this.model.claimownref == null) && this.model.claimdatfrom == null) {
      //   this.$notify.error({ title: '错误', message: '索赔开始日期必输!' });
      //   return;
      // }
      // if ((this.model.claimownref == '' || this.model.claimownref == null) && this.model.claimdatto == null) {
      //   this.$notify.error({ title: '错误', message: '索赔结束日期必输!' });
      //   return;
      // }
      // if (this.model.claimdatfrom != null && this.model.claimdatto != null) {
      //   if (new Date(this.model.claimdatfrom).getTime() > new Date(this.model.claimdatto).getTime()) {
      //     this.$notify.error({ title: '错误', message: '索赔开始日期应小于结束日期!' });
      //     return
      //   }
      //   if (new Date(this.model.claimdatto).getTime() - new Date(this.model.claimdatfrom).getTime() > 365 * 24 * 60 * 60 * 1000 * 5) {
      //     this.$notify.error({ title: '错误', message: '索赔时间跨度不应超过5年!' });
      //     return
      //   }
      // }
      if (this.model.hndtyps == null || this.model.hndtyps.length == 0) {
        this.model.hndtyps = ["FI", "FA", "FR"];
      }
      // if (this.model.gidopentyps == null || this.model.gidopentyps.length == 0) {
      //   this.model.gidopentyps = ["GJBH", "GNBH", "HGBH"];
      // }
      this.load = true;
      this.model.branch = JSON.parse(sessionStorage.getItem('currentOrg')).departmentNumber
      this.model.searol = 'BEN'
      let rtnmsg = await Api.post("/business/gitsel/listGcd",
        {
          ...this.model,
          pageNum: this.spPagination.pageNum,
          pageSize: this.spPagination.pageSize
        });
      if (rtnmsg.respCode == SUCCESS) {
        this.load = false;
        this.spTableData = rtnmsg.data.list || [];
        this.spPagination = {
          pageNum: rtnmsg.data.pageNum || 1,
          pageSize: rtnmsg.data.pageSize || 5,
          total: rtnmsg.data.total
        };
      }
    }
  },
  async handleReset() {
    this.model.seaownref = ""
    this.model.opndatfrom = new Date();
    this.model.opndatto = new Date();
    this.isGuarantee = "";
    this.model.nam = "";
    this.model.ptyExtkey = "";
    this.model.seapty = "";
    this.model.searef = "";
    this.model.ptyNam = "";
    this.model.searol = "";
    this.model.usrExtkey = "";
    this.model.seasta = "";
    this.model.seacur = "";
    this.model.seaamtfr = "";
    this.model.seaamtto = "";
    this.model.seagtyp = "";
    this.model.relflg = "";
    this.model.hndtyp = "";
    this.model.cxmflg = "";
    this.model.seapurpos = "";
    this.model.seahndtyp = "";
    this.model.segtyp = "";
    this.model.fromflg = "";
    this.model.fenlishi = "";
    this.model.cmtflg = "";
    this.model.fingua = "";
  },
  async claimInfo(inr, opentyp) {
    let params = { gidinr: inr, opentyp }
    let rtnmsg = await Api.post("/business/getsel/listCd", params);
    if (rtnmsg.respCode == SUCCESS) {
      const data = rtnmsg.data.list || [];
      const pagination = {
        pageNum: rtnmsg.data.pageNum || 1,
        pageSize: rtnmsg.data.pageSize || 10,
        total: rtnmsg.data.total
      };
      return {
        data,
        pagination
      }
    }
  },
  formSubmit() {
    this.handleSearch();
  },
  	// pageSize改变
		handleSizeChange(val) {
			this.pagination.pageNum = 1;
			this.pagination.pageSize = val;
			this.formSubmit();
		},
  async currentChange(num) {
    this.pagination.pageNum = num;
    this.formSubmit();
  },
  	// pageSize改变
		sphandleSizeChange(val) {
			this.spPagination.pageNum = 1;
			this.spPagination.pageSize = val;
			this.formSubmit();
		},
  async spcurrentChange(num) {
    this.spPagination.pageNum = num;
    this.formSubmit();
  },
  columnSetting(cols) {
    this.showDig = false;
    this.digColumns = [];
    this.columnGroup = [];
    this.selectAll = false;
    // 点击自定义按钮
    this.digColumns = cols;
    this.showDig = true;
    this.columnGroup = cols.filter(item => item.isShow).map(it => it.label);
    this.selectAll = cols.length === this.columnGroup.length;
  },
  async handleColumnChange() {
    this.selectAll = this.digColumns.length === this.columnGroup.length;
  },
  setAll(val) {
    this.columnGroup = val ? this.digColumns.map(item => item.label) : [];
  },
  saveColumnEvent() {
    // 保存
    const list = [];
    this.digColumns.forEach(item => {
      if (!this.columnGroup.includes(item.label)) {
        list.push({
          ...item,
          isShow: false
        });
      } else {
        list.push({ ...item, isShow: true });
      }
    });
    if (this.activeTab === "bs") {
      this.tableColumns = list;
    } else {
      this.spDefaultColumns = list;
    }

    this.showDig = false;
  },


  buttonClick(key) {
    let orInr = this.handleModel.inr || this.handleModel.inr;
    // let name = key.toUpperCase().substring(0, 1) + key.toLowerCase().substring(1);
    this.routerPush({ path: '/business/' + key, query: { orInr } });
    this.handleVisible = false
  },

  async TableDblRow(row) {
    this.getButtons(row, 'getGetselTrnCode');
  },
  async TableClickRow(row) {
    this.getButtons(row, 'getGcdTrnCode');
  },

  async handleClick() {
    if (this.activeTab == 'sc') {
      this.spload = true;
      const { data = [], pagination = {} } = await this.claimInfo(this.selectedModel.inr, this.selectedModel.opentyp);
      this.spTableData = data;
      this.spPagination = pagination;
      this.spload = false;
    }

  },


  //保函详情
  async showDisplayDialog(row) {
    let res = await Api.post("/manager/trn/queryByOwnref", {
      ownref: row.ownref
    });
    if (res.respCode == SUCCESS) {
      if (res.data.list.length === 1) {
        if (this.oldinr && this.$refs[`popover-${row.inr}`]) {
          this.$refs[`popover-${this.oldinr}`].showPopper = false
        }
        this.goDisplay(res.data.list[0])
      } else {
        if (this.oldinr && this.$refs[`popover-${row.inr}`]) {
          this.$refs[`popover-${this.oldinr}`].showPopper = false
        }
        this.oldinr = row.inr
        this.$refs[`popover-${row.inr}`].showPopper = true
        this.infoTableData = res.data.list
      }
    }
  },
  handleCloseInfo(row) {
    this.$refs[`popover-${row.inr}`].showPopper = false
  },
  closeDisplayDialog () {
		if(this.oldinr && this.$refs[`popover-${row.inr}`]){
			this.$refs[`popover-${this.oldinr}`].showPopper = false
		}
	},
  goDisplay(row) {
    this.$refs[`popover-${row.objinr}`].showPopper = false
    let inidattim = row.inidattim;
    // 历史快照
    if (row.inr.length == 8 ) {
      this.routerPush({
        path: '/business/HistoryRecord',
        query: {
          businessInr: row.inr,
          businessType: 'TRN',
          type:'view'
        }
      })
    } else if (row.inr.length == 16) {
      this.routerPush({
        path: `/display/${row.inifrm.toLowerCase()}`,
        query: {
          businessInr: row.inr,
          businessType: 'TRN'
        }
      });
    }
  },
  getCodelabel(value, codenam) {
    const codeobj = this.dbCodes[codenam].find(obj => obj.value === value)
    return codeobj ? codeobj.label : value;
  },
  getButtons(row, queryCode) {
    this.handleModel = row;
    this.handleVisible = true;
    this.queryCode = queryCode;
    this.branch = JSON.parse(window.sessionStorage.currentOrg).departmentNumber;
  },
  async getdbCode(codeType, uil, codeNam) {
    let params = {
      codeType: codeType,
      uil: uil ? uil : 'EN'
    }
    let rtnmsg = await Api.post("/manager/dic/listDicInfo", params)
    if (rtnmsg.respCode === SUCCESS) {
      let curList = rtnmsg.data.map(item => ({
        value: item.codeValue,
        label: item.codeName
      }));
      this.dbCodes[codeNam] = curList
    }
  },
  async onChoose(code, row) {
    let apiCode = ''
    if('GJBH|GNBH|HGBH'.includes(row.opentyp)){
      apiCode = 'getGetselTrnCode'
    }else {
      apiCode = 'getGcdTrnCode'
    }
    let res = await Api.post("/business/getsel/" + apiCode, row)
    if(res.respCode == SUCCESS){
        const length = res.data.length
        let btnStr = res.data;
        for (let i = 0; i < length; i++) {
          let arr = btnStr[i].split("|");
          console.log('cod:',code,',arr:',arr[0],'arr1',arr[1])
          if(arr[0] == code.toUpperCase() && arr[1] == 'N'){
            this.handleVisible = false;
            this.$notify.error({ title: '错误', message: arr[2] });
            return 
          }
        }
    }
    let gcdinr = "";
    let gidinr = "";
    let gidtyp = "";
    let gcdtyp = "";
    if (code.startsWith("n")) {
      gidtyp = "NID";
      gcdtyp = "NCD";
    } else {
      gidtyp = "GID";
      gcdtyp = "GCD";
    }
    if (row.gidinr) {
      gidinr = row.gidinr
      gcdinr = row.inr

    } else {
      gidinr = row.inr
    }
    let rtnmsg = await Api.post("/business/lock/isAccessible", { objInr: gidinr, objType: gidtyp, trnName: code.toUpperCase() })
    if (rtnmsg.respCode != SUCCESS) {
      let msg = '该笔保函数据已被锁定!'
      if (rtnmsg.data && rtnmsg.data.usrId) {
        msg = this.convertLockMsg(rtnmsg,msg)
      }
      this.handleVisible = false;
      this.$notify.error({ title: '错误', message: msg });
      return
    }
    if (gcdinr) {
      rtnmsg = await Api.post("/business/lock/isAccessible", { objInr: gcdinr, objType: gcdtyp, trnName: code.toUpperCase() })
      if (rtnmsg.respCode != SUCCESS) {
        let msg = '该笔保函索赔数据已被锁定!'
        if (rtnmsg.data && rtnmsg.data.usrId) {
          msg = this.convertLockMsg(rtnmsg,msg)
        }
        this.handleVisible = false;
        return
      }
    }
    let sptData = []
    if (gidinr) {
      let rtnmsg = await Api.post("/business/lock/checkPending", { objinr: gidinr, objtyp: gidtyp, transName: code.toUpperCase() })
      if (rtnmsg.data) {
        if (rtnmsg.data.penSptList && rtnmsg.data.penSptList.length) {
          //依次提示
          sptData = [...sptData, ...rtnmsg.data.penSptList]
        }
        if (rtnmsg.data.ameSptList && rtnmsg.data.ameSptList.length) {
          sptData = [...sptData, ...rtnmsg.data.ameSptList]
        }
        if (rtnmsg.data.canSptList && rtnmsg.data.canSptList.length) {
          sptData = [...sptData, ...rtnmsg.data.canSptList]
        }
      }
    }
    if (gcdinr) {
      let rtnmsg = await Api.post("/business/lock/checkPending", { objinr: gcdinr, objtyp: gcdtyp, transName: code.toUpperCase() })
      if (rtnmsg.data) {
        if (rtnmsg.data.penSptList && rtnmsg.data.penSptList.length) {
          //依次提示
          sptData = [...sptData, ...rtnmsg.data.penSptList]
        }
        if (rtnmsg.data.ameSptList && rtnmsg.data.ameSptList.length) {
          sptData = [...sptData, ...rtnmsg.data.ameSptList]
        }
        if (rtnmsg.data.canSptList && rtnmsg.data.canSptList.length) {
          sptData = [...sptData, ...rtnmsg.data.canSptList]
        }
      }
    }
    //去重
    let tempObj = {}
    sptData = sptData.filter(spt => {
      if (tempObj[spt.inr]) {
        return false
      } else {
        tempObj[spt.inr] = 'X'
        return true
      }
    })
    if (sptData.length) {
      this.dealSptData = sptData
      this.sptVisible = true
      this.handleVisible = false
      //传递一个临时跳转函数
      this.$goRoute = () => {
        this.sptVisible = false
        this.routerPush({
          path: "/business/" + code,
          query: { inr: row.inr, gidinr: row.gidinr }
        });
        this.$goRoute = null;

      }
      return
    }
    //跳转交易
    this.routerPush({ path: "/business/" + code, query: { inr: row.inr, gidinr: row.gidinr } })
    this.handleVisible = false;

  },
  toDetail(row) {
    this.routerPush({
      path: "/business/gidinf",
      query: { inr: row.inr, opentyp: row.opentyp, hndtyp:row.hndtyp,inifrm:''}
    })

  },
  toDetailOth(row) {
    if (row.opentyp == "GCBH") {
      this.routerPush({
        path: "/business/gcdinf",
        query: { row: row }
      });
    } else {
      this.routerPush({
        path: "/business/ncdinf",
        query: { row: row }
      });
    }
  },

  toOpn(code) {
    this.routerPush(`/business/` + code);
  },
  TableRowClick(row) {
    this.selectedModel = row
  },
}