<template>
	<div class="eibs-tab">

		<c-col :span="6">

			<c-fullbox>
				<el-form-item label="查验编号" prop="fftref">
					<c-input v-model="model.fftref" placeholder="查验编号"></c-input>
				</el-form-item>
				<template slot="footer">
					<c-button @click="getInvuse" size="small" type="primary">获取</c-button>
				</template>
			</c-fullbox>

		</c-col>
		<c-col :span="18">
			<el-form-item label-width="0px" style="margin-left:2px">
				<c-button @click="excelUpload" size="small" type="primary">Excel导入</c-button>
				<c-button @click="addRow" size="small" type="primary">人工新增</c-button>
					<c-button @click="deleteRow" size="small" type="primary">
					删除
				</c-button>
			</el-form-item>
		</c-col>
		

		<c-col :span="24">
			<el-form ref="invTable" :model="model" label-width="120px" label-position="right" size="small" :validate-on-rule-change="false">
			<el-table max-height="300px" style="text-align: center;" @selection-change="changeSelection1" stripe :data="model.invgrdm.invlst" :paginationShow="false" :border="true">
				<el-table-column type="selection" align="left"  min-width="50">
					</el-table-column>
				<el-table-column label="发票影像ID" sortable min-width="100px" prop="imagid">
					<template slot-scope="scope">
						<c-input v-model="scope.row.imagid"></c-input>
					</template>
				</el-table-column>
				<el-table-column label="发票类型" sortable min-width="110px" prop="invtyp">
					<template slot-scope="scope">
						<c-select v-model="scope.row.invtyp"  dbCode="typinv"></c-select>
					</template>
				</el-table-column>
				<el-table-column label="发票号码" sortable min-width="110px" prop="invnum">
					<template slot-scope="scope">
						<el-form-item :prop="'invgrdm.invlst.' + scope.$index + '.invnum'" label-width="0" :rules="[{required:true,message:'必输项',trigger:['blur','change']}]">
								<c-input v-model="scope.row.invnum" >
								</c-input>
							</el-form-item>
					</template>
				</el-table-column>
				<el-table-column label="发票代码" sortable min-width="110px" prop="invcod">
					<template slot-scope="scope">
						<el-form-item :prop="'invgrdm.invlst.' + scope.$index + '.invcod'" label-width="0" :rules="[{required:true,message:'必输项',trigger:['blur','change']}]">
								<c-input v-model="scope.row.invcod" >
								</c-input>
							</el-form-item>
					</template>
				</el-table-column>
				<el-table-column label="非税金额" sortable min-width="110px" prop="untamt">
					<template slot-scope="scope">
						<c-input-currency :precision="2" v-model="scope.row.untamt">
						</c-input-currency>
					</template>
				</el-table-column>

				<el-table-column label="开票日期" sortable min-width="110px" prop="invdat">
					<template slot-scope="scope">
						<c-date-picker v-model="scope.row.invdat">
						</c-date-picker>
					</template>
				</el-table-column>
				<el-table-column label="有效标识" sortable min-width="100px" prop="valflg">
					<template slot-scope="scope">
						<c-select v-model="scope.row.valflg" dbCode="vldflg"></c-select>
					</template>
				</el-table-column>
			</el-table>
			</el-form>

		</c-col>
		<el-dialog v-dialogDrag width="30%" title="Excel导入" :before-close="closeDialog" :visible.sync="detailsDialog" v-if="detailsDialog">
					<c-col :span="4">
						<el-form-item label-width="0px">
							<el-upload action="#" :before-upload="beforeUpload" :show-file-list="false" accept=".xlsx, .xls, .csv">
								<c-button slot="trigger" size="small" type="primary">选择文件</c-button>
							</el-upload>
						</el-form-item>
					</c-col>
					<c-col :span="4">
						<el-form-item label-width="0px" style="margin-left:10px">
							<c-button @click="downFile()" type="primary" size="small">下载模板</c-button>
						</el-form-item>
					</c-col>
		</el-dialog>

	</div>
</template>
<script>
import Api from "~/service/Api";
import moment from "moment";
import commonFunctions from '~/mixin/commonFunctions.js';

