<template>
	<div v-loading="loading">
		<el-form label-width="180px" style="border: 1px solid #e9e9e9; border-radius: 5px;">
			<el-row style="padding: 20px;margin:10px ;">
				<el-col :span="16">
					协同扫码
				</el-col>
			</el-row>
			<el-row style="padding: 20px;margin:10px ;">
				<el-col :span="16" v-if="userinfo.length==1">
					<el-form-item v-if="userinfo[0].xtsign_userid != '' && userinfo[0].xtsign_userid !=null "
						label="已绑定的协同签名用户">
						<el-icon color="#409EFC">
							<Iphone />
						</el-icon> <span style="font-weight: 700;color: #333;"> {{userinfo[0].xtsign_username}}</span>

					</el-form-item>
					<el-button style="margin-left: 40px;" :icon="Iphone" type="primary" @click="Scan()"><span
							v-if="userinfo[0].xtsign_userid == '' || userinfo[0].xtsign_userid ==null">手机协同签名绑定</span><span
							v-else>更换协同签名绑定</span></el-button>
				</el-col>
			</el-row>
		</el-form>
		<el-form label-width="120px" style="border: 1px solid #e9e9e9; border-radius: 5px;margin-top: 8px;">
			<el-row style="padding: 20px;margin:10px ;">
				<el-col :span="16">
					Ukey绑定
				</el-col>
			</el-row>
			<el-row style="padding: 20px;margin:10px ;">
				<el-col :span="16" v-if="userinfo.length==1">
					<el-form-item v-if="userinfo[0].ukey_sfuid != '' && userinfo[0].ukey_sfuid !=null " label="Ukey状态">
						<el-icon color="#409EFC">
							<Iphone />
						</el-icon> <span style="font-weight: 700;color: #333;">已绑定Ukey</span>
					</el-form-item>
					<el-button style="margin-left: 40px;" :icon="Iphone" type="primary" @click="Ukeybind()"><span
							v-if="userinfo[0].ukey_sfuid == '' || userinfo[0].ukey_sfuid ==null">Ukey绑定</span><span
							v-else>更换Ukey</span></el-button>
				</el-col>
			</el-row>
			<el-row v-if="ukey_show">
				<el-form-item label="选择证书">
					<el-select v-model="selectedZhengShuId" placeholder="请选择证书">
						<el-option v-for="(item,index) in ZhengShuList" :key="index" :label="item.name"
							:value="item.value" />
					</el-select>
					<el-button type="primary" size="large" @click="Ukeybind_submit">绑定</el-button>
				</el-form-item>

			</el-row>
		</el-form>
		<el-form label-width="120px" style="border: 1px solid #e9e9e9; border-radius: 5px;margin-top: 8px;">
			<el-row style="padding: 20px;margin:10px ;">
				<el-col :span="16">
					修改密码
				</el-col>
			</el-row>
			<el-row style="padding: 20px;margin:10px ;">
				<el-col :span="16">
					<el-form-item label="旧密码">
						<el-input size="large" v-model="oldpwd" type="password" placeholder="新密码"
							style="  margin: auto 20px;" />
					</el-form-item>
					<el-form-item label="新密码">
						<el-input size="large" v-model="newpwd" type="password" placeholder="新密码"
							style="  margin: auto 20px;" />
					</el-form-item>
					<el-form-item label="再次输入">
						<el-input size="large" v-model="renewpwd" type="password" placeholder="再次输入"
							style="  margin: auto 20px;" />
					</el-form-item>
				</el-col>
				<el-col :span="8" style="display:flex;align-items:center;"><el-button type="primary" size="large"
						@click="SetPwd">修 改</el-button></el-col>
			</el-row>

		</el-form>
		<el-dialog v-model="dialogVisible" title="绑定协同签名" width="40%">
			<el-form status-icon class="demo-ruleForm erweima">
				<el-form-item>
					<span style="font-size: 22px;">请使用app扫描二维码绑定</span>
				</el-form-item>
				<div class="erweima_tu" v-loading="erweima_loading">
					<canvas v-if="seconds>0" id="canvas" width="300" height="300"
						style="min-height: 300px;min-width: 300px;"></canvas>
					<div v-else class="timeout" @click="refresh()">{{erweimaErrMsg}}
						<div>
							<RefreshRight style="height: 60px;width: 60px;"></RefreshRight>
						</div>
					</div>
				</div>
				<div style="height: 160px;"></div>
			</el-form>

		</el-dialog>
	</div>
</template>

