<!--设置页-->
<template>
	<view class="assemble">
		<view style="height: 30rpx;"></view>
		<view class="option" @click="update_pass()">修改密码</view>
		<view class="option" @click="buildwx()"> 绑定微信</view>
		<view class="option" @click="privacy_agreement(1)">用户协议</view>
		<view class="option" @click="privacy_agreement(2)">隐私策略</view>
		<view class="option" @click="clearCache()">清空缓存</view>
		
		<view style="width:90%;margin: 60rpx auto;">
			<fui-button background="#29d3b4" @click="loginOut()">退出账号</fui-button>
		</view>
	</view>
</template>

<script>
import {Api_url} from '@/common/config.js'
import apiRoute from '@/api/apiRoute.js'
	export default {
		data() {
			return {
				
			}
		},
		methods: {
      //退出登陆
      loginOut(){
        this.$util.loginOut()
      },

			privacy_agreement(type){
				uni.navigateTo({
					url: '/pages-common/privacy_agreement?type='+type
				})
			},
			update_pass(){
				uni.navigateTo({
					url: '/pages-market/my/update_pass'
				})
			},
			
			// 清空缓存
			clearCache() {
				uni.showModal({
					title: '清空缓存',
					content: '确定要清空所有字典缓存吗？',
					success: (res) => {
						if (res.confirm) {
							this.performClearCache();
						}
					}
				});
			},
			
			// 执行清空缓存操作
			performClearCache() {
				try {
					// 获取本地存储的所有键
					const storageInfo = uni.getStorageInfoSync();
					const keys = storageInfo.keys;
					
					// 筛选出dict_开头的键并删除
					let clearCount = 0;
					keys.forEach(key => {
						if (key.startsWith('dict_')) {
							uni.removeStorageSync(key);
							clearCount++;
						}
					});
					
					// 显示清理结果
					uni.showToast({
						title: `已清空${clearCount}个字典缓存`,
						icon: 'success',
						duration: 2000
					});
					
					console.log(`清空缓存完成，共清理${clearCount}个dict_开头的缓存项`);
				} catch (error) {
					console.error('清空缓存失败：', error);
					uni.showToast({
						title: '清空缓存失败',
						icon: 'none',
						duration: 2000
					});
				}
			},
      //绑定微信
      async buildwx(){
        try {
          console.log('开始微信绑定流程')
          
          // 检查当前环境
          // #ifdef MP-WEIXIN
          console.log('微信小程序环境')
          await this.bindWeixinInMiniProgram()
          // #endif
          
          // #ifdef H5
          console.log('H5环境')
          if (this.isWeixinBrowser()) {
            console.log('微信浏览器环境')
            await this.bindWeixinInH5()
          } else {
            console.log('非微信浏览器环境')
            uni.showModal({
              title: '提示',
              content: '请在微信中打开此页面进行微信绑定',
              showCancel: false,
              confirmText: '我知道了'
            })
            return
          }
          // #endif
          
          // #ifndef MP-WEIXIN || H5
          // 其他环境
          uni.showToast({
            title: '当前环境不支持微信绑定',
            icon: 'none'
          })
          // #endif
          
        } catch (error) {
          console.error('绑定微信失败：', error)
          uni.hideLoading()
          uni.showToast({
            title: '绑定失败，请重试',
            icon: 'none'
          })
        }
      },
      
      // 小程序环境绑定流程 - 先绑定小程序openid，然后跳转webview绑定公众号
      async bindWeixinInMiniProgram() {
        uni.showLoading({
          title: '正在获取微信信息...'
        })
        
        // 1. 先获取小程序 openid
        console.log('步骤1: 获取小程序openid')
        const miniProgramOpenid = await this.getMiniProgramOpenid()
        console.log('获取到的openid:', miniProgramOpenid)
        
        if (!miniProgramOpenid) {
          uni.hideLoading()
          uni.showToast({
            title: '获取小程序openid失败',
            icon: 'none'
          })
          return
        }
        
        // 2. 绑定小程序openid
        console.log('步骤2: 绑定小程序openid')
        const bindResult = await this.bindMiniProgramOpenid(miniProgramOpenid)
        console.log('绑定结果:', bindResult)
        
        if (!bindResult) {
          uni.hideLoading()
          return
        }
        
        uni.hideLoading()
        
        // 3. 跳转webview绑定公众号openid
        console.log('步骤3: 跳转webview绑定公众号')
        const webviewUrl = this.buildWebviewUrl(miniProgramOpenid)
        console.log('webview URL:', webviewUrl)
        
        uni.navigateTo({
          url: `/pages-common/webview/wechat_bind?url=${encodeURIComponent(webviewUrl)}`
        })
      },
      
      // H5微信浏览器环境绑定流程
      async bindWeixinInH5() {
        uni.showLoading({
          title: '正在跳转微信授权...'
        })
        
        try {
          // H5环境直接跳转到公众号授权
          const baseUrl = Api_url
          const redirectUri = encodeURIComponent(`${baseUrl}/api/personnel/wechatCallback`)
          const state = encodeURIComponent(JSON.stringify({
            personnel_id: this.$store.state.userInfo.id,
            from: 'h5',
            timestamp: Date.now()
          }))
          
          const authUrl = `${baseUrl}/api/personnel/wechatAuthorize?redirect_uri=${redirectUri}&state=${state}`
          console.log('H5授权URL:', authUrl)
          
          uni.hideLoading()
          
          // 直接跳转到授权页面
          location.href = authUrl
          
        } catch (error) {
          console.error('H5微信绑定失败:', error)
          uni.hideLoading()
          uni.showToast({
            title: '授权跳转失败',
            icon: 'none'
          })
        }
      },
      
      // 获取小程序openid
      getMiniProgramOpenid() {
        return new Promise((resolve, reject) => {
          console.log('开始获取小程序openid')
          
          // #ifdef MP-WEIXIN
          console.log('在微信小程序环境中')
          uni.login({
            provider: 'weixin',
            success: (loginResult) => {
              console.log('微信登录成功，code:', loginResult.code)
              if (loginResult.code) {
                // 调用后端接口换取openid
                apiRoute.getWechatOpenid({
                  code: loginResult.code,
                  type: 'miniprogram'
                }).then(res => {
                  console.log('获取openid接口响应:', res)
                  if (res.code === 1) {
                    resolve(res.data.openid)
                  } else {
                    uni.showToast({
                      title: res.msg || '获取openid失败',
                      icon: 'none'
                    })
                    resolve(null)
                  }
                }).catch(error => {
                  console.error('获取openid接口调用失败：', error)
                  resolve(null)
                })
              } else {
                uni.showToast({
                  title: '微信登录失败',
                  icon: 'none'
                })
                resolve(null)
              }
            },
            fail: (error) => {
              console.error('微信登录失败：', error)
              uni.showToast({
                title: '微信登录失败',
                icon: 'none'
              })
              resolve(null)
            }
          })
          // #endif
          
          // #ifndef MP-WEIXIN
          console.log('非微信小程序环境，启用测试模式')
          
          // 开发阶段测试：使用模拟的code调用API接口
          uni.showModal({
            title: '测试模式',
            content: '当前非小程序环境，是否使用测试code调试接口？',
            success: (res) => {
              if (res.confirm) {
                console.log('用户选择测试模式')
                // 使用测试code调用接口
                apiRoute.getWechatOpenid({
                  code: 'test_code_' + Date.now(),
                  type: 'miniprogram'
                }).then(res => {
                  console.log('测试模式接口响应:', res)
                  if (res.code === 1) {
                    resolve(res.data.openid)
                  } else {
                    console.log('API返回错误:', res.msg)
                    uni.showToast({
                      title: '测试模式：' + (res.msg || '获取openid失败'),
                      icon: 'none',
                      duration: 3000
                    })
                    // 即使失败也返回一个测试openid用于调试流程
                    resolve('test_openid_' + Date.now())
                  }
                }).catch(error => {
                  console.error('测试模式接口调用失败：', error)
                  // 返回测试openid用于调试流程
                  resolve('test_openid_' + Date.now())
                })
              } else {
                console.log('用户取消测试')
                resolve(null)
              }
            }
          })
          // #endif
        })
      },
      
      // 绑定小程序openid
      bindMiniProgramOpenid(openid) {
        return new Promise((resolve) => {
          apiRoute.bindWechatOpenid({
            miniprogram_openid: openid,
            type: 'miniprogram'
          }).then(res => {
            if (res.code === 1) {
              uni.showToast({
                title: '小程序绑定成功',
                icon: 'success'
              })
              resolve(true)
            } else {
              uni.showToast({
                title: res.msg || '小程序绑定失败',
                icon: 'none'
              })
              resolve(false)
            }
          }).catch(error => {
            console.error('绑定小程序openid失败：', error)
            uni.showToast({
              title: '绑定失败，请重试',
              icon: 'none'
            })
            resolve(false)
          })
        })
      },
      
      // 构建webview URL
      buildWebviewUrl(miniOpenid) {
        const baseUrl = Api_url
        const redirectUri = encodeURIComponent(`${baseUrl}/api/personnel/wechatCallback`)
        const state = encodeURIComponent(JSON.stringify({
          mini_openid: miniOpenid,
          personnel_id: this.$store.state.userInfo.id,
          from: 'miniprogram',
          timestamp: Date.now()
        }))
        
        return `${baseUrl}/api/personnel/wechatAuthorize?redirect_uri=${redirectUri}&state=${state}`
      },
      
      // 检测是否为微信环境
      isWeixinBrowser() {
        const ua = navigator.userAgent.toLowerCase()
        return ua.includes('micromessenger')
      }
		}
	}
</script>

<style lang="less" scoped>
	.assemble{
		width: 100%;
		height: 100vh;
		background: #333333; 
	}
	.option{
		margin-bottom: 20rpx;
		background: #404045;
		width: 100%;
		font-size: 28rpx;
		color: #fff;
		line-height: 56rpx;
		padding: 20rpx 0 20rpx 100rpx;
	}
</style>