export default {
  inject: ["root"],
	props: ["model"],
	mixins: [commonFunctions],
  data() {
    return {
      dbCodes: {
        invtyp: []
			},
			detailsDialog: false,
			selection1: []
    };
  },
  methods: {
    async getdbCode(dbCode, codeNam) {
      let params = {
        codeType: dbCode,
        uil: "EN"
      };
      let rtnmsg = await Api.post("/manager/dic/listDicInfo", params);
      if (rtnmsg.respCode === SUCCESS) {
        let srvtxt = rtnmsg.data.map(item => ({
          value: item.codeValue,
          label: item.codeName
        }));
        this.dbCodes[codeNam] = srvtxt;
      }
    },
    getLabel(list, id) {
      if (id != "" && Array.isArray(list) && list.length != 0) {
        return !list.find(item => item["value"] == id)
          ? id
          : list.find(item => item["value"] == id)["label"];
      }
		},
		changeSelection1(val) {
      this.selection1 = val;
		},
		//校验发票
		invTable(){
			this.$refs["invTable"].validate(async valid => {
        if (!valid) {
					this.$notify({
            title: "失败",
            message: "校验失败",
            type: "error"
					});
				}
      });
		},
		addRow() {
			let newRow = {
				imagid: '00000000-0000-0000-0000-000000000000',
				invcod: '',
				invnum: '',
				invdat: null,
				untamt: 0.00,
				valflg: 'VLID',
			};
			let start = 0;
			if (this.model.invgrdm.invlst) {
				start = this.model.invgrdm.invlst.length;
			}
			this.model.invgrdm.invlst.splice(start, 0, newRow);
		},
		deleteRow(){
			if(this.selection1.length == 0){
				this.$message.warning("请选择需要删除的数据");
        return;
			}
			for (var i = this.selection1.length - 1; i >= 0; i--) {
					this.model.invgrdm.invlst.splice(this.selection1[i].index, 1);
				}
		},
    async getInvuse() {
      if (this.model.fftref == "") {
        this.$message.warning("请输入影像编号");
        return;
      }
      let res = await Api.post("/manager/invchk/getImfInfoForElcadd", this.model.fftref);
      if (res.respCode == SUCCESS) {
				if(res.data.errorMsg){
					this.$message.warning(res.data.errorMsg);
					return
				}
        if(res.data.invlst != null){
					this.model.invgrdm.invlst = this.model.invgrdm.invlst.concat(
          res.data.invlst
        );
				}
      }
		},
		closeDialog() {
			this.detailsDialog = false
		},
		excelUpload(){
			this.detailsDialog = true
		},
		beforeUpload(file) {
      this.file2XLSX(file).then(res => {
        let newData = res[0].sheet.map(item => ({
          imagid:
            "00000000-0000-0000-0000-000000000000",
          invcod: item.hasOwnProperty("发票代码")
            ? typeof item["发票代码"] === "number"
              ? item["发票代码"].toString().trim()
              : item["发票代码"].trim()
            : "",
          invnum:
            typeof item["发票号码"] === "number"
              ? item["发票号码"].toString().trim()
              : item["发票号码"].trim(),
          invdat:
            this.changeDate(typeof item["开票日期(YYYY-MM-DD)"] === "number"
              ? moment("1900-01-01")
                  .add(item["开票日期(YYYY-MM-DD)"] - 2, "days")
                  .format("YYYY-MM-DD")
              : item["开票日期(YYYY-MM-DD)"]),
          untamt: item.hasOwnProperty("非税金额(小数点后两位)")
            ? item["非税金额(小数点后两位)"].toString().trim()
            : "",
          amountin: item.hasOwnProperty("发票占用金额(小数点后两位)")
            ? item["发票占用金额(小数点后两位)"].toString().trim()
            : "",
          checkcode:item.hasOwnProperty("校验码后六位") ? (typeof item["校验码后六位"] === "number"
              ? item["校验码后六位"].toString().trim()
              : item["校验码后六位"].trim()) :""
            ,
          amounttax: item.hasOwnProperty("价税合计金额(小数点后两位)")
            ? item["价税合计金额(小数点后两位)"].toString().trim()
            : "",
          valflg: "VLID",
					reason: "",
					state:""
        }));

        this.model.invgrdm.invlst = this.model.invgrdm.invlst.concat(
          newData
				);
				this.detailsDialog = false
      });
      return false;
		},
		//日期格式转换
		changeDate(val){
			let result = val.replace(/\//g,"-")
			return result
		},
		async downFile() {
			let params = {
				path: 'sstf/data/doc/invoiceAuthen.xlsx'
			}
			let res = await Api.post("/manager/fileupdown/fileDown", params);
			if (res.respCode == "AAAAAA") {
				//res.data 内容为 TextResultVo 
				if (res.data.data) {
					let type, code = res.data;
					const loading = this.loading()
					this.base64ToBlob(code, type)
					loading.close()
					this.$notify({
						title: "成功",
						message: "文件下载成功!",
						type: "success",
					});
					this.detailsDialog = false
				}
				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);
		},
		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)
				}
			})
		},
  },
  mounted() {
    this.getdbCode("typinv", "invtyp");
  },
  created() {}
};
</script>
<style scoped lang="less">
.eibs-tab{
	/deep/ .el-dialog{
		height: 200px!important;
		margin-top: calc(50vh - 100px)!important;
	}
	/deep/ .el-dialog__body{
		height: calc(100% - 65px);
	}
}
</style>