<template>
	<view class="login-container">
		<!-- 应用标题和副标题 -->
		<view class="app-header">
			<image :src="logoImage"
			mode="aspectFill"
			style="width: 170rpx; height: 170rpx; display: block; margin: 0 auto;" />
			<view class="app-title">{{ logoName }}</view>
			<!-- <view class="app-subtitle">旧物很有用·回收很简单</view> -->
		</view>

		<!-- 登录操作区域 -->
		<view class="login-actions">
			<button class="login-btn" @click="handleLogin">登录</button>
			<button class="cancel-btn" @click="handleCancel">取消登录</button>

			<view class="agreement">
				<checkbox-group @change="handleAgreementChange" class="radio-group">
					<label class="radio-label">
						<checkbox :checked="agreed" color="#fdbd3e" class="custom-radio" />
						<text class="agreement-text">我已阅读并同意</text>
						<text class="protocol-link" @click.stop="openProtocol('service')">《服务协议》</text>
						<text class="agreement-text">和</text>
						<text class="protocol-link" @click.stop="openProtocol('privacy')">《隐私政策》</text>
					</label>
				</checkbox-group>
			</view>

		</view>




		<!-- <uv-divider  :dashed = "true"></uv-divider> -->

		<!-- <view class="admin-login" @click="goToAdminLogin">管理员登录→</view> -->


		<PrivacyPopup ref="privacyPopup" :needPhone="needPhone" :appName="logoName" @agree="handleAgreePrivacy"
			@reject="handleRejectPrivacy" @open-protocol="openProtocol" />
		<ProtocolDialog ref="protocolDialog" :show="showProtocolDialog" :title="protocolDialogTitle"
			:content="protocolDialogContent" @close="showProtocolDialog = false" @agree="handleProtocolAgree"
			@reject="handleProtocolReject" />

	</view>
</template>

<script>
	import PrivacyPopup from '@/wxcomponents/privacy-popup/privacy-popup.vue'
	import ProtocolDialog from '@/wxcomponents/protocol-dialog/protocol-dialog.vue'
	// import {banner} from  '@/api.uts'
	export default {
		components: {
			PrivacyPopup,
			ProtocolDialog
		},
		data() {
			return {
				agreed: false,
				showProtocolDialog: false,
				protocolDialogTitle: '',
				protocolDialogContent: '',
				configData: [], // 存储 getConfig 返回的 result
				needPhone: false // 控制是否需要手机号授权
			}
		},
		computed: {
			logoImage() {
				const item = this.configData.find(i => i.keyName === 'logo_image')
				uni.setStorageSync('logoImage', item ? item.keyContent : '')
				return item ? item.keyContent : ''
			},
			logoName() {
				const item = this.configData.find(i => i.keyName === 'logo_name')
				uni.setStorageSync('logoName', item ? item.keyContent : '')
				return item ? item.keyContent : ''
			}
		},
		onLoad(query) {
			if (query.shareId) {
				uni.setStorageSync('shareId', query.shareId)
			}
			this.getConfigData()
		},
		methods: {
			getConfigData() {
				this.$api('getConfig', {}, res => {
					// console.log('Config data response:', JSON.parse(JSON.stringify(res)) )
					if (res && res.success && Array.isArray(res.result)) {
						this.configData = res.result
						// console.log('Config data set:',  JSON.parse(JSON.stringify(this.configData)) )
					}
				})
			},
			getConfigByKey(key) {
				const item = this.configData.find(i => i.keyName === key)
				return item ? item.keyContent : ''
			},
			handleLogin() {
				if (!this.agreed) {
					uni.showToast({
						title: '请阅读并勾选服务协议和隐私声明',
						icon: 'none'
					});
					return;
				}

				// this.$refs.privacyPopup.open()
				// uni.showLoading({
				//   title: '登录中...'
				// });
				// setTimeout(() => {
				//   uni.hideLoading();
				//   uni.showToast({
				//     title: '登录成功'
				//   });
				//   uni.reLaunch({
				//     url: '/pages/index/index'
				//   });
				// }, 1500);
				
				this.handleAgreePrivacy()
			},
			handleCancel() {
				// 关闭当前页面回到首页
				uni.reLaunch({
					url: '/pages/component/home'
				});
			},

			handleAgreementChange(e) {
				// console.log(this.agreed);
				// this.agreed = e.detail.value.length > 0;
				if (this.agreed) {
					this.agreed = false;
				} else {
					this.agreed = true;
				}
			},

			openProtocol(type) {
				console.log('Opening protocol:', type)
				console.log('Current configData:', this.configData)
				let protocol = null
				if (type === 'privacy') {
					protocol = this.configData.find(i => i.keyName === 'user_ys')
				} else if (type === 'service') {
					protocol = this.configData.find(i => i.keyName === 'user_xy')
				}
				console.log('Found protocol:', protocol)
				this.protocolDialogTitle = protocol ? protocol.keyValue : (type === 'privacy' ? '隐私政策' : '服务协议')
				this.protocolDialogContent = protocol && protocol.keyContent ? protocol.keyContent :
					(type === 'privacy' ?
						'<div style="padding: 20rpx;">暂无隐私政策内容</div>' :
						'<div style="padding: 20rpx;">暂无服务协议内容</div>')
				this.showProtocolDialog = true
				console.log('Dialog state:', {
					title: this.protocolDialogTitle,
					content: this.protocolDialogContent,
					show: this.showProtocolDialog
				})
			},

			goToAdminLogin() {
				uni.navigateTo({
					url: '/pages/component/admin_login'
				});
			},

			// 同意隐私政策
			handleAgreePrivacy() {
				uni.showLoading({
					title: '登录中...'
				})
				//       执行登录逻辑...

				let self = this
				
				let data = {
					code: res.code
				}
				
				if (uni.getStorageSync('shareId')) {
					data.shareId = uni.getStorageSync('shareId')
				}

				wx.login({
					success(res) {
						// console.log(res.code,'code')
						if (res.code) {
							self.$api('wxLogin', data, res => {
								console.log(res, 'login')
								if (res.code == 200) {
									uni.hideLoading();
									// console.log(res)
									uni.setStorageSync('token', res.result.token);
									uni.setStorageSync('userInfo', res.result.userInfo)
									uni.setStorageSync('openid', res.result.userInfo && res.result.userInfo
										.appletOpenid);
									getApp().globalData.login_status = true;
									if (res.result.userInfo) {
										const userInfo = res.result.userInfo;
										if (!userInfo.headImage || !userInfo.nickName) {
											uni.navigateTo({
												url: '/pages/wxUserInfo'
											});
										} else {
											uni.reLaunch({
												url: '/pages/component/home'
											});
										}
									} else {
										uni.navigateTo({
											url: '/pages/wxUserInfo'
										});
									}
								}
							})
						} else {
							uni.hideLoading();
							console.log('登录失败！' + res.errMsg)
						}
					}
				})
			},

			// 拒绝隐私政策
			handleRejectPrivacy() {
				uni.reLaunch({
					url: '/pages/component/home'
				});
			},

			// 打开协议页面
			openProtocolPage(type) {
				this.openProtocol(type)
			},
			handleProtocolAgree() {
				this.showProtocolDialog = false
				this.agreed = true
				// 你可以在这里添加同意后的其他逻辑
			},
			handleProtocolReject() {
				this.showProtocolDialog = false
				if (this.agreed) {
					this.agreed = false
				}
				// 你可以在这里添加拒绝后的其他逻辑
			}
		}
	}
