<template>
	<div class="video">
		<template v-if="!viewState">
			<el-button type="primary" @click="addClick()">新增视频比对</el-button>
			<el-table :data="tableData">
				<el-table-column>
					<template slot-scope="scope">
						<video :src="scope.row.viedourl" style="width:18%"></video>
					</template>
				</el-table-column>
				<el-table-column prop="taskName" label="视频名称">
				</el-table-column>
				<el-table-column prop="tasklibstr" label="人像库">
				</el-table-column>
				<el-table-column prop="taskstatus" label="任务状态">
				</el-table-column>
				<el-table-column prop="" label="操作" fixed="right" width="150">
					<template slot-scope="scope">
						<el-button type="primary" plain size="mini" @click="viewClick(scope.row.taskNo,scope.row.viedourl)" v-if="scope.row.taskstatus == '任务已经结束'">查看</el-button>
						<el-button type="info" plain disabled size="mini" v-else>查看</el-button>
						<el-button type="primary" plain size="mini" @click="deleteClick(scope.row.idControlTask)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination @size-change="handleSizeChange1" @current-change="handleCurrentChange1" :current-page="pageObj1.pageNo"
			 :page-sizes="[10, 20, 30, 40]" :page-size="pageObj.pageSize" layout="total, sizes, prev, pager, next, jumper"
			 :total="total1">
			</el-pagination>
			<!-- 新增视频对比 -->
			<el-dialog :visible.sync="visibleDialog" center :close-on-click-modal="false">
				<span slot="title"><i class="font-sexteen">新增视频比对</i></span>
				<el-form :model="formModel" :rules="formRules" ref="formRef" label-width="auto">
					<el-form-item prop="videoName" label="视频">
						<el-button type="primary" @click="uploadVideo()">点击选择</el-button><span>{{formModel.videoName}}</span>
					</el-form-item>
					<el-form-item label="选择人像库" prop="librarys">
						<el-select v-model="formModel.librarys" clearable placeholder="人像库类型" multiple>
							<el-option v-for="item in libraryOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="threshold" label="比对阈值">
						<el-slider v-model="formModel.threshold" show-input :step="10">
						</el-slider>
					</el-form-item>
				</el-form>
				<span slot="footer">
					<el-button type="primary" @click="confirmClick()" :disabled="!videoCompareBtn">确认</el-button>
					<el-button @click="cancelClick()">取消</el-button>
				</span>
			</el-dialog>
			<videoUpload ref="uploadRef" @refreshDataList="refreshDataList(arguments)"></videoUpload>
		</template>
		<template v-else>
			<div style="display: flex;justify-content: space-between;">
				<span class="el-icon-arrow-left cursor-class" @click="viewState=false"><i class="font-fourteen">返回</i></span>
				<el-button type="primary" @click="exportPDF()">导出</el-button>
			</div>
			<p><i class="font-eighteen">比对结果</i></p>

			<el-row :gutter="20">
				<el-col :span="3">
					<video :src="videoUrl" controls style="width: 100%;"></video>
				</el-col>
				<el-col :span="21" id="htm2Id">
					<el-row :gutter="20">
						<el-col v-for="(item,index) in warningList" :key="index" :span="8">
							<div class="pic-div" @click="openTask(item)">
								<div class="pic-class">
									<div style="width: 120px;height:120px">
										<canvas width=120 height=120 style="margin-left: 5px;" :ref="'warningImage'+index">
										</canvas>
									</div>
									<div style="width: 120px;height:120px">
										<img :src="item.faceUrl" alt="目标图片" height="100%">
									</div>
								</div>
								<div class="pic-text">
									<span><i>姓名：{{item.name}}</i></span>
									<span><i>性别：{{item.sex}}</i></span>
									<span><i>来源：{{item.libName}}</i></span>
									<span><i>相似度：</i><i class="threshold-class">{{(item.score*100).toFixed(2)}}%</i></span>
								</div>
							</div>
						</el-col>
					</el-row>

					<div style="clear:both"></div>
					<div>
						<el-pagination @current-change="handleCurrentChange" :current-page.sync="pageObj.page.pageNo" :page-size="pageObj.page.pageSize"
						 layout="total,prev, pager, next, jumper" :total="total">
						</el-pagination>
					</div>
				</el-col>
			</el-row>
			<!-- 对比结果详情 -->
			<el-dialog :visible.sync="taskVisible" :close-on-click-modal="false">
				<span slot="title" class="task-title">
					布控任务名称
				</span>
				<div>
					<el-row :gutter="20">
						<el-col :span="16">
							<div>
								<el-image style="width: 100%;" :src="val.bgImg"></el-image>
							</div>
						</el-col>
						<el-col :span="8">
							<div class="compare-pic">
								<div style="display: flex;">
									<div style="width:120px;height:120px">
										<canvas width=120 height=120 ref="imageView">
										</canvas>
									</div>
									<div style="width:120px;height:120px;text-align: center;">
										<img :src="val.faceUrl" alt="目标图片" height="100%">
									</div>
								</div>
								<div style="line-height: 22px;">
									<div><i>姓名：{{val.name}}</i></div>
									<div><i>性别：{{val.sex}}</i></div>
									<div><i>年龄：{{val.age}}</i></div>
									<div><i>身份证号码：{{val.idCard}}</i></div>
									<div><i>来源：{{val.taskName}}</i></div>
									<div><i>相似度：<span class="threshold-class">{{(val.score*100).toFixed(2)}}%</span></span></i></div>
								</div>
							</div>
						</el-col>
					</el-row>
				</div>
			</el-dialog>
		</template>
	</div>
