<template>
	<div class="g-main">
		<div class="m-table">
			<div class="u-table-btn1">
				<el-upload
					:headers="$getElUploadHeaders()"
					ref="upload"
					class="upload-btn"
					action="uploadUlr"
					:limit="1"
					:accept="'.xls,.xlsx'"
					:with-credentials="true"
					:show-file-list="false"
					:auto-upload="true"
					:on-progress="handleProgress"
					:on-success="handleExcelSuccess"
					:before-upload="beforeExcelUpload"
					:http-request="uploadHttpRequest"
				>
					<el-button
						size="small"
						class="diy-button--white"
						:loading="importLoading"
						>表格导入</el-button
					>
				</el-upload>

				<el-button
					class="diy-button--white"
					size="small"
					style="margin-left: 10px"
					@click="handleExportModule()"
					>下载模板</el-button
				>
			</div>

			<div v-if="dataList.length > 0">
				<el-table
					ref="ref_table"
					:data="dataList"
					border
					:height="tableHeight"
					class="m-table-item"
					v-loading="dataListLoading"
					style="width: 100%"
				>
					<el-table-column
						label="序号"
						header-align="center"
						align="center"
						type="index"
						width="100"
					></el-table-column>

					<el-table-column
						prop="srcField"
						header-align="center"
						align="center"
						label="表格信息"
						min-width="100"
					>
					</el-table-column>
					<el-table-column
						prop="field"
						header-align="center"
						align="center"
						label="平台对应信息"
						min-width="110"
					>
						<template slot-scope="scope">
							<span v-if="scope.row.exist">{{
								scope.row.field
							}}</span>

							<div v-else>
								<el-select
									class="item_width_sel"
									v-model="scope.row.itemGroupId"
									size="small"
									placeholder="请选择"
								>
									<el-option
										v-for="item in groupList"
										@click.native="
											handleSelGroup(scope.$index, item)
										"
										:key="item.id"
										:label="item.label"
										:value="item.id"
									>
									</el-option>
								</el-select>

								<el-select
									class="item_width_sel"
									v-model="scope.row.field"
									size="small"
									style="margin-left: 10px"
									placeholder="请选择"
								>
									<el-option
										v-for="item in scope.row.itemList"
										:key="item.itemId"
										:label="item.label"
										:value="item.label"
									>
									</el-option>
								</el-select>
							</div>
						</template>
					</el-table-column>
				</el-table>

				<div ref="divEditBtn" class="m-edit-btn">
					<el-button
						type="primary"
						size="small"
						class="diy-button--blue"
						@click="handleComfirm"
						>保 存</el-button
					>
				</div>
			</div>

			<div class="m-hint" v-else>请先导入表格</div>
		</div>
	</div>
</template>

<script>
import { requestPost } from "@/js/dai/request";
import { mapGetters } from "vuex";

