<!-- component标签可以变换组件 -->
<template>
	<view>
		<view v-if="errorMsg" style="color: red;padding-left: 13px;">{{errorMsg}}</view>
		<iframe id="jingeIframe" style="width: 100%;height: 600px;border: none;" ref="iframe" title="金格云阅读"
			src="./static/CloudSign/viewer.html" :transmissionData="transmissionData"
			:change:transmissionData="renderjs.postMessageToIframe" @load="setConfig"></iframe>
		<wd-toast></wd-toast>
	</view>
</template>
<script>
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 } from 'wot-design-uni'

export default {
  name: 'SinopecEsignPageAPP',
  options: {
    styleIsolation: 'shared',
  },
  props: {
    fileName: {
      type: String,
      default: ""
    },
    valiData: {
      type: Object
    },
	procInsId: { //签章验证
		type: String,
		default: ""
	},
	path: {//签章验证
		type: String,
		default: ""
	},
	taskDefKey: { //流程节点
		type: String,
		default: ""
	}
  },
  emits: ['message'],
  setup(props, { emit }) {
    const toast = useToast()
    const store = useUserStore();
    const iframe = ref(null);
    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 transmissionData = ref({});
	const errorMsg = ref('');

    const setConfig = () => {
      transmissionData.value = {
        filename: props.fileName,
        apiUrl: baseUrl,
        userid: username.value,
      }
	  console.log(transmissionData.value)
    }

	const signValidator = async () => { //签章验证 by 闵
		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 = []
					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;
						}
					})
					filterArrNum.value = filterArr.length;
					if (props.valiData.num <= filterArrNum.value) {
						return true;
					} else {
						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;
			if(props.taskDefKey=='task1715564108096'){ //如果是综合办审核，不需要该区
				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;
	}

    const stampingCompleted = (data) => {
	  console.log(JSON.stringify(data))
      let sealArray = data.data.sealArray;
      sealArrayTemp.value = sealArray;
      console.log(sealArrayTemp.value);
      
      let sealNumMap = {}
      sealArray.forEach(item => {
        if (sealNumMap[item.keySN]) {
          sealNumMap[item.keySN] += 1;
          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----", data)
      if (data.type === 'successMessage') {
        console.log("ev------------", ev)
        sign.value = true;
        console.log("改变状态后-------this.sign-----", sign.value)
        let wjurl = ev.currentTarget[0].data.filename;
        if (wjurl.split('/')[0].includes("非常规盖章")) {
          let wjdata = ev.currentTarget[0].data;
          emit('message', wjdata);
        }
      } else if (data.type === 'sealArray') {
        sign.value = false;
        console.log("删除盖章后的参数--this.sign--", sign.value)
      }
    }

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

    onLoad(() => {
      let userInfo = store.userInfo;
      ldhth.value = userInfo.workNo;
      checkSign(ldhth.value).then((res) => {
        if (res) {
          username.value = res
        } else {
          toast.error("您没有申请电子签章服务！请移步到系统管理-电子签章管理中注册，并联系信息化支持中心进行otp绑定。联系电话：4874260")
        }
      })
    })

	// defineExpose({ //暴露方法
	//   signValidator
	// })

    return {
      iframe,
      compName,
      asyncComponent,
      sealArrayTemp,
      signNum,
      sign,
      ldhth,
      username,
      iframeWin,
      baseUrl,
      filterArrNum,
      transmissionData,
      signValidator,
      stampingCompleted,
	  errorMsg
    }
  }
}
</script>

<script module="renderjs" lang="renderjs">
	export default {
		mounted() {
			this.setupMessageListener()
		},
		methods: {
			postMessageToIframe(data) {
				console.log(data)
				const iframe = document.getElementById('jingeIframe')
				if (iframe && iframe.contentWindow) {
					iframe.contentWindow.postMessage(data, '*')
				}
			},
			setupMessageListener() {
				let that = this;
				window.addEventListener('message', (ev,ev2) => {
					console.log(ev.data)
					if (ev) {
						try {
							that.$ownerInstance.callMethod('stampingCompleted', ev.data)
						} catch (error) {
							console.error('Call method error:', error)
						}
					}
				})
			}
		}
	}
</script>


<style scoped>
</style>