<template>
	<cl-crud @load="onLoad">
		<el-row type="flex">
			<cl-refresh-btn />
			<cl-add-btn>新增单个</cl-add-btn>
			<!-- <el-button type="primary" size="mini" @click="toAdd">上传身份证号</el-button> -->
			<el-button type="primary" size="mini" @click="reqFlag.visible = true"
				>批量上传</el-button
			>
			<cl-multi-delete-btn />
			<cl-flex1 />
			<cl-search-key
				field="id_name"
				:field-list="[
					{
						label: '姓名',
						value: 'id_name'
					},
					{
						label: '身份证号',
						value: 'id_number'
					}
				]"
			></cl-search-key>
		</el-row>

		<el-row>
			<cl-table v-bind="table">
				<!-- <template #column-icon="{ scope }">
					<el-image
					    style="width: 100px; height: 100px"
					    :src="scope.row.icon"
					    :preview-src-list="[scope.row.icon]"
					  />
				</template> -->
			</cl-table>
		</el-row>

		<el-row type="flex">
			<cl-flex1 />
			<cl-pagination />
		</el-row>

		<cl-upsert v-model="form" v-bind="upsert" />

		<!-- 添加身份信息 -->
		<cl-dialog
			title="身份信息管理"
			v-model="reqFlag.visible"
			:props="{
				modal: true,
				customClass: 'cl-chat__dialog',
				'append-to-body': true,
				'close-on-click-modal': false,
				'close-on-press-escape': false
			}"
		>
			<div class="el-div">
				<h3 class="v-line-icon">上传身份信息</h3>
				<el-scrollbar>
					<!-- :model="" -->
					<el-form
						ref="ruleForm"
						label-width="100px"
						size="mini"
						class="demo-ruleForm"
						:disabled="saving"
					>
						<el-form-item label="上传时间" prop="uploadday">
							<el-col :span="12">
								<el-date-picker
									v-model="uploadday"
									type="date"
									placeholder="选择日期"
									:disabled-date="disabledDate"
									:shortcuts="shortcuts"
									format="YYYY-MM-DD"
									value-format="YYYY-MM-DD"
								>
								</el-date-picker>
							</el-col>
						</el-form-item>

						<el-form-item label="选择文件" prop="">
							<el-col :span="12">
								<cl-upload
									v-model="urls"
									accept=".txt"
									list-type="text"
									:limi="1"
									limit-size="10"
								>
									<el-button size="small" type="primary">点击上传</el-button>
									<div slot="tip" class="el-upload__tip" style="color: #ff4200">
										Tips: 只能上传txt文件，且不超过10M
									</div>
									<!-- <el-alert :title="reqFlag.error" v-if="reqFlag.errorTips" type="error" show-icon :closable="false"> </el-alert> -->
								</cl-upload>
								<!-- <cl-upload
									accept=".txt"
									list-type="text"
									:limi="1"
									:auto-upload="false"
									:on-change="openFile"
									:file-list="fileList"
									>
									<el-button size="small" type="primary">点击上传</el-button>
								    <div slot="tip" class="el-upload__tip" style="color: #ff4200;;">Tips: 只能上传txt文件，且不超过10M</div>
									<el-alert :title="reqFlag.error" v-if="reqFlag.errorTips" type="error" show-icon :closable="false"> </el-alert>
								</cl-upload> -->
							</el-col>
						</el-form-item>
						<!-- <el-form-item label="文本预览" v-if="reqFlag.preview">
						    <el-table :data="accounts.slice(0,50)" height="300" row-style="height:14px" cell-style="padding:0" style="width: 100%;margin: 0;font-size: 10px">
						      <el-table-column prop="index" label="序号" width="50"></el-table-column>
						      <el-table-column prop="name" label="账号串" ></el-table-column>
						    </el-table>
						</el-form-item> -->
						<el-form-item label="标记">
							<el-col :span="12">
								<el-input placeholder="请填写标记" v-model="flag" />
							</el-col>
						</el-form-item>
						<el-form-item>
							<!-- <el-button type="primary" @click="submitForm('ruleForm')">上传身份证<i class="el-icon-upload el-icon--right"></i></el-button> -->
							<!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
							<el-button
								size="mini"
								type="primary"
								:disabled="saving"
								@click="batchAdd"
							>
								批量上传
								<i class="el-icon-upload el-icon--right"></i>
							</el-button>
						</el-form-item>
					</el-form>
				</el-scrollbar>
			</div>
		</cl-dialog>
	</cl-crud>
</template>

<script lang="ts">
import { CrudLoad, Table, Upsert } from "cl-admin-crud-vue3/types";
import { defineComponent, inject, reactive, ref, toRefs } from "vue";
import { useRouter } from "vue-router";
import { useRefs } from "/@/core";
import { ElLoading, ElMessageBox } from "element-plus";
// import { ElFile } from "element-plus/lib/el-upload/src/upload.type";

