import Api from '~/service/Api';
import Utils from "~/utils/index"
import commonFunctions from '~/mixin/commonFunctions.js';
import operationFunc from "~/mixin/commonDepend";

export default {
  mixins: [commonFunctions, operationFunc],
  methods: {
    onRecpanGetref() {
      Api.post(`/${this.moduleRouter()}/${this.trnName}/getOwnref`, this.model).then((res) => {
        if (res.respCode == SUCCESS) {
          if (res.data != null) {
            this.model.recgrp.rec.ownref = res.data;
          }
        }
      })
    },
    getBchcodlist(data) {
      return Api.post(`/Financing/bch/getBchcodelist`, data);
    },
    onCopy() {

    },
    //全部删除
    onClrdan() {
      this.model.recpan.danlst = [];
    },
    
    file2XLSX(file) {
			return new Promise(function (resolve, reject) {
				// 通过FileReader对象读取文件
				const reader = new FileReader()
				// 读取为二进制字符串
				reader.readAsBinaryString(file)
				reader.onload = function (e) {
					console.log(e, '读取文件成功的e');
					// 获取读取文件成功的结果值
					const data = e.target.result
					// XLSX.read解析数据,按照type 的类型解析
					const XLSX = require('xlsx')
					let wb = XLSX.read(data, {
						type: 'binary' // 二进制
					})
					console.log(wb, '---->解析后的数据')
					// 存储获取到的数据
					const result = []
					// 工作表名称的有序列表
					wb.SheetNames.forEach(sheetName => {
						result.push({
							// 工作表名称
							sheetName: sheetName,
							// 利用 sheet_to_json 方法将 excel 转成 json 数据
							sheet: XLSX.utils.sheet_to_json(wb.Sheets[sheetName])
						})
					})
					resolve(result)
				}
			})
    },
    
    changeRcvTotCur() {
      this.model.recgrp.rec.cur = this.model.recgrp.rec.rcvtotcur;
      const danlst = this.model.recpan.danlst;
      for (let i = 0; i < danlst.length; i++) {
        const danl = danlst[i];
        danl.cur = this.model.recgrp.rec.rcvtotcur;
      }
    },
    async refreshLnelstAndCuslst() {
      await Api.post(`/${this.moduleRouter()}/${this.trnName}/calDanlst`, this.model).then((res) => {
        if (res.respCode == SUCCESS) {
          if (res.data != null) {
            this.model.recgrp.inelst = res.data.recgrp.inelst;
            this.model.recgrp.cuslst = res.data.recgrp.cuslst;
            this.model.recgrp.rec.inenum = res.data.recgrp.inelst.length;
            this.model.recgrp.rec.cusnum = res.data.recgrp.cuslst.length;
            this.model.recpan.totamt = res.data.recpan.totamt;
            this.model.recpan.bgdamt = res.data.recpan.bgdamt;
            this.model.recgrp.rec.rcvtotamt = res.data.recpan.totamt;
            this.model.recgrp.rec.amt = res.data.recpan.bgdamt;
          }
        }
      })
    },
    isExistsInelst(ineref) {
      if (this.model.recpan.lenlst.length > 0) {
        for (let i = 0; i < this.model.recgrp.lenlst.length; i++) {
          if (ineref === this.model.recgrp.lenlst[i].ineref) {
            return true;
          }
        }
      }

      return false;
    },
    //查询发票关联保单通知书
    onInvnotbut() {
      let params = {
        policyNo: this.model.policyno,
        inelst: this.model.invlst.split(/\r\n|\r|\n/),
      };
      Api.post(`/${this.moduleRouter()}/${this.trnName}/qureyInvoicesNotices`, params).then((res) => {
        if (res.respCode == SUCCESS) {
          if (res.data != null) {
            this.model.invnotres = res.data.list;
          }
        } else {
          this.$notify({
            title: "失败",
            message: res.respMsg,
            type: "error"
          });
        }
      })
    },
    //查询线下承保通知书发票信息
    onNotinvbut() {
      let params = {
        policyNo: this.model.policyno,
        noticeId: this.model.noticeid,
      };
      Api.post(`/${this.moduleRouter()}/${this.trnName}/qureyNoticeInvoices`, params).then((res) => {
        if (res.respCode == SUCCESS) {
          if (res.data != null) {
            this.model.notinvres = res.data.list;
          }
        } else {
          this.$notify({
            title: "失败",
            message: res.respMsg,
            type: "error"
          });
        }
      })
    },
    //校验线下承保通知书
    onRecpanNotchk() {
      this.root.$refs['modelForm'].validateField(['recgrp.rec.policyno']);
      this.root.$refs['modelForm'].validateField(['recgrp.rec.noticeid']);
      if (this.model.recgrp.rec.policyno && this.model.recgrp.rec.noticeid) {
        let params = {
          policyNo: this.model.recgrp.rec.policyno,
          noticeId: this.model.recgrp.rec.noticeid,
        };
        const loading = this.loading();
        Api.post(`/${this.moduleRouter()}/${this.trnName}/onRecpanNotchk`, params).then((res) => {
          if (res.respCode == SUCCESS) {
            loading.close();
            if(res.data.noticeFlag) {
              if(res.data.noticeFlag === 1){
                this.$alert('核验成功!', '提示', {
                  confirmButtonText: "确认",
                })
              } else {
                this.$alert('此承保通知书已失效!', '提示', {
                  confirmButtonText: "确认",
                })
                this.model.recgrp.rec.noticeid = "";
              }
            } else {
              this.$notify.error({
                title: '错误',
                message: '未能获取到此承保通知书状态,核验失败'
              });
            }
          } else {
            this.$notify.error({
              title: '错误',
              message: res.respMsg
            });
          }
          loading.close();
        })
      }
    },

    //进入交易初始化
    async init(params) {
      const rtnmsg = await Api.post(`/${this.moduleRouter()}/${this.trnName}/init`, params);
      if (rtnmsg.respCode === SUCCESS) {
        this._rtnmsg = rtnmsg;
        Utils.copyValueFromVoData(this.model, rtnmsg.data);
        if (this.model.recpan.danlst.length == 0) {
          //   for (let i = 0; i < 10; i++) {
          //     this.model.recpan.danlst.push({
          //       clinam: "",
          //       ineref: "",
          //       ineamt: "0.00",
          //       cur: "",
          //       cusref: "",
          //       cusamt: "0.00"
          //     })
          //   }
        }
      }
    },
    //提交
    async handSubmit() {
      this.$refs['modelForm'].clearValidate();
      this.$refs["modelForm"].validate(async (validStatic) => {
        if (validStatic) {
          await Api.post(`/${this.moduleRouter()}/${this.trnName}/save`, this.model).then((res) => {
            if (res.respCode == SUCCESS) {
              if (res.fieldErrors && Object.keys(res.fieldErrors).length > 0) {
                const tab = this.showBackendErrors(res.fieldErrors);
                if (tab) {
                  // 判断校验失败的表单不属于当前的tab,则切换tab到对应报错的tab页面
                  if (tab.name !== this.tabVal) {
                    this.tabClick(tab, '1');
                  }
                }
              } else {
                this.$notify({
                  title: '成功',
                  message: '提交成功',
                  type: 'success',
                });
                this.$nextTick(() => {
                  this.$store.commit('delTagsArry', this.$route.path)
					        this.$router.back()
                })
              }
            } else {
              this.$notify({
                title: '失败',
                message: res.respMsg,
                type: 'error',
              });
              this.showFrontendErrors()
            }
          })
        } else {
          // 前端校验失败
          this.$notify({
            title: '失败',
            message: '校验失败',
            type: 'error',
          });
          this.showFrontendErrors()
        }
      });
    },
    //检核
    handCheck() {
      this.$refs['modelForm'].clearValidate();
      this.$refs["modelForm"].validate(async (validStatic) => {
        if (validStatic) {
          if (this.model.recpan.danlst.length == 0) {
            this.$alert("至少输入一条关单信息!");
          } else {
            const res = await Api.post(`/${this.moduleRouter()}/${this.trnName}/checkAll`, this.model);
            if (res.respCode == SUCCESS) {
              if (res.fieldErrors && Object.keys(res.fieldErrors).length > 0) {
                const tab = this.showBackendErrors(res.fieldErrors);
                if (tab) {
                  // 判断校验失败的表单不属于当前的tab,则切换tab到对应报错的tab页面
                  if (tab.name !== this.tabVal) {
                    this.tabClick(tab, '1');
                  }
                }
              } else {
                this.$notify({
                  title: "成功",
                  message: "校验成功",
                  type: "success",
                });
              }
            } else {
              this.$message.info(res.respMsg)
            }
          }
        } else {
          // 前端校验失败
          this.$notify({
            title: '失败',
            message: '校验失败',
            type: 'error',
          });
          this.showFrontendErrors()
        }
      });
    },
    //暂存
    handPend() {
      const loading = this.loading('正在暂存数据');
      Api.post(`/${this.moduleRouter()}/${this.trnName}/pend`, this.model).then((res) => {
        if (res.respCode == SUCCESS) {
          loading.close();
          this.$notify({
            title: '成功',
            message: '暂存成功',
            type: 'success',
          });
          this.$store.commit('delTagsArry', this.$route.path)
					this.$router.back()
        } else {
          this.$message.info(res.respMsg)
        }
        loading.close();
      })
    },
    //退出
    handleExit() {
      this.$confirm("确认退出?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$store.commit('delTagsArry', this.$route.path)
        this.$router.back()
      })
    },
    commitAdd(data) {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          add(this.dataForm)
            .then((res) => {
              if (res.errorCode == SUCCESS || res.respCode == SUCCESS) {
                this.$notify.success("添加成功!");
                //此方法为了刷新dbCode列表数据
                this.$refs.selectCur.init();
                this.dialogFlg = false;
                this.onDblctySearch();
              } else {
                this.$notify.error("国家代码重复,添加失败!");
              }

            })
            .catch((err) => {
              this.$notify.error("添加失败!");
            });
        } else {
          this.$notify.error({
            title: '失败',
            message: '请检查必输项!'
          });
        }
      });
    },
    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
      }
    },
  },
};