<script setup>
	import QRCode from 'qrcode'
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Iphone
	} from '@element-plus/icons-vue'
	import {
		adminChangePwd,
		addSignJob,
		XTSignCheckNotify,
		XTSignBindUser,
		GetBaseAdminUserInfo,
		UkeyBindUser
	} from '@/api/api.js'
	let loading = ref(false)
	//获取当前登录用户基本信息
	let userinfo = ref([]);
	const getUserBaseInfo = () => {
		GetBaseAdminUserInfo().then(res => {
			if (res.status == 'ok') {
				userinfo.value = res.info
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	getUserBaseInfo() //获取当前登录用户基本信息
	let oldpwd = ref('')
	let newpwd = ref('')
	let renewpwd = ref('')
	const SetPwd = () => {
		if (newpwd.value == renewpwd.value && renewpwd.value != '') {
			adminChangePwd({
				oldpwd: oldpwd.value,
				newpwd: newpwd.value
			}).then(res => {
				if (res.status == 'ok') {

					ElMessageBox.alert('密码修改成功,请重新登录', '提示', {
						// if you want to disable its autofocus
						// autofocus: false,
						confirmButtonText: 'OK',
						callback: () => {
							window.location.href = "./#/login"
						},
					})
				} else {
					ElMessage.error(res.msg)
				}
			})
		} else {
			ElMessage.error("两次密码不一致，请重新输入！")
		}
	}
	let dialogVisible = ref(false)
	const Scan = () => {
		dialogVisible.value = true
		usePhone()
	}

	const erweima_loading = ref(false)
	const UseErweima = ref(false) //是否使用二维码
	const refresh = () => {
		usePhone()
	}
	let erweimaErrMsg = ref('扫描超时，点击刷新');
	let signJobId = ref(''); ////签名任务id
	let qrcode = ref('');
	//扫码二维码
	const usePhone = () => {
		clearInterval(timer);
		signJobId.value = ''
		qrcode.value = ''
		seconds.value = timelength

		erweima_loading.value = true
		UseErweima.value = true
		addSignJob({}).then(res => {

			if (res.status) {
				qrcode.value = JSON.stringify(JSON.parse(res.data.qrCode));
				signJobId.value = res.data.signDataId;
				console.log(qrcode.value)
				var canvas = document.getElementById("canvas");
				// 调用函数去生成二维码，参数依次为：二维码的容器、要生成的内容、回调函数    
				QRCode.toCanvas(canvas, qrcode.value, function(error) {
					if (error) {
						console.error(error);
					} else {
						erweima_loading.value = false
						start_time()
						console.log("success!");
					}
				})

			} else {
				ElMessage.error(res.msg)

			}
		})
	}
	//定时60秒倒计时
	let timelength = 60
	let seconds = ref(0);
	seconds.value = timelength
	let pinlv = 2 //频率/秒
	let timer
	const start_time = () => {
		timer = setInterval(CheckNotify, pinlv * 1000);
	}
	//const saoma_status=ref(false) //扫码状态
	//检查扫码回调结果
	const CheckNotify = () => {
		if (seconds.value <= 0) {
			console.log("倒计时结束！");
			clearInterval(timer);
		} else {
			console.log(seconds.value + "秒");
			XTSignCheckNotify({
				signJobId: signJobId.value,
				notifyType: 'bind'
			}).then(res => {
				if (res.msg != '暂未回调') {
					//如果查到了，则结束定时器
					clearInterval(timer);
					if (res.status) {
						dialogVisible.value = false
						ElMessageBox.prompt('扫码成功，请输入登录密码，验证绑定', '提示', {
								confirmButtonText: '确定',
								cancelButtonText: '取消',
								inputType: 'password'
							})
							.then(({
								value
							}) => {
								console.log(value)
								XTbind(value)
							})
							.catch(() => {

							})

					} else {
						ElMessage.error(res.msg)
						erweimaErrMsg.value = res.msg
						seconds.value = 0
					}
				}

			})
			seconds.value = seconds.value - pinlv;
		}

	}
	//用户绑定协同userid
	const XTbind = (pwd) => {
		XTSignBindUser({
			signJobId: signJobId.value,
			pwd: pwd
		}).then(res => {
			if (res.status) {
				ElMessageBox.alert('绑定成功', '提示', {
					// if you want to disable its autofocus
					// autofocus: false,
					confirmButtonText: 'OK',
					callback: () => {
						getUserBaseInfo()
					},
				})
			} else {
				ElMessage.error(res.msg)
			}
		})
	}

	//Ukey绑定---------------------------------------------------------------------------------------------
	let ukey_show=ref(false);
	let ZhengShuList = ref('');
	let selectedZhengShuId = ref(''); //选中的id
	let ZhengShuSfid = ref('');
	const Ukeybind = () => {
		ukey_show.value=true
		console.log('获取证书版本号 SOF_GetVersion', xtxsync.SOF_GetVersion()) //获取证书版本号
		let list = xtxsync.SOF_GetUserList()
		console.log('证书列表 SOF_GetVersion', list) //获取证书列表
		const arr = list.split('&&&').slice(0, -1);

		ZhengShuList.value = arr.map(item => {
			const [name, value] = item.split('||');
			return {
				name,
				value
			};
		});
	}
	const Ukeybind_submit = () => {
		console.log(selectedZhengShuId.value);
		//导出证书
		var zhengshu = xtxsync.GetSignCert(selectedZhengShuId.value);
		//获取证书唯一实体标识
		ZhengShuSfid.value = xtxsync.GetCertEntity(zhengshu)
		if (ZhengShuSfid.value.length > 1) {
			ElMessageBox.prompt('请输入登录密码，验证绑定', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					inputType: 'password'
				})
				.then(({
					value
				}) => {
					console.log(value)
					UkeyBindUser({
						sfid: ZhengShuSfid.value,
						pwd: value
					}).then(res => {
						if (res.status) {
							ElMessageBox.alert('绑定成功', '提示', { 
								confirmButtonText: 'OK',
								callback: () => {
									ukey_show.value=false
									getUserBaseInfo()
								},
							})
						} else {
							ElMessage.error(res.msg)
						}
					})
				})
				.catch(() => {

				})
		}

	}
</script>

<style scoped>
	.erweima_tu {

		height: 310px;

		margin-left: auto;
		margin-right: auto;
		margin-bottom: 20px;
		text-align: center;
		color: coral;
	}

	.timeout {
		margin-top: 20%;
		text-align: center;
		color: coral;
		cursor: pointer;
	}

	.saoma_tishi {
		color: #7cba74;
		padding-top: 20%;
		font-size: 20px;
	}
</style>