import { defineComponent, onMounted, reactive } from 'vue'
import { Button, closeToast, Image, Popup } from 'vant'
import styles from './index.module.less'
import iconLogo from './images/icon-logo.png'
import iconLargeLogo from './images/icon-large-logo.png'
import { useRoute } from 'vue-router'
import qs from 'query-string'
import { browser, getUrlCode } from '@/helpers/utils'
import request from '@/helpers/request'
import dayjs from 'dayjs'
import { state } from '@/state'

export default defineComponent({
  name: 'bind-wechat',
  setup() {
    const route = useRoute()
    console.log(route.query)
    const forms = reactive({
      showPopup: false,
      code: '',
      phone: '' as any,
      time: '' as any,
      // platform: route.query.platform,
      popupMessage: '请使用微信打开'
    })
    // 浏览器自带加密方式
    // window.btoa() 加密
    // window.atob() 解密
    // console.log(qs.parse(location.hash))

    const getAppIdAndCode = async (url: string) => {
      try {
        const { data } = await request.get(state.platformApi + '/open/paramConfig/wechatAppId')
        // 判断是否有微信appId
        if (data) {
          closeToast()
          const replaceUrl =
            `https://online.lexiaoya.cn/getWxCode?appid=${data}&state=STATE&redirect_uri=` +
            encodeURIComponent(url)

          console.log(data, 'aaaa')
          console.log(replaceUrl)
          window.location.replace(replaceUrl)
          // goAuth(data, url)
        }
      } catch {
        //
      }
    }
    const goAuth = (wxAppId: string, urlString?: string) => {
      // 用户授权
      console.log(urlString || window.location.href, 'urlString || window.location.href')
      const urlNow = encodeURIComponent(urlString || window.location.href)
      console.log(urlNow, 'urlNow')
      const scope = 'snsapi_base' //snsapi_userinfo   //静默授权 用户无感知
      const appid = wxAppId || 'wx8654c671631cfade'
      const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${urlNow}&response_type=code&scope=${scope}&state=STATE&connect_redirect=1#wechat_redirect`
      window.location.replace(url)
    }

    // 确认授权
    const onAuth = async () => {
      try {
        await request.post(state.platformApi + '/open/user/updateOpenId', {
          data: {
            clientType: state.platformType,
            code: forms.code,
            phone: forms.phone
          }
        })
        window.location.href =
          'https://mp.weixin.qq.com/s?__biz=MzkxMDMwOTI5Nw==&mid=2247485261&idx=1&sn=70c79a832a609bf9fae01c9e90fb4f69&chksm=c12c2593f65bac85d26362bca470f6abc2bfc087d9f4dcf87c00094420bdf5a3acb1b870199b#rd'
      } catch {
        //
      }
    }

    onMounted(async () => {
      // console.log(dayjs(Number(data.time)).subtract(3, 'hour').valueOf())
      // 判断是否是微信，只能微信中打开

      console.log(import.meta.env)
      if (!browser().weixin) {
        forms.showPopup = true
        return
      } else {
        //授权
        const code = getUrlCode()
        if (!code) {
          const newUrl =
            window.location.origin +
            window.location.pathname +
            '#' +
            route.path +
            '?' +
            qs.stringify({
              ...route.query
            })
          await getAppIdAndCode(newUrl)
          return
        } else {
          forms.code = code
        }
      }
      // 处理链接上面的参数
      try {
        const hash = window.location.hash ? window.location.hash.split('?')[1] : ''
        const atob = window.atob(decodeURIComponent(hash))
        const params = qs.parse(atob)
        forms.phone = params.phone
        forms.time = params.time
        if (!forms.phone) {
          forms.popupMessage = '链接已失效'
          forms.showPopup = true
          return
        }
      } catch {
        //
      }

      // t: route.query.t, // 过期时间
      try {
        if (forms.time) {
          const { data } = await request.get(
            state.platformApi + '/open/paramConfig/queryByParamName',
            {
              requestType: 'form',
              params: {
                paramName: 'qr_code_expire_hours'
              }
            }
          )
          if (dayjs(Number(forms.time)).add(data.paramValue, 'hour').isBefore(dayjs())) {
            forms.popupMessage = '二维码已失效'
            forms.showPopup = true
          }
        }
      } catch {
        //
      }
    })
    return () => (
      <div class={styles.bindWeChat}>
        <Image class={styles.largeLogo} src={iconLargeLogo} />
        <Image src={iconLogo} class={styles.smallLogo} />

        <p class={styles.tips}>同意管乐团获取您的微信信息</p>
        <p class={styles.phone}>{forms.phone}</p>

        <div class={styles.btnGroup}>
          <Button type="primary" size="large" round onClick={onAuth}>
            确认授权
          </Button>
        </div>

        <Popup
          v-model:show={forms.showPopup}
          round
          style={{ width: '88%', marginTop: '-6vh' }}
          closeOnClickOverlay={false}
          class={styles.wxPopupDialog}
        >
          <div class={styles.popupContainer}>
            <p class={styles.title1}>温馨提示</p>
            <p class={styles.popupTips}>{forms.popupMessage}</p>
          </div>
        </Popup>
      </div>
    )
  }
})