</template>

<script>
	import debounce from 'lodash/debounce'
	import videoUpload from "./video-upload"
	import html2 from "html2canvas";
	/* import JsPDF from 'jspdf' */
	export default {
		components: {
			videoUpload
		},
		data() {
			return {
				// 视频对比新增按钮
				videoCompareBtn: true,
				// video 和 videoView 状态
				viewState: false,
				// 库列表
				libraryOptions: [],
				// table
				tableData: [],
				total1: 0,
				pageObj1: {
					pageNo: 1,
					pageSize: 10,
					note: {}
				},
				// 新增视频对比弹框隐藏显示
				visibleDialog: false,
				// 新增视频对比的表单
				formModel: {
					videoName: "",
					librarys: [],
					threshold: 90,
					videoUrl: "",
				},
				formRules: {
					videoName: [{
						required: true,
						message: "请上传视频",
					}],
					librarys: [{
						required: true,
						message: "请选人像库",
					}],
					threshold: [{
						required: true,
						message: "请选择阀值",
					}],
				},

				// 任务列表
				warningList: [],
				pageObj: {
					"page": {
						"pageNo": 1,
						"pageSize": 24,
					},
					"taskIds": [],
					taskType: 1,
				},
				total: 0,
				// 单个详情
				taskVisible: false,
				val: {},
				// 视频是否解析完
				timer: null,
			}
		},
		methods: {
			exportPDF() {
				//需要截图的包裹的（原生的）DOM 对象
				let shareContent = document.getElementById("htm2Id") 
				let width = shareContent.clientWidth //获取dom 宽度
				let height = shareContent.clientHeight //获取dom 高度
				let canvas = document.createElement("canvas") //创建一个canvas节点
				let scale = 1; //定义任意放大倍数 支持小数
				canvas.width = width * scale; //定义canvas 宽度 * 缩放
				canvas.height = height * scale; //定义canvas高度 *缩放
				canvas.style.width = shareContent.clientWidth * scale + "px";
				canvas.style.height = shareContent.clientHeight * scale + "px";
				canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
				let opts = {
					scale: scale, // 添加的scale 参数
					canvas: canvas, //自定义 canvas
					logging: false, //日志开关，便于查看html2canvas的内部执行流程
					width: width, //dom 原始宽度
					height: height,
					useCORS: true, // 【重要】开启跨域配置
				};
				html2(shareContent, opts).then(() => {
					var contentWidth = canvas.width;
					var contentHeight = canvas.height;
					//一页pdf显示html页面生成的canvas高度;
					var pageHeight = (contentWidth / 592.28) * 841.89;
					//未生成pdf的html页面高度
					var leftHeight = contentHeight;
					//页面偏移
					var position = 0;
					//a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
					var imgWidth = 595.28;
					var imgHeight = (592.28 / contentWidth) * contentHeight;
					var pageData = canvas.toDataURL("image/jpeg", 1.0);
					var PDF = new JsPDF("", "pt", "a4");
					if (leftHeight < pageHeight) {
						PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
					} else {
						while (leftHeight > 0) {
							PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
							leftHeight -= pageHeight;
							position -= 841.89;
							if (leftHeight > 0) {
								PDF.addPage();
							}
						}
					}
					PDF.save("比对结果" + ".pdf"); // 这里是导出的文件名
				});
			},

			// el-pagination
			handleSizeChange1: function(pageSize) {
				this.pageObj1.pageSize = pageSize
				this.handleCurrentChange1(this.pageObj1.pageNo);
			},
			handleCurrentChange1: function(pageNo) {
				this.pageObj1.pageNo = pageNo
				this.commonSearch1()
			},
			// 查看
			viewClick(idControlTask, videoUrl) {
				this.videoUrl = videoUrl
				this.$http.get(`/warning/taskStatus/${idControlTask}`).then(res => {
					if (res.data.code == 0) {
						if (res.data.data.status == "STATUSOVER") {
							this.pageObj.taskIds = [idControlTask]
							this.getWarningList(this.pageObj)
						} else {
							this.$message.warning("任务进行中")
						}
					} else {
						console.log(res)
					}
				})
			},
			// 查看单个任务
			openTask(val) {
				this.val = val
				this.taskVisible = true
				this.$nextTick(() => {
					let canvas = this.$refs['imageView']
					let cxt = canvas.getContext("2d");
					let img = new Image();
					img.src = this.val.bgImg;
					img.onload = () => {
						cxt.drawImage(img, this.val.positionVO.x, this.val.positionVO.y, this.val.positionVO.w, this.val.positionVO.h,
							0, 0, 120,
							120);
					}
				})
			},
			// 删除
			deleteClick(id) {
				this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
						confirmButtonText: "确认",
						cancelButtonTExt: "取消",
						type: "warning"
					})
					.then(() => {
						this.$http.delete(`/control/deletetask/${id}`).then(res => {
							if (res.data.code === 0) {
								this.$message.success("删除成功")
								if (this.tableData.length === 1 && this.pageObj1.pageNo > 1) {
									this.pageObj1.pageNo = this.pageObj1.pageNo - 1
								}
								this.commonSearch1()
							} else {
								this.$message.warning(res.data.message)
							}
						})
					})
					.catch(err => {
						console.log(err)
					})
			},
			// 上传
			uploadVideo() {
				this.$nextTick(() => {
					this.$refs.uploadRef.init()
				})
			},
			// 上传视频回调
			refreshDataList(param, videoUrl) {
				this.formModel.videoName = param[0]
				this.formModel.videoUrl = param[1]
			},
			// 新增
			addClick() {
				this.visibleDialog = true
				this.videoCompareBtn = true
			},
			// 确认新增
			confirmClick: debounce(function() {
				this.$refs.formRef.validate((valid) => {
					if (valid) {
						this.videoCompareBtn = false
						let obj = {
							"controlThreshold": 0,
							"libIds": [],
							"taskName": "",
							"videourl": ""
						}
						obj.controlThreshold = this.formModel.threshold / 100
						obj.libIds = this.formModel.librarys
						obj.taskName = this.formModel.videoName
						obj.videourl = this.formModel.videoUrl
						this.$http.post(`/control/insertcmpviedo`, obj).then(res => {
							if (res.data.code == 0) {
								this.$refs.formRef.resetFields()
								this.$message.success("新增成功")
								this.pageObj1.pageNo = 1
								this.commonSearch1()
								this.visibleDialog = false
							} else {
								console.log(res)
							}
						})
					} else {
						console.log('error submit!!');
						return false;
					}
				})
			}),
			// 取消新增
			cancelClick() {
				this.$refs.formRef.resetFields()
				this.visibleDialog = false
			},
			// 页码
			handleCurrentChange(val) {
				this.pageObj.page.pageNo = val
				this.getWarningList(this.pageObj)
			},
			getWarningList(obj = this.pageObj) {
				this.$http.post("/warning/alarm", obj).then(res => {
					if (res.data.code === 0) {
						this.viewState = true
						let warningList = res.data.data.records
						this.warningList = warningList
						this.total = Number(res.data.data.total);
						this.warningList.forEach((item, index, arr) => {
							this.$nextTick(() => {
								let canvas = this.$refs[`warningImage${index}`][0]
								let cxt = canvas.getContext("2d");
								let img = new Image();
								img.src = item.bgImg;
								img.onload = function() {
									cxt.drawImage(img, item.positionVO.x, item.positionVO.y, item.positionVO.w, item.positionVO.h, 0, 0,
										120,
										120);
								}
							})
						})
					}
				})
			},
			// 获取库列表
			getLibrary() {
				this.$http.post("/Resources/libraryPage", {
					currentPage: 1,
					pageSize: 9999,
					note: {}
				}).then(res => {
					if (res.data.code === 0) {
						let libraryList = res.data.data.records
						libraryList.forEach(item => {
							this.libraryOptions.push({
								label: item.factoryName,
								value: item.idFactory
							})
						})
						console.log(this.libraryOptions)
					} else {
						console.log(res)
					}
				})
			},
			// 公共查询
			commonSearch1(pageObj = this.pageObj1) {
				this.$http.post("/control/tasklistvideo", pageObj).then(res => {
					if (res.data.code === 0) {
						this.tableData = res.data.data.records
						this.total1 = Number(res.data.data.total)
					} else {
						console.log(res)
					}
				})
			},
			// 定时任务
			get() {
				this.commonSearch1()
			}
		},
		created() {
			// 公共查询
			this.commonSearch1()
			// 获取库列表
			this.getLibrary()
		},
		activated() {
			this.timer = setInterval(this.get, 5000);
		},
		beforeDestroy() {
			clearInterval(this.timer)
			this.timer = null
		}
	}
</script>

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

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

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

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

	.threshold-class {
		width: 70px;
		height: 18px;
		font-size: 24px;
		font-weight: 600;
		color: #FF343E;
	}

	.cursor-class {
		cursor: pointer;
	}

	.pic-div {
		display: flex;
		background: #FFF;
		border-radius: 2px;
		cursor: pointer;
		margin-bottom: 20px;
		padding: 10px;
	}

	.pic-class {
		width: 60%;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.pic-text {
		width: 40%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 0 10px;
	}

	.right-details {
		display: flex;
		justify-content: space-between;
	}

	.right-details div {
		width: 48%;
	}

	.right-bottom-details {
		padding: 10px 0;
		display: flex;
		flex-direction: column;
	}
</style>
