<!-- component标签可以变换组件 -->
<template>
	<view>
		<view v-if="errorMsg" style="color: red;padding-left: 13px;">{{errorMsg}}</view>
		<iframe id="jingeIframe" class="App-iframe" width="100%" ref="iframe" title="金格云阅读"
			src="./static/CloudSign/viewer.html" @load="setConfig"></iframe>
		<wd-toast></wd-toast>
	</view>
</template>
<script setup lang="ts">
	import {
		getCompleteNum
	} from '@/api/bpm/sign'
	import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue';
	import {
		onLoad,
		onShow,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import {
		useUserStore
	} from '@/store/user'
	import { checkSign } from '@/api/bpm/sign'
	import { useToast, useMessage, useNotify, dayjs } from 'wot-design-uni'
	const emit = defineEmits(['message'])
	const iframe = ref(null); //ref
	const toast = useToast()
	const store = useUserStore();
	const compName = ref('');
	const asyncComponent = ref(null);
	const sealArrayTemp = ref([]); //签章数据
	const signNum = ref(0);
	const sign = ref(false);
	const ldhth = ref('');
	const username = ref('');
	const iframeWin = ref(null);
	const baseUrl = import.meta.env.VITE_SERVER_BASEURL
	const filterArrNum = ref(0); //过滤后的数据
	const errorMsg = ref('');

	defineOptions({
		name: 'SinopecEsignPage',
		options: {
			styleIsolation: 'shared',
		},
	})
	const props = defineProps({
		fileName: {
			type: String,
			default: ""
		},
		valiData: {
			type: Object
		},
		procInsId: { //签章验证
			type: String,
			default: ""
		},
		path: {//签章验证
			type: String,
			default: ""
		},
		taskDefKey: { //流程节点
			type: String,
			default: ""
		}
	})

	onShow(() => {
		setTimeout(()=>{
			setConfig()
		},500)
	})



	const setConfig = () => {
		// //给html传值
		iframeWin.value = iframe.value.contentWindow
		console.log(iframe.value)
		console.log(iframe.value.contentWindow)
		try {
			iframeWin.value.postMessage({
				filename: props.fileName,
				apiUrl: baseUrl,
				userid: username.value,
			}, '*')
		} catch (error) {
			console.error('PostMessage error:', error);
			// 可以在这里添加备用通信方式
		}
	}

	const signValidator = async () => { //签章验证 by 闵
		
		console.log(props.path)
		errorMsg.value = '';
		let flag = false;
		if (props.path == 'unconventional/stamp') { //非常规验证
			if (props.valiData.flag) { //先判断数量验证
				if (props.valiData && props.valiData.flag) {//有flag需要正常验证
					let nowTime = new Date(props.valiData.time).getTime();
					let filterArr = []
					console.log(sealArrayTemp.value)
					filterArr = sealArrayTemp.value.filter(item => {
						let sealTime = new Date(item.createTime).getTime();
						if (sealTime >= nowTime && item.userName == props.valiData.name) {
							return true;
						} else {
							return false;
						}
					})
					console.log(filterArr)
					filterArrNum.value = filterArr.length;
					if (props.valiData.num <= filterArrNum.value) {
						return true;
					} else {
						console.log(324325)
						errorMsg.value = "您需要签章(签字或盖章)" + props.valiData.num + "次，目前只签章了" + filterArrNum.value + "次。";
						return false;
					}
				}
			}
			//2024.3.22张祥瑞
			//如果签章路径是非常规盖章则走这里，验证机制为跳过签章个数验证，只要没签章则不能提交流程
			// let flag = false;
			if (sign.value) {
				return flag = true; //只要执行了签章成功操作就返回成功，否则加载个数验证
			} else {
				return flag = false;
			}
		} else if (props.path == 'officialReceptions/index') { //判断公务接待模块
			//2024.5.16张祥瑞
			//如果签章路径是非常规盖章则走这里，验证机制为跳过签章个数验证，只要没签章则不能提交流程
			// let flag = false;
			console.log(2222)
			if(props.taskDefKey=='task1715564108096'){ //如果是综合办审核，不需要该区
				return flag = true; //只要执行了签章成功操作就返回成功，否则加载个数验证
			}
			return flag = true; //只要执行了签章成功操作就返回成功，否则加载个数验证
			if (sign.value) {
				return flag = true; //只要执行了签章成功操作就返回成功，否则加载个数验证
			} else {
				return flag = false;
			}
		} else {
			if (sign.value) {
				return true; //只要执行了签章成功操作就返回成功，否则加载个数验证
			} else {
				// let flag = false;
				await getCompleteNum(props.procInsId).then(res => {
					console.log("res--------132------", res);
					// console.log("flag--132------",flag);
					if (res) {
						if (signNum.value >= (Number(res.result.nrOfCompletedInstances) + 1)) {
							flag = true;
						}
					}
				})
			}
		}
		console.log("flag--142------", flag);
		return flag;
	}


	onLoad(() => {
		//获取当前登录人所属部门
		//这里是要去esign表中使用劳动合同号查询当前使用人的userid
		let userInfo = store.userInfo;
		ldhth.value = userInfo.workNo;
		checkSign(ldhth.value).then((res) => {
			if (res) {
				username.value = res
			} else {
				toast.error("您没有申请电子签章服务！请移步到系统管理-电子签章管理中注册，并联系信息化支持中心进行otp绑定。联系电话：4874260")
			}
		})
	})

	onMounted(() => {

		//接收html盖完章后传过来的值
		window.addEventListener("message", (ev) => {
			console.log(ev)
			//1.获取签章信息
			let sealArray = ev.data.data.sealArray;
			sealArrayTemp.value = sealArray;
			console.log(sealArrayTemp.value);
			//2.循环数组，转换为正确个数（以keySn为比对核心，相同的keySn为个数1）
			let sealNumMap = {}
			sealArray.forEach(item => {
				if (sealNumMap[item.keySN]) {
					sealNumMap[item.keySN] += 1;
					//个数为2为一组
					if (sealNumMap[item.keySN] > 2) {
						let remainder = Math.ceil(sealNumMap[item.keySN] / 2) - 1
						sealNumMap[item.keySN + remainder] = sealNumMap[item.keySN] - remainder * 2;
					}
				} else {
					sealNumMap[item.keySN] = 1;
				}
			})
			signNum.value = Object.keys(sealNumMap).length;
			console.log(sealNumMap)
			console.log("ev.data----", ev.data)
			if (ev.data.type === 'successMessage') {
				console.log("ev------------", ev)
				sign.value = true;
				console.log("改变状态后-------this.sign-----", sign.value)
				let wjurl = ev.currentTarget[0].data.filename;
				//切割盖章文件，用来判断是否是非常规盖章--张祥瑞2024.1.11
				// let wjurl1=wjurl.split('/');
				if (wjurl.split('/')[0].includes("非常规盖章")) {
					let wjdata = ev.currentTarget[0].data;
					emit('message', wjdata);
				}
			} else if (ev.data.type === 'sealArray') { //添加删除盖章后签章，改为false  --张祥瑞 2024.3.22
				sign.value = false;
				console.log("删除盖章后的参数--this.sign--", sign.value)
			}

		})

	})
	
	defineExpose({ //暴露方法
	  signValidator
	})
</script>

<style scoped>
	.App-iframe {
		width: 100%;
		height: 700px;
		border: none;
	}
</style>