import config from '@/config.json'

function loadWXSDK() {
  return new Promise((resolve, reject) => {
    if (window.WxLogin) {
      resolve()
      return
    }
    const script = document.createElement('script')
    script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
    script.onload = resolve
    script.onerror = () => reject(new Error('微信SDK加载失败'))
    document.head.appendChild(script)
  })
}

// 生成 UUID (简单实现)
function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

export async function initWechatLogin(containerId = 'wechat-login-container') {
  await loadWXSDK()

  const stateUUID = generateUUID()
  // 将 state 存入 localStorage 用于防范 CSRF
  localStorage.setItem('wx_state', stateUUID)

  // 动态获取当前的完整基础 URL 作为重定向地址（包括端口号），这样无论本地用什么端口，都能精准跳回来
  const WXLOGIN_APPID = config.wxAppId
  const WXLOGIN_REDIRECT_URI = config.wxRedirectUri

  try {
    const customCss = '.impowerBox .title { opacity: 0 !important; margin-top:20px !important;}.impowerBox .info { margin-bottom:20px !important;} .impowerBox .qrcode { width: 250px !important; height: 250px !important; margin: 0 auto !important; } .impowerBox .qrcode img { width: 250px !important; height: 250px !important; }';

    new window.WxLogin({
      self_redirect: true, // 本地调试时改为 true，让 iframe 自己跳转，避免跨域阻止
      id: containerId,
      appid: WXLOGIN_APPID,
      scope: 'snsapi_login',
      redirect_uri: encodeURIComponent(WXLOGIN_REDIRECT_URI),
      state: stateUUID,
      style: 'black',
      href: 'data:text/css;base64,' + btoa(customCss)
    })
  } catch (err) {
    console.error('初始化微信登录失败:', err)
  }
}

export async function handleWxLoginCallback() {
  const urlParams = new URLSearchParams(window.location.search)
  const code = urlParams.get('code')
  const state = urlParams.get('state')

  if (code && state) {
    const savedState = localStorage.getItem('wx_state')
    if (savedState !== state) {
      console.warn('微信登录 state 校验失败，可能存在跨站请求伪造 (CSRF) 攻击风险。')
      return false
    }

    try {
      const authService = (await import('@/api/authService')).default
      const res = await authService.loginByWxCode(code)
      if (res && res.code === 0 && res.data && res.data.token) {
        localStorage.setItem('token', res.data.token)
        // 清理 URL 参数
        const url = new URL(window.location.href)
        url.search = ''
        window.history.replaceState({}, document.title, url.toString())
        return true
      }
    } catch (err) {
      console.error('微信扫码登录失败:', err)
    }
  }
  return false
}