</script>

<style scoped scss>
	view {
		padding-bottom: 0 !important;
	}

	.login-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f9ece5;
		padding: 0 40rpx;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.app-header {
		margin-top: 320rpx;
		margin-bottom: 280rpx;
		text-align: center;
	}

	.app-title {
		display: flex;
		justify-content: center;
		align-items: center;
		font-family: Alimama ShuHeiTi;
		font-weight: 700;
		font-size: 28px;
		margin-top: 20rpx;
	}

	.app-subtitle {
		font-size: 28rpx;
		color: #fef6e3;
		margin-top: 1rem;
		letter-spacing: 0.11em;
	}

	.login-actions {
		/* height: 30%; */
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #f9ece5;
		border-radius: 30rpx;
	}

	.login-btn,
	.cancel-btn {
		width: 82%;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 45rpx;
		font-size: 32rpx;
		margin-bottom: 20rpx;
		border: none;
	}

	.login-btn {
		background-color: #f79400;
		color: white;
	}

	.cancel-btn {
		background-color: rgba(255, 253, 249);
		color: #f7990c;
		background-color: #f9ece5;
		border: 1px solid rgba(249, 178, 71);
	}

	.agreement {
		/* margin-top: 40rpx; */
		font-size: 24rpx;
		color: #333;
		display: flex;
		justify-content: center;

	}

	.radio-group {
		display: flex;
		align-items: center;
	}

	/* 自定义圆形checkbox样式 */
	.custom-radio {
		/* border-radius: 50%; */
		width: 32rpx;
		height: 32rpx;
		transform: scale(0.7);
		margin-right: 8rpx;
	}

	/* 覆盖uniapp默认checkbox样式 */
	.custom-radio .wx-checkbox-input,
	.custom-radio .uni-checkbox-input {
		border-radius: 50% !important;
		width: 32rpx !important;
		height: 32rpx !important;
	}

	.custom-radio .wx-checkbox-input.wx-checkbox-input-checked,
	.custom-radio .uni-checkbox-input.uni-checkbox-input-checked {
		background-color: #07C160 !important;
		border-color: #07C160 !important;
		color: #ffffff !important;
	}

	/* .radio-label {
  display: flex;
  align-items: center;
} */



	.agreement-text {
		margin: 0 4rpx;
	}

	.protocol-link {
		color: #fabe65;
	}

	.admin-login {
		text-align: center;
		color: #fffffe;
		font-size: 28rpx;
		letter-spacing: 0.15em;
	}
</style>