import Api from '~/service/Api';
import Utils from "~/utils"
import commonFunctions from '~/mixin/commonFunctions.js';
import moment from 'moment'
import {trim} from 'zrender/lib/core/util';

export default {
    mixins: [commonFunctions],
    methods: {
        imageMethod() {
        },
        async foldMethod() {
            const loading = this.loading();
            let res = await Api.post('/public/quesel/butcan', {
                inrList: this.multipleSelection
            });
            if (res.respCode == SUCCESS) {
                this.$notify({
                    title: '成功',
                    message: '归档成功',
                    type: 'success',
                });
                this.handleSearch();
            }
            loading.close();
        },
        async deleteMethod() {
            if (!this.multipleSelection ||(this.multipleSelection && this.multipleSelection.length!==1)) {
                this.$notify({
                    title: '提示',
                    message: '请选择一笔数据操作!',
                    type: 'warning',
                });
                return;
            }
          let row =this.multipleSelectionRow;
           //判断是否被锁
           let rtnmsg = await Api.post(`/${this.moduleRouter()}/lock/getSptAccessible`, { objInr: row.objinr, objType: row.objtyp, trnName: row.inifrm.toUpperCase() })
           if (rtnmsg.respCode===SUCCESS && rtnmsg.data && rtnmsg.data.usrId) {
             let msg = '该笔待办数据已被锁定!' + "锁定人为" + rtnmsg.data.usrId + ",锁定交易为[" + rtnmsg.data.trnLabel+"]"
             this.handleVisible = false;
             this.$notify.error({ title: '错误', message: msg });
             return
           }
            let curRole = JSON.parse(window.sessionStorage.curRole).name;
            if(curRole.indexOf("经办")>=0 ||curRole.indexOf("查询")>=0 || curRole.indexOf("参数")>=0) {
                let usr = this.$store.state.common.username
                let returnFlg = false
                let returnMsg = "所选记录您无权删除,请重新选择!"
                for (let i of this.multipleSelectionObj) {
                    if (i.iniusr != usr) {
                        returnFlg = true
                        returnMsg = returnMsg + "<br/>" + "" + i.ownref + " , " + i.iniusr
                    }
                }
                if (returnFlg) {
                    this.$notify.warning({title: '提示:', message: returnMsg, dangerouslyUseHTMLString: true});
                    return;
                }
            }

            this.$confirm('您确定删除该笔交易?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(async () => {
                const loading = this.loading();
                let res = await Api.post('/public/quesel/delete', {
                    inrList: this.multipleSelection
                });
                if (res.respCode == SUCCESS) {
                    this.$notify({
                        title: '成功',
                        message: '删除成功',
                        type: 'success',
                    });
                    // let arrayList=this.multipleSelectionObj.filter(item=>{
                    //     return item.inr!==row.inr;
                    // });
                    // this.handleSelectionChange(arrayList);
                    this.$refs.relTable.toggleRowSelection(row,false);
                    this.handleSearch();
                }
                loading.close();
            })
        },
        showDoc(row) {
            this.messageVisible = false;
            this.$refs.msgView.fileViewDispaly(-1, {smhinr: row.inr})
        },
        async showMsg(row) {
            let params = {}
            if (row.objtyp === 'TRN') {
                params.trninr = row.objinr;
            }
            if (row.objtyp === 'SPT') {
                params.sptinr = row.objinr;
            }
            let res = await Api.post("/public/quesel/showSmhList", params);
            if (res.respCode == SUCCESS) {
                // 一条直接展示多条展示列表
                if (res.data.smhList.length == 1) {
                    this.messageVisible = false;
                    this.$nextTick(() => {
                        this.$refs.msgView.fileViewDispaly(-1, {smhinr: res.data.smhList[0].inr})
                    })

                } else {
                    this.messageVisible = true;
                    this.messageData = res.data.smhList;
                }
            }

            // return new Promise(async (resolve) => {
            // 	let params = {
            // 		queinr: this.multipleSelection[0]
            //   };
            //   this.$refs.msgView.fileViewDispaly(-1,params)
            // })
        },

        formatJson(filterVal, jsonData) {
            return jsonData.map(v => {
                return filterVal.map(j => v[j])
            })
        },

        async reRoutingMethod() {
            if (this.multipleSelection.length != 1) {
                this.$notify({
                    title: '提示',
                    message: '请勾选一笔数据',
                    type: 'warning',
                });
                return;
            }
            let row = this.multipleSelectionRow;
            let accessUrl=`/${this.moduleRouter()}/lock/isSptAccessible`;
            let curRole = JSON.parse(window.sessionStorage.curRole).name;
            if(this.isPubBranchJinB() && "-pending-correct-".indexOf(row.status)>0){
               accessUrl=`/${this.moduleRouter()}/lock/isReroutingAccessible`;
            }
            let rtnmsg = await Api.post(accessUrl, {
              objInr: row['objinr'],
              objType: row['objtyp'],
              trnName: row['inifrm'].toUpperCase()
            })
            if (rtnmsg.respCode != SUCCESS) {
                let msg = '该笔待办数据已被锁定!'
                if (rtnmsg.data.objTyp != row['objtyp']) {
                    msg = this.convertLockMsg(rtnmsg,msg)
                }
                else if(rtnmsg.respCode == '400011'){
                    msg = "请先完成当前业务的起始交易!"
                }
                else if (rtnmsg.data && rtnmsg.data.usrId) {
                    msg = msg + "锁定人为" + rtnmsg.data.usrId + ",锁定交易为[" + rtnmsg.data.trnLabel+"]"
                }
                this.$notify.error({
                    title: '错误',
                    message: msg
                });
                return 
            }
            if (this.curObjs[0].objtyp == 'SPT') {
								this.curObjInr = this.curObjs[0].objinr;
								this.curFrm = this.curObjs[0].inifrm;
                this.isCheckUmd().then(() => {
                    this.modelInfo.queinr = this.multipleSelection[0];
                    this.isShowReRouting = true
                })
            } else {
                this.modelInfo.queinr = this.multipleSelection[0];
                this.isShowReRouting = true
            }
          

        },

        yptAddMethod() {
            if (this.multipleSelection.length != 1) {
                this.$notify({
                    title: '提示',
                    message: '请勾选一笔数据',
                    type: 'warning',
                });
                return;
            }
            this.$refs.yptAddDialog.isYptAddVisible = true;
            this.$refs.yptAddDialog.formData.ftynum = this.ftynum;
            this.$refs.yptAddDialog.formData.sptinr = this.multipleSelectionRow.objinr;
            this.$refs.yptAddDialog.formData.msgtyp = "BHBLTZ";
            this.$refs.yptAddDialog.formData.reason = "";
        },

        async axqDownloadMethod() {
            if (this.multipleSelection.length != 1) {
                this.$notify({
                    title: '提示',
                    message: '请勾选一笔数据',
                    type: 'warning',
                });
                return;
            }
            const loading = this.loading();
            let res = await Api.post('/public/quesel/axqDownload', {sptinr: this.multipleSelectionRow.objinr});
            loading.close();
            if (res.respCode == SUCCESS) {
                this.$notify({
                    title: '成功',
                    message: '安心签文件下载成功',
                    type: 'success',
                });
            } else {
                this.$notify({
                    title: '错误',
                    message: res.respMsg,
                    type: 'error',
                });
            }
        },

        async axqUploadMethod() {
            if (this.multipleSelection.length != 1) {
                this.$notify({
                    title: '提示',
                    message: '请勾选一笔数据',
                    type: 'warning',
                });
                return;
            }
            const loading = this.loading();
            let res = await Api.post('/public/quesel/axqUploadConfirm', {sptinr: this.multipleSelectionRow.objinr});
            loading.close();
            if (res.respCode == SUCCESS) {
                this.$notify({
                    title: '成功',
                    message: '安心签文件上传确认成功',
                    type: 'success',
                });
            } else {
                this.$notify({
                    title: '错误',
                    message: res.respMsg,
                    type: 'error',
                });
            }
        },
        confirmMethod() {
            if (!this.multipleSelection.length) {
                this.$notify({
                    title: '提示',
                    message: '请至少选择一笔数据',
                    type: 'warning',
                });
                return;
            }
            this.isShowConfirm = true
            this.model.confirmType = '02';
            this.model.remark = '';
        },
        //重置
        handleReset() {
            this.model.bchcon = '';
            this.model.trncorco.ownref = '';
            this.model.relflg = [];
            this.model.usrcon = '';
            // this.model.trncorco.inidatfro = '';
            // this.model.trncorco.inidattil = '';
            this.model.atp.cod = '';
            this.model.trncorco.dflg = [];
            this.model.atptxt = '';
            this.model.searchAllUsers = false;
            this.model.channel = [];
            this.model.frontChannel=[];
            this.model.chnref = '';
            this.model.minamt='';
            this.model.maxamt='';
            this.model.ctmnam='';
            this.model.codeLev = "01";
            this.sortObj={};
            this.handleSearch(orderObj);
        },

        // 机构列表
        async getBranchList() {
            const loading = this.loading();
            let res = await Api.post('/public/quesel/getActBranchList');
            if (res.respCode == SUCCESS) {
                this.bchtypList = res.data.list;
            }
            loading.close();
        },

        //柜员列表
        async getUserList() {
            const loading = this.loading();
            let param={};
            if(this.model.bchcon){
              param.bchcon=this.model.bchcon
            }
            let res = await Api.post("/public/quesel/getActUserList",param);
            if (res.respCode == SUCCESS) {
              this.userList = res.data.list;
            }
            loading.close();
        },

        sortChange(obj) {
            let order = "";
            let prop = "";
            let column = "";
            if(obj && obj.order){
              order=obj.order === 'descending' ? 'desc' : 'asc';
              prop=obj.prop;
            }
            switch (prop) {
                case 'objnam':
                    column = "q.ctmnam";
                    break;
                case 'eciflg':
                    column = "q.eciflg";
                    break;
                case 'chnref':
                    column = "q.chnref";
                    break;
                case 'mancod':
                    column = "atp.mancod";
                    break;
                case 'inifrmName':
                    column = "stb.txt";
                    break;
                case 'ejscpdsta':
                    column = "ejs.sta";
                    break;
                case 'ownref':
                    column = "q.objref";
                    break;
                case 'addtxt':
                    column = "q.objnam";
                    break;
                case 'reloricur':
                    column = "q.relcur";
                    break;
                case 'reloriamt':
                    column = "q.relamt";
                    break;
                case 'inidattim':
                    column = "q.tardattim";
                    break;
                case 'iniusr':
                    column = "q.usrcon";
                    break;
                case 'usr':
                    column = "q.usr";
                    break;
                case 'statusName':
                    column = "q.status";
                    break;
                case 'bchname':
                    column = "b.bchname";
                    break;
                case 'relreq':
                    column = "relreq";
                    break;
                case 'relres':
                    column = "relres";
                    break;
                case 'channelName':
                    column = "q.channel";
                    break;
                case 'cortyp':
                    column = "q.channel";
                    break;
                case 'msgtyp':
                    column = "q.msgtyp";
                    break;
                case 'remark':
                    column = "q.remark";
                    break;
            }
            let orderObj = {
                order: order,
                column: column
            }
            this.$orderObj = orderObj
            this.sortObj=orderObj;
            this.handleSearch(orderObj);
        },
        async getUnAssignData () {
          const loading = this.loading();
          const res = await Api.post('/public/sptsel/getTask', {});
          if (res.respCode === SUCCESS) {
            this.$notify({
              title: '成功',
              message: '领取任务成功!',
              type: 'success',
            });
          }else{
            this.$alert(res.respMsg, '提示', {
                confirmButtonText: '确定'
            })
          }
          loading.close();
          this.handleSearch();
      },

      async getAutoUnAssignData () {
        const loading = this.loading();
        const res = await Api.post('/public/sptsel/getTask', {autFlag:"Y"});
        loading.close();
    },

        //查询列表
        async handleSearch(orderObj) {
            if(this.$refs.relTable) {
                this.$refs.relTable.clearSelection();
            }
            let inidatfro = this.model.trncorco.inidatfro;
            let inidattil = this.model.trncorco.inidattil;
            if (!inidattil) {
                this.$notify.error({
                    title: '错误',
                    message: '查询结束日期必输!'
                });
                return;
            }
            if (Number(this.model.minamt)>Number(this.model.maxamt)) {
                this.$notify.error({title: '错误', message: '业务金额区间错误!'});
                return;
            }
            let comarray=[...this.model.channel,...this.model.frontChannel];
            let params = {
                roletypeId: JSON.parse(window.sessionStorage.curRole).id,
                roletypeName: JSON.parse(window.sessionStorage.curRole).name,
                ownref: this.model.trncorco.ownref?this.model.trncorco.ownref.trim():this.model.trncorco.ownref,
                inidatfro: inidatfro ? moment(inidatfro).format('YYYY-MM-DD') + ' 00:00:00' : "",
                inidattil: moment(inidattil).format('YYYY-MM-DD') + ' 23:59:59',
                usrcon: this.model.usrcon,
                chnref: this.model.chnref,
                relflg: this.model.relflg,
                bchcon: this.model.bchcon,
                cod: this.model.atp.cod,
                bustypList: this.model.trncorco.dflg,
                atptxt: this.model.atptxt,
                pageNo: this.pagination.pageIndex,
                pageSize: this.pagination.pageSize,
                channel: comarray,
                minamt:this.model.minamt,
                maxamt:this.model.maxamt,
                ctmnam:this.model.ctmnam,
                codeLev: this.model.codeLev,
						};
            if (orderObj) {
                params.orderStr = orderObj.order;
                params.columnStr = orderObj.column
            }

            if (this.model.relflg.includes('H') && this.model.relflg.length===1) {
                params.foldflg = true;
            } else {
                params.foldflg = false;
            }
            //查询接口
            const loading = this.loading();
            const res = await Api.post('/public/quesel/list', params);
            if (res.respCode === SUCCESS) {
                let trninrList=[];
                if(this.currentOrg==="1000"){
                  res.data.list.forEach((item)=>{
                      item.usr="-new-assigned-".indexOf(item.status)>0?item.usr:"-";
                      if(this.isPubHeadFuhe() && item.objtyp==='TRN' ){
                         trninrList.push(item.objinr);
                      }
                  })
                  if(trninrList.length>0){
                      this.doCheckReleaseList(trninrList);
                  }
                // }else{
                //     //获取二级分行复核的权限
                //     let accbch=JSON.parse(window.sessionStorage.accbch)
                //     if(accbch && accbch.lev==="2") {
                //         res.data.list.forEach((item) => {
                //             if ('-保函复核-'.indexOf(this.roletypeName) > 0 && item.objtyp === 'TRN') {
                //                 trninrList.push(item.objinr);
                //             }
                //         })
                //         this.doCheckReleaseBranchList(trninrList);
                //     }
                }
                if (this.model.relflg.includes('H') && this.model.relflg.length===1) {
                    this.foldData.data = res.data.list;
                    this.paginationFold.total = res.data.total;
                } else {
                    this.stmData.data = res.data.list;
                    this.pagination.total =res.data.total;
                }
            }
            loading.close();
        },

        async doCheckReleaseList(inrList){
          let res = await Api.post('/public/trnrel/checkReleaseList', {trninrList:inrList});
          if (res.respCode == SUCCESS) {
              this.checkReleaseList=res.data;
          }
        },

        async doCheckReleaseBranchList(inrList){
            if(inrList.length>0) {
                let res = await Api.post('/public/trnrel/checkReleaseBranchList', {trninrList: inrList});
                if (res.respCode == SUCCESS) {
                    this.checkReleaseList = res.data;
                    // let failResult= res.data.filter((item)=>{
                    //     return item.success===false;
                    // })
                    // for(let i=0;i<failResult.length;i++){
                    //     let matchIndex = this.stmData.data.findIndex(item => {
                    //         return item.objtyp==="TRN" && item.objinr===failResult[i].trninr;
                    //     });
                    //     if(matchIndex >=0){
                    //         this.stmData.data[matchIndex].message=failResult[i].message;
                    //     }
                    // }
                }
            }
        },

        async exportExcel() {
            let inidatfro = this.model.trncorco.inidatfro;
            let inidattil = this.model.trncorco.inidattil;
            if (!inidattil) {
                this.$notify.error({
                    title: '错误',
                    message: '查询结束日期必输!'
                });
                return;
            }
            const loading = this.loading();
            let params = {
                roletypeId: JSON.parse(window.sessionStorage.curRole).id,
                roletypeName: JSON.parse(window.sessionStorage.curRole).name,
                ownref: this.model.trncorco.ownref?this.model.trncorco.ownref.trim():this.model.trncorco.ownref,
                inidatfro: inidatfro ? moment(inidatfro).format('YYYY-MM-DD') + ' 00:00:00' : "",
                inidattil: moment(inidattil).format('YYYY-MM-DD') + ' 23:59:59',
                usrcon: this.model.usrcon,
                relflg: this.model.relflg,
                bchcon: this.model.bchcon,
                cod: this.model.atp.cod,
                bustypList: this.model.trncorco.dflg,
                atptxt: this.model.atptxt,
                pageNo: this.pagination.pageIndex,
                pageSize: this.pagination.pageSize,
                channel: this.model.channel,
                codeLev: this.model.codeLev,
                assignFlag:this.model.assignFlag,
            };
            if (this.multipleSelection && this.multipleSelection.length > 0) {
                params.selinr = this.multipleSelection;
            }

            let res = await Api.post('/public/quesel/exportExcel', params);
            if (res.respCode == SUCCESS) {
                let name = moment(new Date()).format('yyyy-MM-DD HH:mm:ss');
                res.data.forEach((arr, index) => {
                    if (index == 0) return
                    let num = parseFloat(arr[7])
                    if (isNaN(num)) num = 0
                    arr[7] = {
                        v: num,
                        t: 'n',
                        z: '#,##0.00'
                    }
                })
                // XLSX.SSF._table[164]='0.000'
                Utils.exportToExcel(res.data, "待办列表_" + name + ".xlsx", "待办列表");
            }
            loading.close();
        },

        //交易代码
        async onSeainf() {
            this.dialogTitle = `交易列表`;
            this.dialogTableVisible = true;
            // 分层取值
            this.loadingFlag = true;
            this.tableList = [];
            this.currentPage = 1;
            this.pageSize = 10000;
            this.total = 0;
            // 获取table的表格数据
            let params = {
                cod: this.model.atp.cod,
                pageNo: this.currentPage,
                pageSize: this.pageSize
            };
            const res = await Api.post('/public/quesel/getFrameList', params);
            if (res.respCode === SUCCESS) {
                if (res.data && res.data.list) {
                    this.total = res.data.total;
                    res.data.list.forEach((item, i) => {
                        item.index = i + 1;
                    });
                    this.tableList = res.data.list;
                }
            }
            this.loadingFlag = false; //接口调完变成false
        },

        currentChange(num) {
            this.currentPage = num;
            this.getTableData();
        },

        async dbClickRow(row, column, event) {
            // 此处为了回填数据时回调
            this.$emit('handleChange')
            // 回填数据
            this.model.atp.cod = row.cod;
            this.dialogTableVisible = false;
        },
        beforeClose(done) {
            this.dialogTableVisible = false;
            this.currentPage = 1;
            done();
        },

        //交易详情
        async onWaitDetail(idx, row) {
            let res = await Api.post("/public/trnrel/getFinTrnInfo", {trninr:row.objinr});
            if (res.respCode == SUCCESS) {
                let trninr =row.inr;
                let inifrm=row.inifrm;
                if(res.data.finTrninr){
                  trninr = res.data.finTrninr;
                  inifrm = res.data.finInifrm;
                }            
                //待复核详情
                this.routerPush({
                    path: '/business/inftrnpsDetail',
                    query: {
                        inr: trninr,
                        inifrm: inifrm.toLocaleLowerCase(),
                        businessType: row['objtyp']
                    }
                });
            }
        },

        //归档详情
        async onFoldDetail(idx, row) {
            let inifrm = row['inifrm'].toLocaleLowerCase();
            if (row.objtyp === "SPT") {
                if(row.inifrm==="SPTROU"){
                  this.showFoldMsg(row.objinr);
                }else{
                  //待经办详情
                  this.routerPush({
                      path: `/display/${inifrm}`,
                      query: {
                          businessInr: row['objinr'],
                          businessType: row['objtyp'],
                          type: "sptview"
                      }
                  });
              }
            }
        },
        //归档下的报文展示
        async showFoldMsg(sptinr) {
          let params = {}
          params.sptinr = sptinr;
          let res = await Api.post("/public/quesel/showSmhList", params);
          if (res.respCode == SUCCESS) {
              // 一条直接展示多条展示列表
              if (res.data.smhList.length == 1) {
                  this.messageVisible = false;
                  this.$nextTick(() => {
                      this.$refs.msgView.fileViewDispaly(-1, {smhinr: res.data.smhList[0].inr})
                  })
              } else {
                  this.messageVisible = true;
                  this.messageData = res.data.smhList;
              }
          }
      },
        async onViewImgList (idx, row) {
          let params = {
            status: row.status,
            ownref: row.ownref,
            objtyp: row.objtyp,
            objinr: row.objinr,
            inifrm: row.inifrm
          }
          let res = await Api.post("/public/imgsel/getImgParams", params);
          console.log('row', res)
          this.imgParams.tradeCode = res.data.tradeCode
          this.imgParams.imginr = res.data.imgInr
          this.imgParams.sdhflg = res.data.sdhFlg
          this.imgParams.smhinr = res.data.smhInr
          this.imgParams.trnName = res.data.trnName
          this.imgParams.businessInr = res.data.businessInr

          let curRole = JSON.parse(window.sessionStorage.curRole).name;
          let curOrgLevel = JSON.parse(window.sessionStorage.currentOrg).level;
          let isDisplay = (curRole.indexOf("经办") !== -1);//是否经办
          let isHead = (curOrgLevel == 0);//是否总行
          //是否收单行交易
          if(this.imgParams.sdhflg){
            if(!isHead && isDisplay) {
              this.imgParams.limit = false
            };
          }else{
            if(isDisplay) {
              this.imgParams.limit = false
            };
          }
          // 总行
          if(isHead){
            let hasImgs = await this.checkImgList(this.imgParams);
            if(hasImgs > 0){
              this.showimgListDialogDialog = true
              this.$refs.sunscanRef.refresh();
            } else {
              this.$notify.warning("当前业务没有影像记录!");
            }
          }
          else {
            this.showimgListDialogDialog = true
            this.$refs.sunscanRef.refresh();
          }
        },
        async checkImgList(reqParams){
          let trninr = this.$route.query.businessInr || null
          let data = {
            ownref: reqParams.tradeCode,
            imginr: reqParams.imginr,
            trninr: reqParams.businessInr,
            msginr: reqParams.smhinr,
            branch: JSON.parse(window.sessionStorage.currentOrg).departmentNumber
          };
          let res = await Api.post("/public/imgsel/getImgCount", data);
          return res.data;
        },
        //处理
        async onHandle(idx, row) {
            let inifrm = row['inifrm'].toLocaleLowerCase();
            let params = {
                queinr: row.inr
            }
            if (inifrm === "sptrou") {
                this.isShowReRouting = true;
                this.$refs.reroutingDialog.modelInfo.queinr = row.inr;
                return;
            }
            let res = await Api.post("/public/quesel/checkStatus", params);
            if (res.respCode == SUCCESS) {
                let inftxt = res.data.inftxt;
                if (row['status'] === 'waiting_confirm') {
                    this.customerConfirm(row);
                } else if (row['status'] === 'correct') {
                    this.correctDeal(row, res.data.reason);
                } else {
										this.curObjInr = row.objinr;
										this.curFrm = row.inifrm;
                    this.isCheckUmd().then(() => {
                        this.rw02Deal(row, inftxt);
                    })
                }
            } else {
                this.$notify({
                    title: "错误",
                    message: res.respMsg,
                    type: "error",
                });
            }
            this.$refs.relTable.toggleRowSelection(row,false);
        },

        // 判断是否是黑名单
        isCheckUmd() {
            return new Promise(async (resolve, reject) => {
                let params = {
                    sptinr: this.curObjInr,
                    transName: this.curFrm
                };
                //查询接口
                const loading = this.loading();
                const res = await Api.post('/public/umdsel/umdSptCheck', params);
                if (res.respCode === SUCCESS) {
                    this.tymdData.data = res.data.sptList;
                    this.paginationTymd.total = Number(res.data.total);
                    this.tymdDataTmp.data = res.data.umdList;
                    if (res.data.sptList) {
                        this.$nextTick(() => {
                            res.data.sptList.map((item, index) => {
                                if (item.inr === res.data.sptinr) {
                                    this.$refs.tymdData.setCurrentRow(this.$refs.tymdData.data[index])
                                    this.handleRowClickTymd(item)
                                }
                            })
                        });
                    }
                    if (!res.data.errorMap.message) {
                        resolve()
                    } else {
                        this.$notify({
                            title: '错误',
                            message: res.data.errorMap.message,
                            type: "warning",
                        });
                        reject()
                    }
                }
                loading.close();
            })
        },
        // 案例查询
        async handleEgSearch() {
            let params = {
                sptinr: this.curObjInr,
                transName: this.curFrm
            };
            //查询接口
            const loading = this.loading();
            const res = await Api.post('/public/umdsel/initumdSpt', params);
            if (res.respCode === SUCCESS) {
                this.tymdData.data = res.data.sptList;
                this.paginationTymd.total = Number(res.data.total);
                this.tymdDataTmp.data = res.data.umdList;
                this.$nextTick(() => {
                    res.data.sptList.map((item, index) => {
                        if (item.inr === res.data.sptinr) {
                            this.$refs.tymdData.setCurrentRow(this.$refs.tymdData.data[index])
                            this.handleRowClickTymd(item)
                        }
                    })
                })
            }
            loading.close();
        },

        taskMethod(){
          this.routerPush({path: '/business/mandist'});
        },
        // 点击对应的案例,填充案例编号
        handleRowClickTymd(row) {
						this.curObjInr = row.inr;
						this.curFrm = row.inifrm;
            this.tymdData2.data = [];
            this.tymdDataTmp.data.forEach(umd => {
                if (umd.sptinr == row.inr) {
                    Object.keys(this.codeMap).forEach(key => {
                        if (umd.code == key) {
                            umd.code = this.codeMap[key];
                        }
                    });
                    Object.keys(this.casecodeMap).forEach(key => {
                        if (umd.casecode == key) {
                            umd.casecode = this.casecodeMap[key];
                        }
                    });
                    this.tymdData2.data.push(umd);
                    this.tymdData2.caseno = umd.caseno;
                }
            })
        },
        async commonDeal(row) {
            let inifrm = row['inifrm'].toLowerCase();
            let curQuery = {}
            if (row['msgtyp']) {
                curQuery.msgtyp = row['msgtyp']
            }
            if (row.objtyp === 'TRN') {
                curQuery.type = 'rel';
            }

            if (row.objtyp == 'SPT') {
                let rtnmsg = await Api.post(`/${this.moduleRouter()}/lock/isSptAccessible`, {
                    objInr: row['objinr'],
                    objType: row['objtyp'],
                    trnName: inifrm.toUpperCase()
                })
                if (rtnmsg.respCode != SUCCESS) {
                    let msg = '该笔待办数据已被锁定!'
                    if (rtnmsg.data.objTyp != row['objtyp']) {
                        msg = this.convertLockMsg(rtnmsg,msg)
                    }else if(rtnmsg.respCode == '400011'){
                        msg = "请先完成当前业务的起始交易!"
                    }
                    else if (rtnmsg.data && rtnmsg.data.usrId) {
                        msg = msg + "锁定人为" + rtnmsg.data.usrId + ",锁定交易为[" + rtnmsg.data.trnLabel+"]"
                    }
                    this.$notify.error({
                        title: '错误',
                        message: msg
                    });
                    return
                }
                this.routerPush({
                    path: `/business/${inifrm}`,
                    query: {
                        businessInr: row['objinr'],
                        businessType: row['objtyp'],
                        ...curQuery
                    }
                });
            } else if (row.objtyp == 'TRN') {
                let rtnmsg = await Api.post(`/${this.moduleRouter()}/lock/isAccessible`, {
                    objInr: row['objinr'],
                    objType: row['objtyp'],
                    trnName: 'TRNREL'
                })
                if (rtnmsg.respCode != SUCCESS) {
                    let msg = '该笔复核数据已被锁定!'
                    if (rtnmsg.data && rtnmsg.data.usrId) {
                        msg = msg + "锁定人为" + rtnmsg.data.usrId
                    }
                    this.$notify.error({
                        title: '错误',
                        message: msg
                    });
                    return
                }
                this.routerPush({
                    path: `/review/review-${inifrm}`,
                    query: {
                        businessInr: row['objinr'],
                        businessType: row['objtyp'],
                        ...curQuery
                    }
                });
            }

        },

        rw02Deal(row, inftxt) {
            if (inftxt && trim(inftxt)) {
                const h = this.$createElement;
                let infarray = inftxt.split("\n");
                this.$confirm(
                    h('div', [
                        h('p', infarray[0]),
                        h('p', infarray[1]),
                        h('p', infarray[2]),
                        h('p', infarray[3])
                    ]), '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(async () => {
                    this.commonDeal(row);
                })
            } else {
                this.commonDeal(row);
            }
        },

        correctDeal(row, reason) {
            if (reason && trim(reason)) {
                this.$confirm(reason, '驳回原因:', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(async () => {
                    this.commonDeal(row);
                })
            } else {
                this.commonDeal(row);
            }
        },

        async customerConfirm(row) {
          //待客户确认增加锁
            let rtnmsg = await Api.post(`/${this.moduleRouter()}/lock/isAccessible`, {
              objInr: row['objinr'],
              objType: row['objtyp'],
              trnName: 'TRNREL'
          })
          if (rtnmsg.respCode != SUCCESS) {
              let msg = '该笔待办数据已被锁定!'
              if (rtnmsg.data && rtnmsg.data.usrId) {
                  msg = msg + "锁定人为" + rtnmsg.data.usrId
              }
              this.$notify.error({
                  title: '错误',
                  message: msg
              });
              return
          }

            this.$confirm('客户已确认此笔交易?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(async () => {
                let params = {
                    queinr: row.inr
                }
                let res = await Api.post("/public/quesel/customerConfirm", params);
                if (res.respCode == SUCCESS) {
                    this.$notify({
                        title: '成功',
                        message: '客户确认成功',
                        type: 'success',
                    });
                    this.handleSearch();
                }
            })
        },
        // 退回
        async onReturn(ind, row) {
           //判断是否被锁
           let rtnmsg = await Api.post(`/${this.moduleRouter()}/lock/getSptAccessible`, { objInr: row.objinr, objType: row.objtyp, trnName: row.inifrm.toUpperCase() })
           if (rtnmsg.respCode===SUCCESS && rtnmsg.data && rtnmsg.data.usrId) {
             let msg = '该笔待办数据已被锁定!' + "锁定人为" + rtnmsg.data.usrId + ",锁定交易为[" + rtnmsg.data.trnLabel+"]"
             this.handleVisible = false;
             this.$notify.error({ title: '错误', message: msg });
             return
           }
          //单证中心退回
          if ((row.cla === 'RIM' || row.cla === 'PEN' || row.cla === 'COR' || row.cla === 'EJS' || row.cla === 'YPT' || row.cla === 'INC')
              && row.sdhflg === 'X') {
              this.queinr = row.inr;
              this.isOrderVisible = true;
              this.model.remark = "";
              return;
          }

          //云平台退回
          if (row.channel === 'YPT' && row.frontChannel!=='ZT') {
              this.queinr = row.inr;
              this.model.yptntf = "";
              this.isYptVisible = true
              return;
          }

          if (row.channel === 'EJS') {
              this.$refs.ejsRepairDialog.queinr = row.inr;
              this.$refs.ejsRepairDialog.isEjsVisible = true;
              this.$refs.ejsRepairDialog.formData.ejsntf="";
              return;
          }
            if ("-SWT-HVP-FMT-CIP-ZT-".indexOf(row.channel)>0 ||row.frontChannel==='ZT' ) {
                let res = await Api.post('/public/sptcpt/initIncReback',{inr:row.objinr});
                if (res.respCode == SUCCESS) {
                    this.$refs.cipRepairDialog.cipData.direction = res.data.direction;//01阳光E结算 02核心,03中台
                    this.$refs.cipRepairDialog.cipData.smhList = res.data.smhList;
                    if(res.data.msgtyp!=='T2D' && row.channel==='SWT' && row.inifrm==='CPTADV'){
                        this.$notify.error({ title: '错误', message: 'SWIFT报文无需退回!' });
                        return;
                    }
                    if( row.channel==='SWT' && !row.inifrm.startsWith("CPT")){
                        this.$notify.error({ title: '错误', message: 'SWIFT报文无需退回!' });
                        return;
                    }
                }
                this.$refs.cipRepairDialog.queinr = row.inr;
                this.$refs.cipRepairDialog.sptinr = row.objinr;
                this.$refs.cipRepairDialog.isCipVisible = true;
                this.$refs.cipRepairDialog.cipData.cipntf="";
                return;
            }
        },

        //单证中心退回
        async orderReturn(row) {
            this.$refs.modelForm.validate((valid) => {
                if (valid) {
                    this.$confirm('您确定退回该笔交易?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(async () => {
                        let params = {
                            queinr: this.queinr,
                            remark: this.model.remark
                        }
                        let res = await Api.post("/public/quesel/backToBranch", params);
                        if (res.respCode == SUCCESS) {
                            this.$notify({
                                title: '成功',
                                message: '退回成功',
                                type: 'success',
                            });
                            this.isOrderVisible = false
                            this.model.remark = "";
                            this.handleSearch();
                        }
                    })
                }
            })
        },

        async confirmSubmit() {
            this.$refs.confirmForm.validate((valid) => {
                if (valid) {
                    this.$confirm('您确定提交该笔交易?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(async () => {
                        let params = {
                            inrList: this.multipleSelection,
                            confirmType: this.model.confirmType,
                            remark: this.model.remark
                        }
                        let message = this.model.confirmType === "01" ? "柜员确认成功" : "柜员待确认成功";
                        let res = await Api.post("/public/quesel/confirmBusiness", params);
                        if (res.respCode == SUCCESS) {

                            this.$notify({
                                title: '成功',
                                message: message,
                                type: 'success',
                            });
                            this.isShowConfirm = false
                            this.model.remark = "";
                            this.handleSearch();
                        }
                    })
                }
            })
        },


        //云平台提交
        yptSummit() {
          this.$refs.yptForm.validate((valid) => {
            if (valid) {
            this.$confirm('您确定退回该笔交易?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(async () => {
                let params = {
                    queinr: this.queinr,
                    reason: this.model.yptntf
                }
                let res = await Api.post("/public/quesel/yptRepair", params);
                if (res.respCode == SUCCESS) {
                    this.$notify({
                        title: '成功',
                        message: '退回成功',
                        type: 'success',
                    });
                    this.closeYptDialog();
                    this.handleSearch();
                }
            });
          }
        });
        },

        // rerouting
        singleManualAssign(index, row) {
            this.multipleSelection = [row.inr]
            this.multipleSelectionRow = row;
            this.isShowReRouting = true
        },
        // 批量手工分配
        mulManualAssign() {
            if (!this.multipleSelection.length) {
                this.$notify({
                    title: '提示',
                    message: '请至少选择一个需要手工分配的数据',
                    type: 'warning',
                });
                return;
            }
            this.isShowReRouting = true
        },
        // 手工分配关闭弹框
        closeConfirmDialog() {
            this.isShowConfirm = false
        },
        closeDialog() {
            this.isShowReRouting = false
        },
        closeYptDialog() {
            this.isYptVisible = false
        },
        closeOrderDialog() {
            this.isOrderVisible = false
        },
        // 手工分配成功回调,刷新页面
        refresh() {
            this.isShowReRouting = false
            this.handleSearch();
        },
        handleToggleSearch: function () {
          this.searchToggle = !this.searchToggle
          this.$emit('search-toggle', this.searchToggle)
        },
        // pageSize改变
        handleSizeChange(val) {
            this.pagination.pageIndex = 1;
            this.pagination.pageSize = val;
            this.handleSearch(this.sortObj);
        },
        // 页码改变
        handleCurrentChange(val) {
            this.pagination.pageIndex = val;
            this.handleSearch(this.sortObj);
        },
        // pageSize改变
        handleSizeChangeFold(val) {
            this.paginationFold.pageIndex = 1;
            this.paginationFold.pageSize = val;
            this.handleSearch();
        },
        // 页码改变
        handleCurrentChangeFold(val) {
            this.paginationFold.pageIndex = val;
            this.handleSearch();
        },
        selectableFn(row) {
            return true;
        },
        async onDisplay(idx, row) {
          let res = await Api.post("/public/trnrel/getFinTrnInfo", {trninr:row.creobjinr});
          if (res.respCode == SUCCESS) {
            let trninr = res.data.trninr;
            let inifrm = res.data.inifrm.toLocaleLowerCase();
            this.routerPush({
              path: `/review/review-${inifrm}`,
              query: {
                businessInr: trninr,
                businessType: "TRN",
                type: 'view'
              }
            });
          }
        },
        writeReleaseList(obj){
          //写入release数据
          let findBool=false;
          for(let i=0;i<this.checkReleaseList.length;i++){
              if( obj.trninr===this.checkReleaseList[i].trninr){
                this.checkReleaseList[i].success=obj.success;
                findBool=true;
                break;
              }
          }
          if(!findBool){
            this.checkReleaseList.push(obj);
          }
        },

        async checkRelease(row){
           //选中单笔业务,校验复核角色处理按钮权限
           const loading = this.loading();
           let res = await Api.post('/public/trnrel/checkRelease', {trninr: row.objinr});
           if (res.respCode == SUCCESS) {
               if(res.data){
                this.writeReleaseList({trninr:row.objinr,success:true});
               }else{
                this.writeReleaseList({trninr:row.objinr,success:false});
               }
           }
           loading.close();
        },
        tableClick(row,column,event) {
            if(!row)
                return;
            if(column && column.property==="op")
                return;
            if(!row.flag){
                row.flag="X";
                this.$refs.relTable.toggleRowSelection(row,true);
            }else{
                row.flag="";
                this.$refs.relTable.toggleRowSelection(row,false);
            }
        },
        // 表格多选
        async handleSelectionChange(val) {
            this.multipleSelection = val.map((item) => {
                return item.inr
            })
            this.multipleSelectionObj = val.map((item) => {
                return item
            })
            this.curObjs = val.map((item) => {
                return item
            })
            this.multipleStatusSelection = val.map((item) => {
                return item.status
            })
            let length=this.multipleSelectionObj.length;
            this.multipleSelectionRow =length && length>0?this.multipleSelectionObj[length-1]:{};

            if (this.multipleSelectionObj && this.multipleSelectionObj.length===1 && this.multipleSelectionObj[0].objtyp === 'TRN') {
              this.checkRelease(this.multipleSelectionObj[0]);
           }
            if (this.multipleSelectionRow && this.multipleSelectionRow.inifrm==="CPTADV" && this.multipleSelectionRow.eciflg!=='0' && "-103-cips111-".indexOf(this.multipleSelectionRow.msgtyp)>0){
                //转电商队列
                if(this.$refs.relTable) {
                    //已归档不做dolayout
                    this.$nextTick(() => {
                        this.$refs.relTable.doLayout();
                    })
                }
            }
            if (this.multipleSelectionRow && this.multipleSelectionRow.objtyp === 'SPT' && this.multipleSelectionRow.channel === 'YPT' && this.multipleSelectionRow.objinr) {
                const loading = this.loading();
                let res = await Api.post('/public/quesel/initAxqButton', {sptinr: this.multipleSelectionRow.objinr});
                if (res.respCode == SUCCESS) {
                    this.axqDownloadVisible = res.data.axqDownloadVisible;
                    this.axqUploadVisible = res.data.axqUploadVisible;
                    this.yptAddDisable = res.data.yptAddDisable;
                    this.ftynum = res.data.ers ? res.data.ers.ftynum : "";
                }
                loading.close();
            }
        },
        handleTabClick(tab) {
            let name = tab.name;
            switch (name) {
                case 'tymd':
                    this.handleEgSearch()
                    break;
                default:
                    return;
            }
        },
        // 页码改变
        handleCurrentChangeTymd(val) {
            this.paginationTymd.pageIndex = val;
            this.handleSearchTymd();
        },
        // pageSize改变
        handleSizeChangeTymd(val) {
            this.paginationTymd.pageIndex = 1;
            this.paginationTymd.pageSize = val;
            this.handleSearchTymd();
        },
    },
};