<template>
	<div class="libraryView">
		<div><span class="el-icon-arrow-left cursor-class" @click="returnAllPicStateClick()"><i
					class="font-fourteen">返回</i></span></div>
		<p><i class="font-eighteen">{{libraryModel.factoryName}}</i>&nbsp;&nbsp;&nbsp;<i
				class="font-fourteen">{{libraryModel.remarks}}</i></p>
		<div class="conditions-div">
			<el-form :model="formModel" :inline="true">
				<el-form-item label=" ">
					<el-input v-model="formModel.name" clearable placeholder=" " disabled></el-input>
				</el-form-item>
<!--        <el-form-item label="姓名">-->
<!--					<el-input v-model="formModel.name" clearable placeholder="姓名"></el-input>-->
<!--				</el-form-item>-->
<!--				<el-form-item label="性别">-->
<!--					<el-radio-group v-model="formModel.sex" @change="sexChange">-->
<!--						<el-radio-button label="0">男</el-radio-button>-->
<!--						<el-radio-button label="1">女</el-radio-button>-->
<!--						<el-radio-button label="">不限</el-radio-button>-->
<!--					</el-radio-group>-->
<!--				</el-form-item>-->
<!--				<el-form-item>-->
<!--					<el-button type="primary" @click="searchClick()">搜索</el-button>-->
<!--				</el-form-item>-->
				<el-form-item style="float: right;">
<!--					<el-button type="primary" @click="addOrUpdateClick('update')">编辑</el-button>-->
					<el-button type="primary" @click="uploadClick()">上传</el-button>
<!--					<el-button type="primary" @click="batchDelClick()" v-if="!selectState">批量删除</el-button>-->
<!--					<el-button-group v-else style="margin-left: 10px;">-->
<!--						<el-button type="danger" @click="confirmBatchDelClick()">确认删除</el-button>-->
<!--						<el-button type="primary" @click="cancelBatchDelClick()">取消删除</el-button>-->
<!--					</el-button-group>-->
				</el-form-item>
			</el-form>
		</div>
		<div>
			<div class="library-div" v-for="item in libraryList">
				<div class="library-btn-class" @mouseover="btnOver(item,$event)" @mouseout="btnOut(item,$event)">
					<img :src="$replaceImgUrl(item.url)" alt="目标图片" height="100%">
<!--					<div class="search-btn" v-show="item.btnState">-->
<!--						<i class="cursor-class font-fourteen" style="color: #FFF;" @click="toRetrieval(item)">检 索</i>-->
<!--					</div>-->
				</div>
				<div class="library-text">
					<div class="library-btn">
						<span><i>姓名：{{item.name}} </i></span>
						<span class="el-icon-edit edit-class cursor-class" @click="updatePicClick(item)"></span>
					</div>
					<div class="library-btn">
						<span><i> </i>
							<i v-if="item.sex==0"> </i>
							<i v-else-if="item.sex==1"> </i>
							<i v-else>不限</i>
						</span>
						<span class="el-icon-delete del-class cursor-class" @click="delPicClick(item,$event)"></span>
					</div>
					<div class="library-btn">
<!--						<span><i>年龄：{{item.age}}({{item.birthDate}})</i></span>-->
						<span v-show="selectState">
							<el-checkbox v-model="item.selectState" @change="checkboxChange(item)"></el-checkbox>
						</span>
					</div>
<!--					<span><i>身份证号码：{{item.idCard}}</i></span>-->
				</div>
			</div>
		</div>
		<div style="clear:both"></div>
		<div>
			<el-pagination @current-change="handleCurrentChange" :current-page.sync="pageObj.pageNo"
				:page-size="pageObj.pageSize" layout="total,prev, pager, next, jumper" :total="total">
			</el-pagination>
		</div>
		<!-- 编辑图片 -->
		<el-dialog :visible.sync="updateDialog" center :show-close="false" :close-on-click-modal="false">
			<span slot="title"><i class="font-sexteen">编辑人像信息</i></span>
			<el-form ref="formUpdateRef" :model="formUpdateModel" :rules="updateRule" label-width="auto">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="formUpdateModel.name" clearable placeholder="姓名" maxlength="30" show-word-limit>
					</el-input>
				</el-form-item>
<!--				<el-form-item label="身份证号码" prop="idCard">-->
<!--					<el-input v-model="formUpdateModel.idCard" clearable placeholder="身份证号码" maxlength="18"-->
<!--						show-word-limit></el-input>-->
<!--				</el-form-item>-->
			</el-form>
			<span slot="footer">
				<el-button type="primary" @click="confirmClick">确认</el-button>
				<el-button @click="cancelClick()">取消</el-button>
			</span>
		</el-dialog>
		<!-- 编辑人脸库 -->
		<LibraryAddUpdate ref="addOrUpdateRef" @refreshClick="refreshClick(arguments)"></LibraryAddUpdate>
		<!-- 上传 -->
		<LibraryUpload ref="uploadRef" @refreshUploadClick="refreshUpload($event)" />
	</div>
</template>