export default defineComponent({
	name: "sys-idcard",
	data() {
		return {
			rules: {
				// name: [
				//   { required: true, message: '请输入活动名称', trigger: 'blur' },
				//   {
				//     min: 3,
				//     max: 5,
				//     message: '长度在 3 到 5 个字符',
				//     trigger: 'blur',
				//   },
				// ],
				uploadtime: [{ required: true, message: "请选择上传时间", trigger: "blur" }]
			}
		};
	},

	setup() {
		const service = inject<any>("service");
		const { refs, setRefs }: any = useRefs();
		const router = useRouter();

		const urls = ref<string>("");
		// const urlList = computed(() => urls.value.split(",").filter(Boolean));

		// 文件列表
		const fileList = ref<any[]>([]);
		// 文本内容
		const accounts = ref<any[]>([]);
		// 标致
		const reqFlag = reactive({
			visible: false,
			errorTips: false,
			preview: false,
			error: ""
		});
		const flag = ref<string>("");
		// 保存状态
		const saving = ref<boolean>(false);
		// const ruleForm= reactive({
		// 	uploadtime: new Date()
		// });
		// 表单值
		const form = reactive<any>({
			relevance: 1
		});

		// 新增、编辑配置
		const upsert = reactive<Upsert>({
			width: "800px",

			items: [
				{
					prop: "id_name",
					label: "姓名",
					span: 20,
					component: {
						name: "el-input",
						props: {
							placeholder: "请填写姓名"
						}
					},
					rules: {
						required: true,
						message: "姓名不能为空"
					}
				},
				{
					prop: "id_number",
					label: "证件号",
					span: 20,
					component: {
						name: "el-input",
						props: {
							placeholder: "请填写证件号"
						}
					},
					rules: {
						required: true,
						message: "证件号不能为空"
					}
				},
				{
					prop: "flag",
					label: "标记",
					span: 20,
					component: {
						name: "el-input",
						props: {
							placeholder: "请填写标记"
						}
					}
				}
			]
		});

		// 表格配置
		const table = reactive<Table>({
			props: {
				"default-sort": {
					prop: "id_name",
					order: "descending"
				}
			},
			columns: [
				{
					type: "selection",
					width: 60
				},
				{
					prop: "id_name",
					label: "姓名",
					sortable: "true",
					minWidth: 120,
					headerAlign: "left",
					align: "left"
				},
				{
					prop: "id_number",
					label: "证件号",
					minWidth: 120,
					headerAlign: "left",
					align: "left"
				},
				{
					prop: "flag",
					label: "标记",
					width: 120,
					headerAlign: "left",
					align: "left"
				},
				{
					prop: "createTime",
					label: "创建时间",
					sortable: "custom",
					minWidth: 150,
					headerAlign: "left",
					align: "left"
				},
				{
					prop: "updateTime",
					label: "更新时间",
					sortable: "custom",
					minWidth: 150,
					headerAlign: "left",
					align: "left"
				},
				{
					label: "操作",
					type: "op"
				}
			]
		});

		function toAdd() {
			router.push("/cool/moudles/shuyou/views/id_card_add");
		}

		// crud 加载
		function onLoad({ ctx, app }: CrudLoad) {
			// console.log(service);
			ctx.service(service.shuyouIdCard).done();
			app.refresh();
		}

		const state = reactive({
			disabledDate(time) {
				return time.getTime() > Date.now();
			},
			shortcuts: [
				{
					text: "今天",
					value: new Date()
				},
				{
					text: "昨天",
					value: () => {
						const date = new Date();
						date.setTime(date.getTime() - 3600 * 1000 * 24);
						return date;
					}
				},
				{
					text: "一周前",
					value: () => {
						const date = new Date();
						date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
						return date;
					}
				}
			],
			uploadday: new Date()
		});

		// function openFile(file,fileList) {
		// 	console.log("function openFile")
		// 	// console.log(fileList)
		// 	// reqFlag.errorTips = false;
		// 	fileList = fileList.slice(-1)
		// 	// // console.log(fileList)
		// 	// let fileName = file.name
		// 	// var reader = new FileReader();
		// 	// let pos = fileName.lastIndexOf('.')
		// 	// let lastName = fileName.substring(pos, fileName.length)
		// 	// const isLt2M = file.size / 1024 / 1024 < 20
		// 	// if (lastName.toLowerCase() !== '.txt') {
		// 	// 	reqFlag.error = '请上传.txt文件类型'
		// 	// 	reqFlag.errorTips = true;
		// 	// 	accounts.value = []
		// 	// } else if (!isLt2M) {
		// 	// 	reqFlag.error = '文件大小不能超过10MB'
		// 	// 	reqFlag.errorTips = true;
		// 	// 	accounts.value = []
		// 	// } else {
		// 	// 	reader.onload = e => this.$emit('load', dealNum(reader.result))
		// 	// 	reader.readAsText(file.raw)
		// 	// }
		// };
		// function dealNum (item) {
		//     // let word = item.replace(/\n|\r\n/g, '<br/>')
		//     let word = item
		//     var dataArr = word.split(/[\r\n]+/) // /[(\r\n)\r\n]+/
		//     dataArr.forEach((item, index) => {
		//         if (!item) {
		//             dataArr.splice(index, 1)// 删除空项
		//         }
		//     })
		//     let objList = []
		//     dataArr.forEach((item, index) => {
		//           let obj = {
		//             index: index,
		//             name: item
		//           }
		//           objList.push(obj)
		//     })
		//     accounts.value = objList
		//     reqFlag.preview = true
		// };
		// 批量新增
		async function batchAdd() {
			saving.value = true;
			const loading = ElLoading.service({
				lock: true,
				text: "上传中，请勿关闭此页面...",
				spinner: "el-icon-loading",
				background: "rgba(0, 0, 0, 0.7)"
			});
			// console.log(urls);
			const params = {
				uploadday: state.uploadday,
				fileaddress: urls,
				flag: flag.value
			};
			await service.shuyouIdCard
				.batchAdd(params)
				.then((data) => {
					console.log(data);
					reqFlag.visible = false;
					loading.close();
					// if (data.code == -1) {
					// 	ElMessage.success(data.message);
					// } else {
					// 	ElMessage.success(data.message);
					// }
					ElMessageBox.alert(data.message, "提示", {
						confirmButtonText: "关闭"
					});
				})
				.catch((err: string) => {
					loading.close();
					ElMessageBox.alert(err, "提示", {
						confirmButtonText: "关闭"
					});
				});
			saving.value = false;
		}

		return {
			service,
			form,
			reqFlag,
			fileList,
			accounts,
			saving,
			...toRefs(state),
			flag,
			upsert,
			table,
			onLoad,
			toAdd,
			// openFile,
			// dealNum,
			batchAdd,
			urls
		};
	},

	methods: {
		// submitForm(formName) {
		//   this.$refs[formName].validate((valid) => {
		//     if (valid) {
		// 		// alert('submit!')
		// 		const params = {
		// 			id_name: '张飞'
		// 		}
		// 		alert(this.accounts[0].name)
		// 		this.$service.shuyou.idCard.data2(params);
		// 		// return this.request({
		// 		// 	url: "/data",
		// 		// 	method: "GET",
		// 		// 	params
		// 		// 	// 参数与 axios 一致
		// 		// });
		//     } else {
		// 		console.log('error submit!!')
		// 		return false
		//     }
		//   })
		// },
		// resetForm(formName) {
		// 	this.$refs[formName].resetFields()
		// 	this.accounts = []
		// },
		// openFile(file,fileList) {
		// 	this.reqFlag.errorTips = false;
		// 	this.fileList = fileList.slice(-1)
		// 	let fileName = file.name
		// 	var reader = new FileReader();
		// 	// alert(fileName)
		// 	let pos = fileName.lastIndexOf('.')
		// 	let lastName = fileName.substring(pos, fileName.length)
		// 	const isLt2M = file.size / 1024 / 1024 < 20
		// 	if (lastName.toLowerCase() !== '.txt') {
		// 		this.reqFlag.error = '请上传.txt文件类型'
		// 		this.reqFlag.errorTips = true;
		// 		this.accounts = []
		// 	} else if (!isLt2M) {
		// 		this.reqFlag.error = '文件大小不能超过10MB'
		// 		this.reqFlag.errorTips = true;
		// 		this.accounts = []
		// 	} else {
		// 		reader.onload = e => this.$emit('load', this.dealNum(reader.result))
		// 		reader.readAsText(file.raw)
		// 	}
		// },
		// dealNum (item) {
		//     // let word = item.replace(/\n|\r\n/g, '<br/>')
		//     let word = item
		//     var dataArr = word.split(/[\r\n]+/) // /[(\r\n)\r\n]+/
		//     dataArr.forEach((item, index) => {
		//         if (!item) {
		//             dataArr.splice(index, 1)// 删除空项
		//         }
		//     })
		//     let objList = []
		//     dataArr.forEach((item, index) => {
		//           let obj = {
		//             index: index,
		//             name: item
		//           }
		//           objList.push(obj)
		//     })
		//     this.accounts = objList
		//     this.reqFlag.preview = true
		// },
	}
});
</script>
<style>
.el-div {
	display: flex;
	flex-direction: column;
	height: 100%;
	position: relative;
	padding: 10px;
	box-sizing: border-box;
	background-color: #fff;
	overflow: hidden;
}
/* 红色短竖线 start */
.v-line-icon {
	position: relative;
	padding-left: 20px;
	margin-bottom: 20px;
}
.v-line-icon:before {
	position: absolute;
	content: "";
	width: 5px;
	height: 18px;
	left: 10px;
	top: 50%;
	margin-top: -9px;
	border-radius: 2px;
	background: #ff4200;
}

/* 红色短竖线 end */
</style>
