import Api from '~/service/Api';
import commonFunctions from '~/mixin/commonFunctions.js';
import Utils from "~/utils/index";
import buildFn from '../event/buildCommons.js';

export default {
	mixins: [commonFunctions, buildFn],
	methods: {
		// 点击获取按钮拉取当前key字段下的表单数据
		queryFormData(key) { },
		// 业务信息=》基本信息=》保函编号-----获取保函编号
		queryOwnref() {
			let params = this.model.nidgrp.rec;
			params.ownref = this.model.nitp.tempOwnref;
			if (this.model.nidgrp.rec.hndtyp == "OT") {
				if (!this.model.nidgrp.ben.pts.ptainr || !this.model.nidgrp.rec.gartyp) {
					return
				}
			} else {
				if (!this.model.nidgrp.apl.pts.ptainr || !this.model.nidgrp.rec.hndtyp || !this.model.nidgrp.rec.gartyp) {
					return
				}
            }
            let ptainr = '';
			if (this.model.nidgrp.rec.hndtyp == "OT") {
				ptainr = this.model.nidgrp.ben.pts.ptainr;
			} else {
				ptainr = this.model.nidgrp.apl.pts.ptainr;
            }
            const loading = this.loading();
			let trnName = this.root.trnName.toUpperCase();
			Api.post(`/business/ref/nid?ptaInr=${ptainr}&trnName=${trnName}`, params).then(res => {
				loading.close();
				if (res.respCode == SUCCESS) {
          this.model.nidgrp.rec.ownref = res.data;
          this.model.nitp.tempOwnref = res.data;
				} else {
          this.$message.error(res.respMsg);
        }
			}).catch(() => {
				loading.close();
			});
		},
        changedata(){
            if(this.model.nidgrp.rec.beyzd3 == 'N'){
                this.model.nidgrp.rec.beyzd4 = ''
                this.model.nitp.indirectswiaddc = ''
                this.codes.endtxt = ''
            }
            if(!(this.model.nidgrp.rec.hndtyp == 'OC' && this.model.nidgrp.rec.beyzd3 == 'Y')){
                return
            }
            const loading = this.loading();
            Api.post(`/business/nitopnRule/getBeginAndEndData`).then(res => {
                loading.close();
                if (res.respCode === SUCCESS) {
                    if(res.data){
                        this.model.nitp.indirectswiaddc = res.data.beginGtx.gidtxt;
                        this.$set(this.codes, 'indirectswiaddinr', res.data.beginGtx.inr);
                        this.$set(this.codes, 'endtxt', res.data.endGtx.gidtxt);
                        this.$set(this.codes, 'endinr', res.data.endGtx.inr);
                    }
                }
            }).catch(() => {
                loading.close();
            });
        },
		clearBdbData(){
			this.model.nidgrp.bdb.name = '';
			this.model.nidgrp.bdb.nam = '';
			this.model.nidgrp.bdb.inr = '';
			this.model.nidgrp.bdb.ptyinr = '';
			this.model.nidgrp.bdb.ptainr = '';
			this.model.nidgrp.bdb.extkey ='';
			this.model.nidgrp.bdb.rol = '';
			this.model.nidgrp.bdb.pts.extkey = '';
			this.model.nidgrp.bdb.pts.rol = '';
			this.model.nidgrp.bdb.pts.ptainr = '';
			this.model.nidgrp.bdb.pts.ptyinr = '';
			this.model.nidgrp.bdb.pts.cnnam = '';
			this.model.nidgrp.bdb.pts.cnadr = '';
			this.model.nidgrp.bdb.pts.ennam = '';
			this.model.nidgrp.bdb.pts.enadr = ''
		},
		// 数据采集标志--"cfagit.cfaflg"
		onCfaflg(e) {
			if (e == undefined) {
				return;
			}
			switch (this.model.cfagit.cfaflg) {
				case "1":
					this.model.cfagit.basflg = 'X';
					this.model.cfagit.dclflg = 'X';
					if (!this.model.cfagit.ownextkey) {
						this.model.cfagit.ownextkey = this.codes.ownExtkeyList[0].branch;
					}
					break;
				case "2":
					this.model.cfagit.basflg = 'X';
					this.model.cfagit.dclflg = '';
					break;
				case "3":
					this.model.cfagit.basflg = '';
					this.model.cfagit.dclflg = 'X';
					break;
				case "5":
					this.model.cfagit.vrfflg = 'X';
					this.model.cfagit.dclflg = 'X';
					break;
				default:
					this.model.cfagit.basflg = '';
					this.model.cfagit.vrfflg = '';
					this.model.cfagit.dclflg = '';
			}
			if (this.model.cfagit.cfaflg == "4" || this.model.cfagit.cfaflg == "") {
				this.model.cfagit.ownextkey = "";
			}
		},
		copyValueToCountrycod() {
			this.ejectOitWarning('cty', this.model.nidgrp.rec.countrycod, 'nidgrp.rec.countrycod');
			let val = this.model.nidgrp.rec.countrycod;
			if (this.model.cfagit) {
				this.model.cfagit.recgrp.bas.bencountrycode = val;
				if (this.model.cfagit.recgrp.bas.modifySet) {
					if (!this.model.cfagit.recgrp.bas.modifySet.includes("bencountrycode")) {
						this.model.cfagit.recgrp.bas.modifySet.push("bencountrycode");
					}
				} else {
					this.model.cfagit.recgrp.bas.modifySet = ["bencountrycode"];
				}
			}
			if (this.model.rmbbop.rmb2122) {
				this.model.rmbbop.rmb2122.recgrp.ads.voucheecountrycode = val;
			}
		},
		//申报2122报文
		query2122() {
			let trnName = this.root ? this.root.trnName : this.trnName;
			if (this.model.rmbbop.rmb2122.rmbflg === '1') {
				let rmbbop = this.buildRobbop(this.model, trnName);
				Api.post('/business/rmbbopnid/rmbbop2122Cal', rmbbop).then(res => {
					if (res.respCode === SUCCESS) {
						this.model.rmbbop.rmb2122 = res.data.rmb2122;
						this.model.rmbbop.rmb2122.recgrp.ads.opertype = '1';
					}
				});
			}
		},
		//设置通知行change事件
		setAdvBankChange(){
			//赋值opbnk
			if(this.model.zmqflg === "X" && this.model.nidgrp.adv.pts.extkey !== "")
				this.model.nidgrp.rec.oppbnk = this.model.nidgrp.adv.pts.extkey.slice(0, 11);
		},
		queryCfap() {
			let trnName = this.root ? this.root.trnName : this.trnName;
			if (this.model.cfagit.cfaflg == '1') {
				let cfap = this.buildCfap(this.model, trnName);
				if (cfap.recgrp.dcl == null || cfap.recgrp.dcl.length == 0) {
					var a = [{
						exguarancode: "",
						actiontype: "",
						wabachandate: "",
						basere: "",
						remark: "",
						actiondesc: "",
						acp: "",
					}];
					cfap.recgrp.dcl = a;
				}
				Api.post('/business/nid/cfaMapping', cfap).then(rtnmsg => {
					if (rtnmsg.respCode == SUCCESS) {
            Utils.copyValueFromVoData(this.model.cfagit.recgrp,rtnmsg.data.recgrp);
            if(rtnmsg.data.ownextkey != null && rtnmsg.data.ownextkey != "") {
            this.model.cfagit.ownextkey = rtnmsg.data.ownextkey
            }
            this.model.cfagit.cfatyp = "A";
            this.model.cfagit.recgrp.bas.actiontype = "A";
            this.model.cfagit.recgrp.bas.acp = "X";
            this.model.cfagit.recgrp.dcl[0].actiontype = "A";
            this.model.cfagit.recgrp.dcl[0].acp = "X";
          }
				});
			}
		},
		// 获取地区机构号
		async getOwnExtkeyCondition1() {
			const loading = this.loading();
			let body = { ownExtKey: "" };
			if (this.model.trnInfo && this.model.trnInfo.sdhflg == "X" && this.model.cfagit.ownextkey) {
				body.ownExtKey = this.model.cfagit.ownextkey;
			}
			let res = await Api.post('/business/bch/getBranchListByownExtKey', body);
			loading.close();
			if (res.respCode === SUCCESS) {
				this.ownExtkeyList = res.data;
			}
		},
		onCfaCurDate() {
			var moment = require('moment');
			this.model.cfagit.recgrp.bas.contractdate = this.model.nidgrp.rec.opndat;
			this.model.cfagit.recgrp.bas.maturity = this.model.nidgrp.rec.opndat;
			this.model.cfagit.recgrp.bas.maturity = moment(this.model.nidgrp.rec.opndat).add(20, "years").format("YYYY-MM-DD HH:mm:ss");
			this.model.cfagit.recgrp.bas.guarancurr = this.model.nidgrp.cbs.max.cur;
			this.model.cfagit.recgrp.bas.guaranamount = this.model.nidgrp.cbs.max.amt;
			this.model.cfagit.recgrp.dcl[0].wabachandate = this.model.cfagit.recgrp.bas.contractdate;
			this.model.cfagit.recgrp.dcl[0].basere = this.model.nidgrp.cbs.max.amt;
		},
		onBccls1() {
			if (this.model.addbcb.bccls1 == 'N') {
				if(this.model.nidgrp.rec.hndtyp && this.model.nidgrp.rec.hndtyp == 'OC'){
					this.model.addbcb.expdat = this.model.nidgrp.rec.liadat;
				}else{
				  this.model.addbcb.expdat = this.model.nidgrp.rec.expdat;
				}
      } else if (this.model.addbcb.bccls1 == 'Y') {
				if(this.model.nidgrp.rec.hndtyp && this.model.nidgrp.rec.hndtyp == 'OC'){
					this.model.addbcb.preexpdat = this.model.nidgrp.rec.liadat;
				}else{
				  this.model.addbcb.preexpdat = this.model.nidgrp.rec.expdat;
				}
			}
		},
		// 保函模板转文本
		templateToText() {
			let gtxinr = this.model.nidgrp.rec.gtxinr;
			let textTempData = this.model.textTempData;
			this.formatTxtp(this.model.nidgrp.blk.gtxgidtxt, gtxinr, 'gtx', textTempData, 'nidgrp')
		},
		// 保函模板转反担保协议文本
		templateToTextFdb() {
			let gtxinr = this.codes.indirectswiaddinr;
			console.log(this.model.nitp.indirectswiaddc);
			console.log(gtxinr);
			this.formatTxtp(this.model.nitp.indirectswiaddc, gtxinr, 'gtx', {}, '', 'fdb')
		},
        // 递转保函模板转反担保协议文本
        templateToTextDz() {
            let gtxinr = this.codes.endinr;
            console.log(this.codes.endtxt);
            console.log(gtxinr);
            this.formatTxtp(this.codes.endtxt, gtxinr, 'gtx', {}, '', 'dz')
        },
		// 密文文本解析
		templateToTextMiWen() {
			let gtxinr = this.model.nidgrp.rec.gtxinrmw;
			console.log(this.model.nidgrp.blk.gtxgidtxtmw);
			console.log(gtxinr);
			this.formatTxtp(this.model.nidgrp.blk.gtxgidtxtmw, gtxinr, 'gtx', {}, 'nidgrp', 'gtxinrmw')
		},
		changeTxt() {
			if (!this.model.nidgrp.blk.modifySet || !this.model.nidgrp.blk.modifySet.includes("gidtxt")) {
				this.templateToText()
			}
			if (!this.model.nitp.modifySet || !this.model.nitp.modifySet.includes("indirectswiadd")) {
				this.templateToTextFdb()
			}
            if (!this.model.nitp.modifySet || !this.model.nitp.modifySet.includes("indirectswiadd")) {
                this.templateToTextDz()
            }
			if (!this.model.nidgrp.blk.gidtxtmw && this.model.nidgrp.rec.othersno && (this.model.nidgrp.rec.othersno =='E0000009'
      || this.model.nidgrp.rec.othersno =='E0000016' || this.model.nidgrp.rec.othersno =='E0000017' || this.model.nidgrp.rec.othersno =='E0000020'
      || this.model.nidgrp.rec.othersno == 'E0000024')) {
				this.templateToTextMiWen()
			}
		},
		async getPtsptaInfo() {
			let data = {
				bchbranch: JSON.parse(sessionStorage.getItem("currentOrg")).departmentNumber
			};
			let res = await Api.post('/business/ptspta/getPtsptaInfo', data);
			if (res.respCode === SUCCESS) {
				this.model.nidgrp.con.pts.extkey = res.data.ptaobjkey;
				this.model.nidgrp.con.pts.adrblk = res.data.cnnamadr;
				this.model.nidgrp.con.pts.rol = 'CON';
				this.model.nidgrp.con.pts.ptainr = res.data.ptainr
			}
		},
		async agreementSigning() {
			let data = {
				ftynum: this.model.nitp.yptgimod.img[0].ftynum
			};
			let res = await Api.post('/business/nitopnRule/agreementSigning', data);
			if (res.respCode == "AAAAAA") {
				if (res.data && res.data.data == "Y") {
					this.model.nitp.xyflg = res.data.data;
					this.$notify({
						title: "成功",
						message: "协议盖章成功!",
						type: "success",
					});
				}
				else {
					this.$notify({
						title: '失败',
						message: '协议盖章调用失败,错误信息:' + res.data.respMsg,
						type: 'error',
					});
				}
			}
			else {
				this.$notify({
					title: '失败',
					message: '协议盖章调用失败!',
					type: 'error',
				});
			}
		},
		async showText() {
			let data = this.model.nitp.yptgimod.img;
			let res = await Api.post('/business/nitopnRule/getTextResultVo', data);
			if (res.respCode == "AAAAAA") {
				//res.data 内容为 TextResultVo 
				if (res.data.data) {
					let type, code = res.data;
					switch (res.data.extension) {
						case "pdf": {
							type = "application/pdf";
							this.base64ToBlob(code,type);
							break;
						}
						case "html": {
							type = "text/html";
							this.base64ToBlob(code,type);
							break;
						}
						case "doc": {
							type = "application/msword";
							this.base64ToBlob(code,type);
							break;
						}
						case "docx": {
							type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
							this.base64ToBlob(code,type);
							break;
						}
						case "xls": {
							type = "application/vnd.ms-excel";
							this.base64ToBlob(code,type);
							break;
						}
						case "xlsx": {
							type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
							this.base64ToBlob(code,type);
							break;
						}
						case "txt": {
							type = "text/plain";
							this.base64ToBlob(code,type);
							break;
						}
						case "gif": {
							type = "image/gif";
							this.base64ToBlob(code,type);
							break;
						}
						case "jpeg": {
							type = "image/jpeg";
							this.base64ToBlob(code,type);
							break;
						}
						case "jpg": {
							type = "image/jpeg";
							this.base64ToBlob(code,type);
							break;
						}
						case "png": {
							type = "image/png";
							this.base64ToBlob(code,type);
							break;
						}
						case "bmp": {
							type = "image/bmp";
							this.base64ToBlob(code,type);
							break;
						}
						case "aac": {
							type = "audio/aac";
							this.base64ToBlob(code,type);
							break;
						}
						case "abw": {
							type = "application/x-abiword";
							this.base64ToBlob(code,type);
							break;
						}
						case "arc": {
							type = "application/x-freearc";
							this.base64ToBlob(code,type);
							break;
						}
						case "avi": {
							type = "video/x-msvideo";
							this.base64ToBlob(code,type);
							break;
						}
						case "jar": {
							type = "application/java-archive";
							this.base64ToBlob(code,type);
							break;
						}
						case "js": {
							type = "text/javascript";
							this.base64ToBlob(code,type);
							break;
						}
						case "json": {
							type = "application/json";
							this.base64ToBlob(code,type);
							break;
						}
						case "mp3": {
							type = "audio/mpeg";
							this.base64ToBlob(code,type);
							break;
						}
						case "ppt": {
							type = "application/vnd.ms-powerpoint";
							this.base64ToBlob(code,type);
							break;
						}
						case "pptx": {
							type = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
							this.base64ToBlob(code,type);
							break;
						}
						case "rar": {
							type = "application/x-rar-compressed";
							this.base64ToBlob(code,type);
							break;
						}
						case "svg": {
							type = "image/svg+xml";
							this.base64ToBlob(code,type);
							break;
						}
						case "tar": {
							type = "application/x-tar";
							this.base64ToBlob(code,type);
							break;
						}
						case "zip": {
							type = "application/zip";
							this.base64ToBlob(code,type);
							break;
						}
						case "7z": {
							type = "application/x-7z-compressed";
							this.base64ToBlob(code,type);
							break;
						}
						default: {
							break;
						}
					}
					this.$notify({
						title: "成功",
						message: "文件下载成功!",
						type: "success",
					});
				}
				else {
					this.$notify({
						title: '失败',
						message: '文件下载失败!',
						type: 'error',
					});
				}
			}
		},
		base64ToBlob(code, type) {
			if(type == 'application/pdf') {
				code.data = code.data.replace(/[\n\r]/g, "")
			}
			const raw = window.atob(code.data);
			const rawLength = raw.length;
			const uInt8Array = new Uint8Array(rawLength);
			for (let i = 0; i < rawLength; ++i) {
				uInt8Array[i] = raw.charCodeAt(i);
			}
			const blob = new Blob([uInt8Array], { type: type });
			// const fileURL = URL.createObjectURL(blob);
			// window.open(fileURL)
			let fileName = code.filename;
			var downloadElement = document.createElement('a');
      var href = window.URL.createObjectURL(blob);
      downloadElement.href = href;
      downloadElement.download = fileName;
      document.body.appendChild(downloadElement);
      downloadElement.click();
      document.body.removeChild(downloadElement);
      window.URL.revokeObjectURL(href);
    },
    updateOwnref(){
      let ownref = this.model.nidgrp.rec.ownref;
      if (ownref === '') {
        //编号为空,不处理,需要点击获取按钮得到业务编号
        return;
      }
      let gartyp = this.model.nidgrp.rec.gartyp;
      if (gartyp === '') {
        return;
      }
      if (gartyp === 'V') {
        let flag = ownref.substr(8, 1);
        if (flag !== 'X') {
          ownref = ownref.substr(0, 8) + 'X' + ownref.substr(8);
          this.model.nidgrp.rec.ownref = ownref;
        }
      } else {
        let flag = ownref.substr(8, 1);
        if (flag === 'X') {
          ownref = ownref.substr(0, 8) + ownref.substr(9);
          this.model.nidgrp.rec.ownref = ownref;
        } 
      }
		},
		checkGidtxt() {
			this.$nextTick(() => {
				this.root.$refs['modelForm'].validateField(['nidgrp.blk.gidtxt']);
			})
		},
	},
};