<template>
	<view class="container">
		<view class="wapper">
			<!-- #ifdef APP -->
			<view class="backArrow">
				<text class="iconfont icon-youjiantou zuojiantou" style="left: 5rpx;" @click="goBack()"></text>
				<text style="font-size: 30rpx;">注销账号</text>
			</view>
			<!-- #endif -->
			
			<view class="wapperBox">
				<view class="warn">
					<text class="iconfont icon-redgantanhao"></text>
					<text>注销后，您将无法使用当前账号</text>
					<text>相关数据也将被删除无法找回</text>
				</view>
				<view class="cancelBox">
					<view class="title">
						注销账号
					</view>
					<view class="phone">
						{{mobile}}
					</view>
				</view>
				<view class="signatureBox">
					<view class="txt">
						<text style="font-size: 30rpx;font-weight: 500;">签字确认</text>
						<text style="font-size: 26rpx;">(请在虚线框内签字)</text>
					</view>
					<view class="signatureContent" v-show="!applyParam.personalSignOssPath">
						<e-signature 
							:showCanvas="showCanvas" 
							ref="signatureComponent" 
							@sendImage="getImage"
							@validationError="handleValidationError"
							:emptyTxt="'请先签名'"
							:validationTxt="'签名过于简单，请认真书写您的姓名'"
						></e-signature>
						<view class="clearBox">
							<view class="imgBox">
								<image src="@/static/clear.png" @click="clearImg" mode="widthFix"></image>
							</view>
						</view>
					</view>
					<image :src="applyParam.personalSignOssPath" mode="widthFix" v-if="applyParam.personalSignOssPath"></image>
				</view>
			</view>
		</view>
		<view class="btnBox">
			<view class="protol">
				<view class="empty" v-if="!isTick" @click="isTick=true"></view>
				<text v-else class="iconfont icon-icon_duihao-mian" @click="isTick=false"></text>
				<text style="color: #666;">我已阅读并同意</text>
				<text style="color: #20269B;" @click="jump()">《账号注销协议》</text>
			</view>
			<view 
				class="bottomBtn" 
				:style="{opacity:isTick?'1':'.5'}"
				@click="applyCancel()"
			>
				申请注销
			</view>
		</view>
		<everyJoinPopup 
			ref="successCancelPopup"
			content="注销成功"
			:maskClick="false"
			@continue="jumpPage"
		/>
	</view>
</template>

