import Utils from '~/utils/index';
import Api from '~/service/Api';
import moment from 'moment'
export default {
  methods: {
    //重置
    handleReset() {
      this.model.bchcon = '';
      this.model.trncorco.ownref = '';
      this.model.trncorco.relflg = '0';
      this.model.usrcon = '';
      this.model.trncorco.inidatfro = '';
      this.model.trncorco.inidattil = '';
      this.model.atp.cod = '';
      this.model.trncorco.dflg = '1';
      this.model.atptxt = '';
      this.model.searchAllUsers = false;
    },

    // 获取transaction弹框表格数据
    async queryGridDialog(cod) {
      let params = {
        inr: '',
        oldkey: '',
        dissel: '',
        usrcon: '',
        rouflg: '',
        sepflg: '',
        cod: cod,
        dtaflg: '',
        lnkobj: '',
        pageNum: 1,
        pageSize: 10,
      };
      const loading = this.loading();
      let res = await Api.post('/service/trnrel/findAtpCod', params);
      if (res.respCode == SUCCESS) {
        this.$refs['gridSelectDialog'].show = true;
        this.$refs['gridSelectDialog'].cod = cod;
        this.$refs['gridSelectDialog'].tableData =
          res.data && res.data.atpList.list;
        this.$refs['gridSelectDialog'].pagination.total = Number(
          (res.data && res.data.atpList.total) || 0
        );
      }
      loading.close();
    },
    // 选中transaction弹框表格的行数据
    selectGridEtyPromptData(val) {
      this.$emit('changeModel', val);
    },
    //查询列表
    async handleSearch() {
      let inidatfro = this.model.trncorco.inidatfro;
      if (!inidatfro || inidatfro == '') {
        this.$notify.error({ title: '错误', message: '查询开始日期必输!' });
        return;
      }
      let inidattil = this.model.trncorco.inidattil;
      if (!inidattil || inidattil == '') {
        this.$notify.error({ title: '错误', message: '查询结束日期必输!' });
        return;
      }
      if (this.model.trncorco.relflg == '') {
        this.model.trncorco.relflg = '0';
      }
      let params = {
        ownref: this.model.trncorco.ownref,
        inidattil: moment(this.model.trncorco.inidattil).format('YYYY-MM-DD'),
        inidatfro: moment(this.model.trncorco.inidatfro).format('YYYY-MM-DD'),
        usrcon: this.model.usrcon,
        relflg: this.model.trncorco.relflg,
        bchcon: this.model.bchcon,
        cod: this.model.atp.cod,
        dflg: this.model.trncorco.dflg,
        atptxt: this.model.atptxt,
        bchtyp: '',
        iniusr: '',
        userId: 'ZL',
        pageNum: this.pagination.pageIndex,
        pageSize: this.pagination.pageSize,
      };
      //查询接口
      const loading = this.loading();
      const res = await Api.post('/service/trnrel/getTenrelList', params);
      if (res.respCode === SUCCESS) {
        this.stmData.data = res.data.list;
        this.pagination.total = Number(res.data.total);
        this.$store.commit('setTaskList', {
          key: 'trnrel',
          val: this.stmData.data && this.stmData.data.length,
        });
        this.$store.commit('setLoadingFreshReview', false)
      }
      loading.close();
    },

    //交易代码
    async onSeainf() {},

    //交易详情
    async onWaitDetail(idx, row) {
      let viewurl = 'business-new/inftrnpsDetail';
      let params = {
        inr: row.inr,
        userId: sessionStorage.getItem('userId') || 'ZL'
      };
      const res = await Api.post('/service/trnrel/getTenrelDetailData', params);
      if (res.respCode === 'AAAAAA') {
        let model = res.data;
        sessionStorage.setItem('InftrnpsDetail', JSON.stringify(model));
        this.$router.push({ path: viewurl, query: {} });
      } else {
        const h = this.$createElement;
        const msg = res.respMsg || '请求执行失败!';
        this.$notify.error({
          title: '错误',
          message: h('p', { style: 'word-break:break-all;' }, msg),
        });
      }
    },

    //处理
    async onHandle(idx, row) {
      let trnName = row.trnName;
      const operateId = await this.$store.dispatch(
        'Transaction/setOperateFuns',
        {
          pass: this.onRelrow.bind(this, idx),
          refuse: this.onReprow.bind(this, idx),
        }
      );
    //   let Flag = JSON.parse(localStorage.getItem('flag_'+row.inifrm.toLowerCase()))
    //  //判断该交易名是否存在已打开复核页面,如果存在则提示
    //   if ( Flag  ) {
    //     console.log
    //     this.$notify({
    //       title: "错误",
    //       message: row.inifrm.toLowerCase()+"交易已存在一笔复核",
    //       type: "error",
    //   });
    //   return
    //   }
      this.$router.push({
        // name: 'Review-new' + trnName.charAt(0).toUpperCase() + trnName.substring(1),
        path: 'review-new/review' + row['inifrm'].toLowerCase(),
        query: { trn: row['inr'], operateId: operateId,newFlag:row.inifrm.toLowerCase(),inr: row.objinr,trninr: row.inr},
        params: { prePageId: this.model.pageId },
      });
      localStorage.setItem(`review_${row.inifrm.toLowerCase()}`, JSON.stringify(row))
      //进入复核之后,给该交易的交易码设置flag,用来判断是否存在该交易码的复核页面
      localStorage.setItem(`flag_${row.inifrm.toLowerCase()}`,true)
    },
    async onRelrow(idx) {
      this.$confirm('您确定复核该笔交易?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
         // 提交复核之后给移除该交易码的flag,用来判断此交易码没有当前页面
        localStorage.removeItem('flag_'+this.$route.query.newFlag)
        let params = {
          transName: 'trnrel',
          userId: window.sessionStorage.userId || 'ZL',
          selirn: [this.$route.query.trn]
        }
        let rtnmsg = await Api.post('/service/trnrel/relrow', params);
        if (rtnmsg.respCode === SUCCESS) {
          let errorMsg = '';
          let fieldErrorsFlag = !rtnmsg.data.fieldErrors;
          if (!fieldErrorsFlag) {
            let errorMsgkey = '';
            let errorMsgVal = '';
            for (const key in rtnmsg.data.fieldErrors) {
              errorMsgkey = key;
              errorMsgVal = rtnmsg.data.fieldErrors[key];
            }
            errorMsg = errorMsgkey + ':' + errorMsgVal;
            this.$notify.error({
              title: '错误',
              message: '复核失败!错误信息[' + errorMsg + ']',
            });
          } else {
            this.$notify({
              title: '成功',
              message: '复核成功',
              type: 'success',
            });
            this.$store.dispatch('TagsView/delView', this.$route);
            this.$router.history.push('/taskList', () => {
              this.$store.commit('setTaskListTabVal', 'trnrel');
              // 刷新表格
              this.$store.commit('setLoadingFreshReview', true);
            });
          }
        } else {
          let errorMsg = '';
          let fieldErrorsFlag = !rtnmsg.data.fieldErrors;
          if (!fieldErrorsFlag) {
            let errorMsgkey = '';
            let errorMsgVal = '';
            for (const key in rtnmsg.data.fieldErrors) {
              errorMsgkey = key;
              errorMsgVal = rtnmsg.data.fieldErrors[key];
              errorMsg = errorMsg + errorMsgkey + ':' + errorMsgVal + ';';
            }
          } else if (rtnmsg.respMsg) {
            errorMsg = rtnmsg.respMsg;
          }
          this.$notify.error({
            title: '错误',
            message: '复核失败!错误信息[' + errorMsg + ']',
          });
        }
      });
    },

    //交易快照
    // display(inr) {
    //   let params = {
    //           inr: inr,
    //           transName: 'trnrel',
    //           userId: sessionStorage.getItem('userId') || 'ZL',
    //       };
    //     Api.post('/service/trnrel/getTrnNameByInr', params).then((res) => {
    //       if (res.respCode == SUCCESS) {
    //           const trnName = res.data.toLowerCase();
    //           let viewurl = "/#/display/" + trnName + "?trninr=" + inr
    //           window.open(viewurl, 'newwindow', 'height=1500,width=1200,top=100,left=100,toolbar=no,resizable=no,menubar=no,location=no, status=no');
    //       }
    //   });
    // },

    //处理-退回
    async onReprow(idx) {
      this.$confirm('您确定退回该笔交易?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
         // 退回复核之后移除该交易码的flag,用来判断此交易码没有当前页面
        localStorage.removeItem('flag_'+this.$route.query.newFlag)
        let params = {
          trninr: this.$route.query.trn,
          transName: 'trnrel',
          userId: sessionStorage.getItem('userId') || 'ZL',
          pageId: this.model.pageId || '1',
          dflg: '',
          relflg: '',
          inidatfro: '',
          inidattol: '',
        };
        let rtnmsg = await Api.post('/service/trnrel/reprow', params);
        if (rtnmsg.respCode == SUCCESS) {
          let errorMsg = '';
          let fieldErrorsFlag =
            !rtnmsg.fieldErrors || JSON.stringify(rtnmsg.fieldErrors) == '{}';
          if (!fieldErrorsFlag) {
            let errorMsgkey = '';
            let errorMsgVal = '';
            for (const key in rtnmsg.fieldErrors) {
              errorMsgkey = key;
              errorMsgVal = rtnmsg.fieldErrors[key];
            }
            errorMsg = errorMsgkey + ':' + errorMsgVal;
            this.$notify.error({
              title: '错误',
              message: '退回失败!错误信息[' + errorMsg + ']',
            });
          } else {
            this.$notify({
              title: '成功',
              message: '退回成功',
              type: 'success',
            });
            this.$store.dispatch('TagsView/delView', this.$route);
            this.$router.history.push('/taskList', () => {
              this.$store.commit('setTaskListTabVal', 'trnrel');
              // 刷新表格
              this.$store.commit('setLoadingFreshReview', true);
            });
          }
        } else {
          let errorMsg = '';
          let fieldErrorsFlag =
            !rtnmsg.fieldErrors || JSON.stringify(rtnmsg.fieldErrors) == '{}';
          if (!fieldErrorsFlag) {
            let errorMsgkey = '';
            let errorMsgVal = '';
            for (const key in rtnmsg.fieldErrors) {
              errorMsgkey = key;
              errorMsgVal = rtnmsg.fieldErrors[key];
              errorMsg = errorMsg + errorMsgkey + ':' + errorMsgVal + ';';
            }
          } else if (rtnmsg.respMsg) {
            errorMsg = rtnmsg.respMsg;
          }
          this.$notify.error({
            title: '错误',
            message: '退回失败!错误信息[' + errorMsg + ']',
          });
        }
      });
    },

    // pageSize改变
    handleSizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.handleSearch();
    },
    // 页码改变
    handleCurrentChange(val) {
      this.pagination.pageIndex = val;
      this.handleSearch();
    },
  },
};