<script>
	import LibraryAddUpdate from "./library-add-update"
	import LibraryUpload from "./library-upload"
	import {
		getIdentityIdInfo
	} from "@/utils/identity.js"
	export default {
		components: {
			LibraryAddUpdate,
			LibraryUpload
		},
		data() {
			// 身份证校验
			var legalIdCardNo = (rule, value, callback) => {
				if (!value) {
					return callback(new Error('身份证号码不能为空'));
				}
				setTimeout(() => {
					let regIdCard =
						/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/
					//如果通过该验证，说明身份证格式正确，但准确性还需计算
					if (regIdCard.test(value)) {
						if (value.length == 18) {
							var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4,
							2); //将前17位加权因子保存在数组里
							var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3,
							2); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
							var idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和
							for (var i = 0; i < 17; i++) {
								idCardWiSum += value.substring(i, i + 1) * idCardWi[i];
							}
							var idCardMod = idCardWiSum % 11; //计算出校验码所在数组的位置
							var idCardLast = value.substring(17); //得到最后一位身份证号码
							//如果等于2，则说明校验码是10，身份证号码最后一位应该是X
							if (idCardMod == 2) {
								if (idCardLast == "X" || idCardLast == "x") {
									callback();
								} else {
									callback(new Error('身份证号码错误'));
								}
							} else {
								//用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
								if (idCardLast == idCardY[idCardMod]) {
									callback();
								} else {
									callback(new Error('身份证号码错误'));
								}
							}
						}
					} else {
						callback(new Error('身份证格式不正确'));
						// callback();
					}
				}, 1000);
			};
			return {
				// 表单查询
				formModel: {
					name: "",
					sex: ""
				},
				libraryList: [],
				// 分页
				total: 0,
				pageObj: {
					pageNo: 1,
					pageSize: 16,
					note: {}
				},
				// 编辑图片
				updateDialog: false,
				// 编辑图片表单
				formUpdateModel: {
					name: "",
					idCard: "",
					idPortrait: "",
				},
				updateRule: {
					name: [{
						required: true,
						message: "请输入姓名",
						trigger: "blur"
					}],
					idCard: [{
						required: true,
						validator: legalIdCardNo,
						trigger: "blur"
					}],
				},
				// 批量删除按钮的隐藏/显示状态
				selectState: false,
				// 批量删除的图片id数组
				idArr: [],
				// 父页面传递的参数
				libraryModel: {},
			}
		},
		methods: {
			// 初始化
			init(row) {
				this.libraryModel = row
				console.log(row)
				this.pageObj.note.libraryId = row.idFactory
				this.commonSeach(this.pageObj)
			},
			// 上传
			uploadClick() {
				this.$nextTick(() => {
					this.$refs.uploadRef.init("upload", "fromView", this.pageObj.note.libraryId)
				})
			},
			// 上传回调
			refreshUpload(formWhere) {
				this.commonSeach()
			},
			// 查询
			searchClick() {
				this.pageObj.note = {
					...this.pageObj.note,
					...this.formModel
				}
				if (this.pageObj.note.name != "") {
					this.pageObj.pageNo = 1
				} else if (this.pageObj.note.age != "") {
					this.pageObj.pageNo = 1
				}
				this.commonSeach()
			},
			// 返回人像库组页面
			returnAllPicStateClick() {
				this.$emit("returnLibraryEmit")
			},
			// 性别筛选
			sexChange(e) {
				this.formModel.sex = e
			},
			// 鼠标事件
			btnOver(row, $event) {
				let arr = JSON.parse(JSON.stringify(this.libraryList))
				this.libraryList = arr.map(item => {
					if (row.url === item.url) {
						item.btnState = true
					}
					return item
				})
			},
			btnOut(row, $event) {
				this.libraryList.forEach((item, index, arr) => {
					if (row.url === item.url) {
						arr[index].btnState = false
					}
				})
			},
			// 分页
			handleCurrentChange(pageNo) {
				this.pageObj.pageNo = pageNo
				this.pageObj.note = {
					...this.pageObj.note,
					...this.formModel
				}
				this.commonSeach()
			},
			// 图片编辑
			updatePicClick(row) {
				// 尝试直接对象赋值
				this.updateDialog = true
				this.formUpdateModel.name = row.name
				this.formUpdateModel.idCard = row.idCard
				this.formUpdateModel.idPortrait = row.idPortrait
			},
			// 保存修改
			confirmClick() {
				this.$refs['formUpdateRef'].validate((valid) => {
					if (valid) {
						this.$http.put("/Resources/updatePortrait", this.formUpdateModel).then(res => {
							if (res.data.code === 0) {
								this.libraryList.forEach(item => {
									if (this.formUpdateModel.idPortrait === item.idPortrait) {
										let infoObj = getIdentityIdInfo(this.formUpdateModel
											.idCard)
										item.name = this.formUpdateModel.name
										item.idCard = this.formUpdateModel.idCard
										if (infoObj) {
											item.age = infoObj.age
											item.birthDate = infoObj.birthday
											item.sex = infoObj.general
										}
									}
								})
								this.$message.success("修改成功")
								this.updateDialog = false
							} else {
								console.log(res)
							}
						})

					} else {
						console.log('error submit!!');
						return false;
					}
				})
			},
			// 取消编辑
			cancelClick() {
				this.$refs.formUpdateRef.resetFields()
				this.updateDialog = false
			},
			// 删除
			delPicClick(row, $event) {
				this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(() => { // Promise 来处理后续响应
					this.$http.delete(`/Resources/deletePortrait/${row.idPortrait}`).then(res => {
						if (res.data.code === 0) {
							this.pageObj.note = {
								...this.pageObj.note,
								...this.formModel
							}
							if (this.pageObj.note.name != "") {
								this.pageObj.pageNo = 1
							} else if (this.pageObj.note.age != "") {
								this.pageObj.pageNo = 1
							}
							if (this.libraryList.length === 1 && this.pageObj.pageNo > 1) {
								this.pageObj.pageNo = this.pageObj.pageNo - 1
							}
							this.commonSeach(this.pageObj)
							this.$message.success("删除成功")
						} else {
							console.log(res)
						}
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			// 跳转检索页面
			toRetrieval(row) {
				this.$router.push({
					name: 'monitoring-retrieval',
					params: {
						imageUrl: row.url,
					}
				})
			},
			// 编辑人脸库
			addOrUpdateClick(type) {
				this.$nextTick(() => {
					this.$refs.addOrUpdateRef.init(type, JSON.stringify(this.libraryModel))
				})
			},
			// 编辑人脸库回调
			refreshClick(type) {
				let row = type[1]
				this.libraryModel.factoryName = row.factoryName;
				this.libraryModel.remarks = row.remarks;
				this.commonSeach()
			},
			// 批量删除
			batchDelClick() {
				this.selectState = true
			},
			// 复选图片change事件
			checkboxChange(row) {
				console.log(row.selectState)
			},
			// 确认批量删除
			confirmBatchDelClick() {
				// 将选中对象的id加到idArr
				this.libraryList.forEach(item => {
					if (item.selectState) {
						this.idArr.push(item.idPortrait)
					} else {
						if (this.idArr.indexOf(item.idPortrait) != -1) {
							this.idArr.splice(this.idArr.indexOf(item.idPortrait), 1)
						}
					}
				})
				if (this.idArr.length > 0) {
					this.$http.post("/Resources/deletePortraits", {
						"idPortrait": this.idArr
					}).then(res => {
						if (res.data.code == 0) {
							this.idArr = []
							this.pageObj.note = {
								...this.pageObj.note,
								...this.formModel
							}
							if (this.pageObj.note.name != "") {
								this.pageObj.pageNo = 1
							} else if (this.pageObj.note.age != "") {
								this.pageObj.pageNo = 1
							}
							// 防止删除后删除框任然存在 重点关注这个知识点
							this.libraryList = []
							this.commonSeach()
							this.$message.success("批量删除成功")
						} else {
							console.log(res)
						}
					})
				} else {
					this.$message.info("请选择要删除的图片")
				}
			},
			// 取消批量删除
			cancelBatchDelClick() {
				this.idArr = []
				this.selectState = false
				this.libraryList.forEach(item => {
					item.selectState = false
				})
			},
			// 公共查询
			commonSeach(pageObj = this.pageObj) {
				this.$http.post("/Resources/queryPortrait", pageObj).then(res => {
					if (res.data.code === 0) {
						this.libraryList = res.data.data.records
						this.libraryList.forEach(item => {
							item.btnState = false
						})
						this.total = Number(res.data.data.total)
					} else {
						console.log(res)
					}
				})
			}
		}
	}
</script>

<style scoped>
	i {
		font-style: normal;
		font-family: "Noto Sans SC";
		color: #333
	}

	.font-fourteen {
		font-size: 14px;
		font-weight: 400;
	}

	.font-eighteen {
		font-size: 18px;
		font-weight: bold;
	}

	.font-sexteen {
		font-size: 16px;
		font-weight: bold;
	}

	.cursor-class {
		cursor: pointer;
	}

	.conditions-div {
		background-color: #FFF;
		border-radius: 2px;
	}

	.conditions-div>>>.el-form-item {
		margin: 10px;
	}

	.library-div {
		width: 24%;
		background-color: #FFF;
		float: left;
		margin: 5px 0.5%;
		padding: 10px;
		display: flex;
		box-shadow: 0px 0px 5px 0px rgba(19, 22, 30, 0.1);
		border-radius: 2px;
		height: 140px;
	}

	.library-text {
		width: 72%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		margin-left: 3%;
	}

	.library-btn {
		display: flex;
		justify-content: space-between;
	}

	.del-class {
		margin-left: 10px;
	}

	.edit-class:hover {
		color: green
	}

	.del-class:hover {
		color: red
	}

	.library-btn-class {
		position: relative;
		height: 120px;
		width: 120px;
		text-align: center;
		background-color: #F1F6F9;
	}

	.search-btn {
		background: #000000;
		line-height: 2;
		width: 100%;
		color: #FFF;
		text-align: center;
		position: absolute;
		opacity: 0.5;
		bottom: 0px;
	}
</style>