<script>
	import sha256 from 'js-sha256'
	import api from "@/api/api";
	import everyJoinPopup from "@/components/commonPopup/everyJoinPopup.vue";
	import eSignature from '@/components/eSignature/eSignature.vue';
	import dataHandling from "@/util/dataHandling";
	import { initJssdkShare, setWechatShare } from '@/util/fiveshare';
	export default {
		components:{eSignature,everyJoinPopup},
		data() {
			return {
				mobile:'',
				userId: uni.getStorageSync('cffp_userId'),
				showCanvas: true,
				completionSignPath: '',
				applyParam:{
					personalSignOssPath:'',
					approvalStatus:''
				},
				touchMoveHandler:null,
				isScrollLocked: false,
				isTick:false,
				signatureError: '' // 新增签名错误信息
			}
		},
		onLoad() {
			let dataForm = uni.getStorageSync('userinfodataForm')
			this.mobile = dataForm.mobile
		},
		onShow(){
			this.lockScroll()
			// #ifdef H5
						initJssdkShare(() => {
						  setWechatShare();
						}, window.location.href);
						// #endif
		},
		beforeDestroy() {
			console.log('组件销毁');
			this.releaseScroll();
		},
		onHide() {
			this.releaseScroll();
		},
		onUnload() {
			this.releaseScroll();
		},
		destroyed() {
			uni.hideToast();
		},
		methods: {
			// 处理签名验证错误
			handleValidationError(error) {
				this.signatureError = error;
				if (error) {
					uni.showToast({
						title: error,
						icon: 'none',
						duration: 2000
					});
				}
			},
			jumpPage(){
				dataHandling.pocessTracking(
				  '注销',
				  `用户注销账号`,
				  '点击',
				  2,
				  '注销账号',
				  '/myPackageA/setting/logOff'
				)
				uni.switchTab({
					url:'/pages/index/index'
				})
				this.$refs.successCancelPopup.close()
			},
			lockScroll() {
				if (this.isScrollLocked) return;
				
				// #ifdef H5
				this.touchMoveHandler = (e) => {
					const signatureArea = document.querySelector('.signatureContent');
					if (signatureArea && signatureArea.contains(e.target)) {
						e.preventDefault();
					}
				};
				
				document.body.addEventListener('touchmove', this.touchMoveHandler, { passive: false });
				// #endif
				
				// #ifdef APP-PLUS
				const pages = getCurrentPages();
				const page = pages[pages.length - 1];
				const webview = page.$getAppWebview();
				webview.setStyle({
					scrollIndicator: 'none',
					scrollsToTop: false,
					bounce: 'none'
				});
				// #endif
				
				this.isScrollLocked = true;
			},
			releaseScroll() {
				if (!this.isScrollLocked) return;
				
				// #ifdef H5
				if (this.touchMoveHandler) {
					document.body.removeEventListener('touchmove', this.touchMoveHandler);
					this.touchMoveHandler = null;
				}
				// #endif
				
				// #ifdef APP-PLUS
				const pages = getCurrentPages();
				const page = pages[pages.length - 1];
				const webview = page.$getAppWebview();
				webview.setStyle({
					scrollIndicator: 'auto',
					scrollsToTop: true,
					bounce: 'vertical'
				});
				// #endif
				
				this.isScrollLocked = false;
			},
			jump(){
				dataHandling.pocessTracking(
				  '查看',
				  `用户点击了账户注销协议`,
				  '点击',
				  2,
				  '注销账号',
				  '/myPackageA/setting/logOff'
				)
				uni.navigateTo({
					url:'/myPackageA/ruleAndContract/cancelProtocol'
				})
			},
			
			applyCancel(){
			    if(!this.isTick){
			      uni.showToast({
			        title: '请阅读并勾选《账号注销协议》',
			        duration: 3000,
			        icon: 'none'          
			      })
			      return
			    }
			    
			    // 先验证签名
			    this.$nextTick(() => {
			      const signatureValid = this.$refs.signatureComponent.validateSignature();
			      if (!signatureValid) {
			        return;
			      }
			      // return
			      // 如果验证通过，再执行完成签名
			      this.$refs.signatureComponent.finish();
			    });
			  },
			clearImg(){
				this.applyParam.personalSignOssPath = null;
				this.$refs.signatureComponent.clear();
				this.signatureError = '';
			},
			getImage(e){
				api.saveDigitalSignatures({imgStr:e}).then((res)=>{
					if(res['success']){
						this.applyParam.personalSignOssPath = res['data']['filePath'];
						const userId = uni.getStorageSync('cffp_userId')
						const timestamp = Date.now()
						const signatureSecret = "ajb_signature_secret_123!@#"
						const hasText = `${userId}|${timestamp}|${signatureSecret}`
						const hashResult = sha256(hasText);
						let params = {
							"userId":uni.getStorageSync('cffp_userId'),
							"signatureData":this.applyParam.personalSignOssPath,
							"signatureHash":hashResult,
							"timestamp":timestamp,
						}
						console.log('注销参数',params);
						api.cancellation(params).then(res =>{
							if(res['success']){
								uni.clearStorageSync();
								uni.setStorageSync('loginType','visitor');
								this.$refs.successCancelPopup.open()
							}else{
								uni.showToast({
									title: res['message'],
									icon: 'none'
								});
							}
						})
						this.releaseScroll()
					}
				})
			},
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			cancel(){
				uni.navigateBack({delta:1})
			},
			sunmit(){
				api.cancellation({userId: this.userId}).then(res =>{
					if(res['success']){
						uni.showToast({
							title: '操作成功',
							icon: 'none'
						});
						uni.clearStorageSync();
						uni.setStorageSync('loginType','visitor');
						uni.redirectTo({
							url:'/myPackageA/login/login?from=index'
						})
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container{
		display: flex;
		flex-direction: column;
		background-color: #fff;
		color: #333;
		.wapper{
			flex: 1;
			.backArrow{
				background-color: #fff;
				box-sizing: border-box;
				display: flex;
				height: 100rpx;
				justify-content: space-between;
				align-items: center;
				position: relative;
				width: 100%;
				text:nth-child(2){
					width: 100%;
					text-align: center;
					position: absolute;
				}
			}
			.wapperBox{
				margin-top: 20rpx;
				padding: 20rpx;
				.warn{
					display: flex;
					align-items: center;
					justify-content: center;
					width: 100%;
					box-sizing: border-box;
					flex-direction: column;
					font-size: 26rpx;
					
					.icon-redgantanhao{
						color: #F43530;
						font-size: 50rpx;
						margin-bottom: 20rpx;
					}
				}
				.cancelBox{
					margin: 20rpx 0;
					border-radius: 10rpx;
					padding: 30rpx;
					background-color: #FAFAFA;
					.title{
						font-size: 30rpx;
						font-weight: 500;
					}
					.phone{
						text-align: center;
						color: #20269B;
						font-size: 40rpx;
					}
				}
				.signatureBox{
					border-radius: 10rpx;
					padding: 30rpx;
					background-color: #FAFAFA;
					.txt{
						margin-bottom: 20rpx;
					}
					.signatureContent{
						margin-top: 20rpx;
						height: auto;
						position: relative;
						touch-action: none;
						.clearBox{
							display: flex;
							align-items: center;
							justify-content: center;
							.imgBox{
								display: flex;
								align-items: center;
								width: 120rpx;
								height: 120rpx;
							}
						}
					}
				}
			}
		}
		.btnBox{
			margin-bottom: 20rpx;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			.protol{
				display: flex;
				align-items: center;
				.empty{
					width: 30rpx;
					height: 30rpx;
					border: 1rpx solid #20269B;
					border-radius: 50%;
					margin-right: 5rpx;
				}
				.icon-icon_duihao-mian{
					font-size: 30rpx;
					color: #20269B;
					margin-right: 5rpx;
				}
			}
			.bottomBtn{
				margin-top: 20rpx;
				width: 65%;
				padding: 20rpx;
				color: #fff;
				border-radius: 40rpx;
				font-size: 28rpx;
				text-align: center;
				background-color: #20269B;
			}
		}
	}
</style>