export default {
	data() {
		return {
			customerId: "", // 客户id，父组件传
			customerName: "", // 客户名称，父组件传

			tableParams: {
				customerId: "",
			},
			// tableHeight: 500,
			search: "",
			dataList: [],

			dataListLoading: false,
			total: 0,
			pageSize: 20,
			pageNo: 0,

			formShow: false,
			formData: {},

			scopeList: [],
			dataSyncConfigId: "",
			importLoading: false,

			groupList: [],
			sHeight: 0,

			importCode: "",
			importOption: { exist: {}, notExist: {} },

			fileData: null,
		};
	},

	computed: {
		tableHeight() {
			const h = this.clientHeight - this.sHeight + this.iframeHeigh;
			const _h = this.clientHeight - this.sHeight;
			return this.$store.state.inIframe ? h : _h;
		},

		...mapGetters(["clientHeight", "iframeHeight"]),
	},
	components: {},
	created() {},
	async mounted() {
		// await this.loadData();
		await this.loadPersonGroup();

		this.sHeight = this.$refs.divEditBtn.offsetHeight + 300;
	},
	methods: {
		diaClose() {
			this.formShow = false;
		},

		async loadPersonGroup() {
			const url = "/oper/customize/icformitemgroup/list";
			// const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/isServiceProject/service/serviceScopeTree'
			let params = {
				formCode: "resi_base_info",
				policyFlag: "1",
			};

			const { data, code, msg } = await requestPost(url, params);

			if (code === 0) {
				this.groupList = data;
			} else {
				this.$message.error(msg);
			}
		},

		//选择人员信息第一列下拉框
		async handleSelGroup(index, item, isSet) {
			const url = "/oper/customize/icformitem/getItemListV2";
			// const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/isServiceProject/service/serviceScopeTree'
			let params = {
				policyFlag: "1",
				groupId: item.id,
			};

			const { data, code, msg } = await requestPost(url, params);

			if (code === 0) {
				let oneData = this.dataList[index];
				oneData.itemList = data;
				this.$set(this.dataList, index, oneData);
			} else {
				this.$message.error(msg);
			}
		},

		// 加载列表数据
		async loadData() {
			this.dataListLoading = true;
			// const url = 'http://yapi.elinkservice.cn/mock/245/epmetuser/dataSyncConfig/list'
			const url = "/epmetuser/dataSyncConfig/list";

			this.tableParams = {
				pageSize: this.pageSize,
				pageNo: this.pageNo,
			};

			const { data, code, msg } = await requestPost(
				url,
				this.tableParams
			);
			this.dataListLoading = false;
			if (code === 0) {
				this.total = data.total;
				this.dataList = data.list;
				this.dataList.forEach((element) => {
					element.stateShow =
						element.switchStatus === "open" ? true : false;
				});
			} else {
				// this.$message.error(msg )
			}
		},

		handleChangeScope(value) {
			// console.log('value', value)

			this.orgIdArray = value;
			this.scopeList = [];
			let selArray = this.$refs["myCascader"].getCheckedNodes();

			// console.log('selArray', selArray)

			selArray.forEach((element, index) => {
				let obj = {
					orgId: element.data.agencyId,
					orgType: element.data.level,
					orgIdPath: element.path.join(":"),
				};
				this.scopeList.push(obj);
			});

			console.log("this.scopeList", this.scopeList);
		},

		async handleExportModule() {
			let url = "/actual/base/residentBaseInfo/import/download-template";

			let params = {};
			await this.$http({
				method: "POST",
				url,
				responseType: "blob",
				data: params,
			})
				.then((res) => {
					const url = window.URL.createObjectURL(new Blob([res.data]))
					const aLink = document.createElement('a')
					aLink.style.display = 'none'
					aLink.href = url
					aLink.setAttribute('download', '人员导入模板.zip')
					document.body.appendChild(aLink)
					aLink.click()
					document.body.removeChild(aLink)
					window.URL.revokeObjectURL(url)
					// // this.download(res.data, title + '.xls')
					// if (res.headers["content-disposition"]) {
					// 	let fileName = window.decodeURI(
					// 		res.headers["content-disposition"]
					// 			.split(";")[1]
					// 			.split("=")[1]
					// 	);
					// 	console.log("filename", fileName);
					// 	let blob = new Blob([res.data], {
					// 		type: "application/vnd.ms-excel",
					// 	});
					// 	var url = window.URL.createObjectURL(blob);
					// 	var aLink = document.createElement("a");
					// 	aLink.style.display = "none";
					// 	aLink.href = url;
					// 	aLink.setAttribute("download", fileName);
					// 	document.body.appendChild(aLink);
					// 	aLink.click();
					// 	document.body.removeChild(aLink); //下载完成移除元素
					// 	window.URL.revokeObjectURL(url); //释放掉blob对象
					// } else this.$message.error("下载失败");
				})
				.catch((err) => {
					console.log("err", err);
					return this.$message.error("网络错误");
				});
		},
		// 上传大图标成功
		handleExcelSuccess(res, file) {
			if (res.code === 0 && res.msg === "success") {
				console.log("resss---ppp", res);
			} else {
				this.$message.error(res.msg);
			}
		},
		handleProgress(event, file, fileList) {
			console.log("percentage", file.percentage);
		},

		beforeExcelUpload(file) {
			console.log("file", file);
			const isType = file.type === "application/vnd.ms-excel";
			const isTypeComputer =
				file.type ===
				"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
			const fileType = isType || isTypeComputer;
			const isLt1M = file.size / 1024 / 1024 < 10;
			if (!fileType) {
				this.$message.error("上传文件只能是xls/xlsx格式！");
			}

			if (!isLt1M) {
				this.$message.error("上传文件大小不能超过 10MB!");
			}
			return fileType && isLt1M;
		},

		async uploadHttpRequest(file) {
			this.importLoading = true;
			this.importBtnTitle = "正在上传中...";
			const formData = new FormData(); //FormData对象，添加参数只能通过append('key', value)的形式添加
			formData.append("file", file.file); //添加文件对象
			formData.append("code", ""); //添加文件对象
			await this.$http
				.post("/actual/base/residentBaseInfo/importExcel", formData)
				.then((res) => {
					console.log("res-up", res);
					if (res.data.code == 0 && res.data.msg == "success") {
						console.log(res.data.data);
						const data = res.data.data;

						this.dataList = [
							...Object.keys(data.option.exist).map((k) => {
								return {
									index: k,
									srcField: data.option.exist[k],
									exist: true,
									field: data.option.exist[k],
								};
							}),
							...Object.keys(data.option.notExist).map((k) => {
								return {
									index: k,
									srcField: data.option.notExist[k],
									exist: false,
									field: "",
								};
							}),
						];
						this.importOption = data.option;
						this.importCode = data.code;
						this.fileData = file;
					} else this.$message.error(res.data.msg);
				})
				.catch((err) => {
					console.log("失败", err);
					file.onError(); //上传失败的文件会从文件列表中删除
					// this.$message.error('导入失败')
				});
			this.importLoading = false;
			this.importBtnTitle = "导入";
			this.$refs.upload.clearFiles();
		},

		async handleComfirm() {
			this.importLoading = true;
			this.importBtnTitle = "正在上传中...";
			const { importOption, importCode, dataList } = this;
			dataList.forEach((item) => {
				if (!item.exist) {
					importOption.notExist[item.index] = item.field;
				}
			});
			await this.$http
				.post("/actual/base/residentBaseInfo/import/header", {
					code: importCode,
					option: {
						exist: importOption.exist,
						notExist: importOption.notExist,
					},
				})
				.then((res) => {
					console.log("res-up", res);
					if (res.data.code == 0 && res.data.msg == "success") {
						// this.upload2(this.fileData, this.importCode);
						this.afterSuccess();
					} else this.$message.error(res.data.msg);
				})
				.catch((err) => {
					console.log("失败", err);
					file.onError(); //上传失败的文件会从文件列表中删除
					// this.$message.error('导入失败')
				});
			this.importLoading = false;
			this.importBtnTitle = "导入";
		},

		async upload2(file, code) {
			this.importLoading = true;
			this.importBtnTitle = "正在上传中...";
			const formData = new FormData(); //FormData对象，添加参数只能通过append('key', value)的形式添加
			formData.append("file", file.file); //添加文件对象
			formData.append("code", code); //添加文件对象
			await this.$http
				.post("/actual/base/residentBaseInfo/importExcel", formData)
				.then((res) => {
					console.log("res-up", res);
					if (res.data.code == 0 && res.data.msg == "success") {
						this.afterSuccess();
					} else this.$message.error(res.data.msg);
				})
				.catch((err) => {
					console.log("失败", err);
					file.onError(); //上传失败的文件会从文件列表中删除
					// this.$message.error('导入失败')
				});
			this.importLoading = false;
			this.importBtnTitle = "导入";
			this.$refs.upload.clearFiles();
		},

		afterSuccess() {
			this.$confirm('导入成功，是否到系统管理-导入记录中查看进度?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				center: true
			})
				.then(() => {
					this.$router.replace('/main/importRecord-index');
				})
				.catch(() => {});

			this.dataList = [];
			this.importOption = {};
			this.importCode = "";
			this.fileData = null;
		},

		// 取消
		diaCancel() {
			this.$emit("cancleBack");
		},
	},
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/modules/management/list-main.scss";

.m-edit-btn {
	display: flex;
	margin-top: 20px;
	margin-right: 16px;
	justify-content: flex-end;
	text-align: center;
}

.item_width_sel {
	width: 200px;
}

.m-hint {
	font-size: 50px;
	line-height: 300px;
	text-align: center;
	color: #aaaaaa;
}
</style>
