import Api from '~/service/Api';
import moment from 'moment';

export default {
  methods: {
    async handleSearch() {
      if(this.activeTab === 'le'){
        if ((this.model.infcon.seaownref == '' || this.model.infcon.seaownref == null) && this.model.infcon.opndatfrom == null) {
        this.$notify.error({ title: '错误', message: '开始日期必输!' });
        return;
        }
        if ((this.model.infcon.seaownref == '' || this.model.infcon.seaownref == null) && this.model.infcon.opndatto == null) {
          this.$notify.error({ title: '错误', message: '截止日期必输!' });
          return;
        }
        if (this.model.infcon.opndatfrom != null && this.model.infcon.opndatto != null) {
          if (new Date(this.model.infcon.opndatfrom).getTime() > new Date(this.model.infcon.opndatto).getTime()) {
            this.$notify.error({ title: '错误', message: '开始日期应小于或等于截止日期!' });
            return
          }
        }
      }else{
        let ownref = this.model[this.activeTab + 'con'][this.activeTab + 'ownref']
        let opndatfrom = this.model[this.activeTab + 'con'].opndatfrom
        let opndatto = this.model[this.activeTab + 'con'].opndatto
         if ((ownref == '' || ownref == null) && opndatfrom == null) {
        this.$notify.error({ title: '错误', message: '开始日期必输!' });
        return;
        }
        if ((ownref == '' || ownref == null) && opndatto == null) {
          this.$notify.error({ title: '错误', message: '截止日期必输!' });
          return;
        }
        if (opndatfrom != null && opndatto != null) {
          if (new Date(opndatfrom).getTime() > new Date(opndatto).getTime()) {
            this.$notify.error({ title: '错误', message: '开始日期应小于或等于截止日期!' });
            return
          }
        }
      }
      this.load = true;
      let queryCon = this.activeTab === 'le' ? this.model.infcon : this.model[this.activeTab + 'con']
      let params = {
        ...queryCon, 
        opndatfrom : queryCon.opndatfrom ? moment(queryCon.opndatfrom).format("YYYY-MM-DD") : '',
        opndatto : queryCon.opndatto ? moment(queryCon.opndatto).format("YYYY-MM-DD") : '',
        branch : JSON.parse(sessionStorage.getItem('currentOrg')).departmentNumber,
        pageNumber: this.pagination.pageIndex,
        pageSize:this.pagination.pageSize,
      };
      if( this.activeTab === 'bp'  ){
        params.pnttyp = 'BED'
      }
      delete params.markSet
      delete params.modifySet
     let rtnmsg = await Api.post('/Lc/letsel/list' + this.activeTab, params);
      if (rtnmsg.respCode == SUCCESS) {
        if(this.activeTab === 'le'){
          this.stmData.data = [];
          this.stmData.data = rtnmsg.data.list;
        }else{
          this['stmData' + this.toTitleCase(this.activeTab)].data = [];
          this['stmData' + this.toTitleCase(this.activeTab)].data = rtnmsg.data.list;
        }
        this.pagination.total = rtnmsg.data.total;
      } else {
        this.$notify.error({ title: '错误', message: '服务请求失败!' });
      }
      this.load = false;
    },

    toTitleCase(str){
      return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
    },
    //重置
    async handleReset() {
      if(this.activeTab === 'le'){
        this.model.infcon = {}
      }else{
        this.model[this.activeTab + 'con']  = {}
      }
    },

    // pageSize改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.handleSearch();
    },
    // 页码改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pagination.pageIndex = val;
      this.handleSearch();
    },

    // 详情
    async details(row) {
      const params = {
        ownref: row.ownref,
      };
      const res = await Api.post('/manager/trn/getTrnListByOwnref', params);
      if (res.respCode === SUCCESS) {
        if (res.data.length === 1) {
          if(this.oldRefId &&  this.$refs[this.oldRefId]){
            this.$refs[this.oldRefId].showPopper = false;
          }
          this.display(res.data[0])
        }else{
          this.trnData.data = res.data;
          this.oldRefId = 'popover_' + row.inr
          this.$refs[this.oldRefId].showPopper = true;
        }
      }
    },
    closeDisplayDialog(){
      if(this.oldRefId){
        this.$refs[this.oldRefId].showPopper = false;
      }
    },

    // 关闭详情弹框
    closeDetailsDialog(refId) {
      if(refId  &&  this.$refs[refId]){
        this.$refs[refId].showPopper = false;
      }
    },

    // 处理
    async handler(row) {
        this.handleModel = row;
        if(this.activeTab === 'bp'){
          this.trnUrl = 'Financing';
          this.inifrm = 'bptsel';
        } else if(this.activeTab === 'df'){
          this.trnUrl = 'Financing';
          this.inifrm = 'dftsel';
        } else{
          this.trnUrl = 'Lc';
          this.inifrm = 'letsel';
        }
        this.initdialog = true;
    },

    //双击表格数据
    async TableDblRow(row) {
      this.handler(row)
    },
    //单击表格数据
    TableRowClick(row) {
      if(this.activeTab === 'be' || this.activeTab === 'bt'){
        this.selectedModel = row
      }else{
      this['selectedModel' + this.toTitleCase(this.activeTab)] = row
      }
    },
    //点击页签
    async  handleClickTab(){
      if(this.activeTab === 'be' || this.activeTab === 'lt'){
        //从信用证跳转到单据或转让证页签
        if(this.selectedModelLe.inr) {
          this.load = true;
          let params = {
            ledinr: this.selectedModelLe.inr,
            pageNumber: this.pagination.pageIndex,
            pageSize: this.pagination.pageSize,
          };
          let rtnmsg = await Api.post('/Lc/letsel/list' + this.activeTab + 'ByLed', params);
          if (rtnmsg.respCode == SUCCESS) {
            this['stmData' + this.toTitleCase(this.activeTab)].data = [];
            this['stmData' + this.toTitleCase(this.activeTab)].data = rtnmsg.data.list;
            this.pagination.total = rtnmsg.data.total;
          } else {
            this.$notify.error({title: '错误', message: '服务请求失败!'});
          }
          this.load = false;
        }
      }else if(this.activeTab === 'bt') {
        //从转让证跳转到转让证单据页签
        if (this.selectedModelLt.inr) {
          this.load = true;
          let params = {
            ltdinr: this.selectedModelLt.inr,
            pageNumber: this.pagination.pageIndex,
            pageSize: this.pagination.pageSize,
          };
          let rtnmsg = await Api.post('/Lc/letsel/listbtByLtd', params);
          if (rtnmsg.respCode == SUCCESS) {
            this.stmDataBt.data = [];
            this.stmDataBt.data = rtnmsg.data.list;
            this.pagination.total = rtnmsg.data.total;
          } else {
            this.$notify.error({title: '错误', message: '服务请求失败!'});
          }
          this.load = false;
        }
      }else if(this.activeTab === 'bp') {
        //从出口证单据或转让证单据跳转到出口融资页签
        if (this.selectedModel.inr) {
          this.load = true;
          let params = {
            pntinr: this.selectedModel.inr,
            pnttyp: this.selectedModel.pnttyp === 'LED' ? 'BED' : this.selectedModel.pnttyp === 'LTD' ? 'BTD' : '',
            pageNumber: this.pagination.pageIndex,
            pageSize: this.pagination.pageSize,
          };
          let rtnmsg = await Api.post('/Lc/letsel/listbpByBedOrBtd', params);
          if (rtnmsg.respCode == SUCCESS) {
            this.stmDataBp.data = [];
            this.stmDataBp.data = rtnmsg.data.list;
            this.pagination.total = rtnmsg.data.total;
          } else {
            this.$notify.error({title: '错误', message: '服务请求失败!'});
          }
          this.load = false;
        }
      }
    },
    changeOwnref(){
      if(this.activeTab === 'le'){
        if(this.model.infcon.seaownref){
          this.model.infcon.opndatfrom = null
        }
      }else{
        if(this.model[this.activeTab + 'con'][this.activeTab + 'ownref']){
          this.model[this.activeTab + 'con'].opndatfrom = null
        }
      }
    },
    //点击处理弹窗中按钮
    // async handleClick (btn,row) {
    //   this.routerPush({
    //     path: "/business/" + btn.code.toLowerCase(),
    //     query: {inr: row.inr,pntinr: row.pntinr,pnttyp:'BED',ledinr:row.ledinr }
    //   });
    //   this.initdialog = false;
    // },
    // 关闭处理弹框
    closeHandlerDialog() {
      this.initdialog = false;
    },

    /**
     * 打开详情页面
     * @param {string} inr
     */
    display(row) {
      if(this.oldRefId){
        this.$refs[this.oldRefId].showPopper = false;
      }
      // 历史快照
      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'
          }
        });
      }
    },
    toLetopn() {
      // 点击开立,清空从待经办进来的时候带的行参数
      localStorage.setItem('row_letopn', null)
			localStorage.setItem('review_letopn',null)
			this.routerPush({
				path: `/business/letopn`,
			});
    },
    toLetnot() {
			this.routerPush({
				path: `/business/letnot`,
			});
    },

  async toLetdrw() {
        let params = {
        branch: JSON.parse(sessionStorage.getItem('currentOrg')).departmentNumber,
        frmtyp: 'LETDRW',
      }
      const res = await Api.post('/manager/atpbch/getInifrm', params);
      if (res.respCode === SUCCESS) {
				this.routerPush({
					path: '/business/' + res.data.inifrm.toLowerCase(),
				});
      }
    },

  async  toLetrsv() {
        let params = {
        branch: JSON.parse(sessionStorage.getItem('currentOrg')).departmentNumber,
        frmtyp: 'LETRSV',
      }
      const res = await Api.post('/manager/atpbch/getInifrm', params);
      if (res.respCode === SUCCESS) {
				this.routerPush({
					path: '/business/' + res.data.inifrm.toLowerCase(),
				});
      }
    },
    
    //Info
    toInfo(row,objtyp,subobjtyp){
      this.routerPush({
        path: "/business/" +  this.activeTab.toLowerCase() + "dinf",
        query: { inr: row.inr,objtyp:objtyp,pntinr:row.pntinr,subobjtyp:subobjtyp}
      });
    },
    async handleClick (btn,row) {
      let objtyp = '';
      if (this.activeTab === 'le') {
        objtyp = 'LED';
      } else if (this.activeTab === 'be') {
        objtyp = 'BED';
      } else if (this.activeTab === 'lt') {
        objtyp = 'LTD';
      } else if (this.activeTab === 'bt') {
        objtyp = 'BTD';
      } else if (this.activeTab === 'bp') {
        objtyp = 'BPD';
      } else if (this.activeTab === 'df') {
        objtyp = 'DFD';
      } else {
        objtyp = '';
      }
     let obj = {
        objtyp:objtyp,
        objinr:row.inr,
        pntinr:row.pntinr,
        pnttyp:this.activeTab === 'be' ? 'BED' : row.pnttyp,
        ledinr:row.ledinr,
        trnName:btn.code.toLowerCase(),
      }
     let isPush =  await this.$refs.lockAndPending.checkLockAndPending(obj)
      if(!isPush){
        return
      }
      let params = {}
      if(btn.code.toLowerCase() == 'jstopn'){
        params = {
          path: "/business/" + btn.code.toLowerCase(),
        }
      }else{
        params = {
          path: "/business/" + btn.code.toLowerCase(),
          query: {inr: row.inr,pntinr: row.pntinr,pnttyp:'BED',ledinr:row.ledinr }
        }
      }
      this.routerPush(params);
      this.initdialog = false;
    },
     //修改弹窗状态
     changeBtn(isVisible){
      this.initdialog = isVisible;
    },
  },
};