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, goWechatAuth } 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()
          goWechatAuth(data, url)
        }
      } catch {
        //
      }
    }

    // 确认授权
    const onAuth = async () => {
      try {
        await request.post(state.platformApi + '/open/user/updateOpenId', {
          data: {
            clientType: state.platformType,
            code: forms.code,
            phone: forms.phone
          }
        })
        if (state.platformType === 'STUDENT') {
          window.location.href =
            'https://mp.weixin.qq.com/s?__biz=MzkxMDMwOTI5Nw==&mid=2247485362&idx=3&sn=9b265d36b5dabe7f9393fc679c367540&chksm=c12c256cf65bac7ae2a865435b950f6e1285afd226356db0ffde815b1ee345f29cfcdb798cc9#rd'
        } else if (state.platformType === 'TEACHER') {
          window.location.href =
            'https://mp.weixin.qq.com/s?__biz=MzkxMDMwOTI5Nw==&mid=2247485362&idx=2&sn=e3eaa3b85315535fcf4fd344c0a9b548&chksm=c12c256cf65bac7a898b0bce0d59f02ff924b6a0eabd9ba3fa67a87a0bdb98b916c328fe43f0#rd'
        } else if (state.platformType === 'SCHOOL') {
          window.location.href =
            'https://mp.weixin.qq.com/s?__biz=MzkxMDMwOTI5Nw==&mid=2247485362&idx=1&sn=b9081f35ec8a09897a6a14c2ff617b35&chksm=c12c256cf65bac7ae7ad2627454d296870483070b861729a40c2b9deda54b097e75be206b49f#rd'
        }
      } catch {
        //
      }
    }

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

      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>
    )
  }
})
