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;
          }
        }
      })
    },
    onCopy() {

    },
    //全部删除
    onClrdan() {
      this.model.recpan.danlst = [];
    },
    //批量导入
    onBatimp() {

    },
    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;
    },
    onRecpanNotchk() {
      let params = {
        policyNo: this.model.recgrp.rec.policyno,
        noticeId: this.model.recgrp.rec.noticeid,
      };
      Api.post(`/Financing/dbazxb/qureyNoticeInvoices`, params).then((res) => {
        if (res.respCode == SUCCESS) {
          if (res.data != null) {
            this.model.notinvres = res.data;
          }
        }
      })
    },
    async init(params) {
      const loading = this.loading();
      const rtnmsg = await Api.post(`/${this.moduleRouter()}/${this.trnName}/init`, params);
      if (rtnmsg.respCode === SUCCESS) {
        loading.close();
        this.model = rtnmsg.data;
      } else if (rtnmsg.respCode === '400001') {
        loading.close();
        this.$store.commit('delTagsArry', this.$route.path);
        this.$router.back()
      }
    },
    
    getBchcodlist(data) {
      return Api.post(`/Financing/bch/getBchcodelist`, data);
    },
    refreshLnelstAndCuslst() {
      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;
          }
        }
      })
    },
    handSubmit() {
      this.$refs['modelForm'].clearValidate();
      this.$refs["modelForm"].validate(async (validStatic) => {
        if (validStatic) {
          Api.post(`/${this.moduleRouter()}/${this.trnName}/update`, 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()
        }
      });
      return false;
    },
    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(() => {
        Api.post(`/Financing/dbezxb/exit`, this.model);
        this.$store.commit('delTagsArry', this.$route.path)
        this.$router.back()
      })
    },
  },
};