import { useEffect, useState } from 'react'
import * as Api from "../api/access"
import { useSearchParams } from 'react-router-dom';
import { useAuthStore } from '../store/AuthStore';
import wx from 'weixin-js-sdk'

function Home() {
  const [tips, setTips] = useState("登陆中，请稍后")
  let [urlParams] = useSearchParams();
  const authStore = useAuthStore()

  const navigateAccessPage = async () => {
    try {
      const res = await Api.getAccessPage()
      if (res.code !== 200) {
        throw new Error(res.message);
      }

      window.location.href = res.data.url

    } catch (e: any) {
      setTips("获取活动页失败")
      console.error(e.message);
    }
  }

  const recordState = async () => {
    try {
      const code = urlParams.get('code') || "null"
      const state = urlParams.get('state') || "err"
      const customer_id = authStore.tid || 0
      const customer_openid = authStore.clientOpenid || "null"
      const res = await Api.recordState({
        code: code,
        state: state,
        customer_id: customer_id,
        customer_openid: customer_openid,
      })
      if (res.code !== 200) {
        throw new Error(res.message);
      }
    } catch (e: any) {
      console.error(e.message);
    }
  }

  const navigateActivityPage = async (customer_id: number) => {
    try {
      const res = await Api.getActivityPage(customer_id)
      if (res.code !== 200) {
        throw new Error(res.message);
      }

      const activityCode = authStore.activityCode
      const userId = authStore.userId
      const corpId = authStore.corpId
      authStore.clear()

      let url = ""
      if (activityCode != "") {
        url = res.data.url + `?activityCode=${activityCode}&userId=${userId}&corpId=${corpId}`
      } else {
        url = res.data.url
      }

      if (res.data.type == "h5") {
        window.location.href = url
      } else {
        wx.miniProgram.navigateTo({
          url: url
        })
      }
    } catch (e: any) {
      console.error(e.message);
    }
  }

  const bindIds = async (code:string) => {
    try {
      //检查是否有tid和openid
      const tid = authStore.tid
      const openid = authStore.clientOpenid
      const phone = authStore.phone
      const sign = authStore.sign
      const activityCode = authStore.activityCode || ""
      const userId = authStore.userId || ""
      const corpId = authStore.corpId || ""
      const timestamp = authStore.timeStamp || ""

      if (tid && openid && sign || tid && phone && sign) {
        authStore.setCode(code)
        const res = await Api.bindIds({
          code: code,
          client_openid: openid,
          phone: phone,
          client_sign: sign,
          customer_id: tid,
          activity_id: 1,
          activity_code: activityCode,
          user_id: userId,
          corp_id: corpId,
          timestamp: timestamp,
        })
        if (res.code !== 200) {
          throw new Error(res.message);
        }
        navigateActivityPage(tid)
      } else {
        setTips("授权参数失效，请再次尝试")
      }
    } catch (e: any) {
      console.error(e.message);
      setTips("授权失败")
    }
  }

  useEffect(() => {
    const tid = parseInt(urlParams.get('tid') || "0")
    const openid = urlParams.get('openid') || urlParams.get('openId')
    const phone = urlParams.get('phone')
    const sign = urlParams.get('sign')
    //裂变专用参数
    const activityCode = urlParams.get('activityCode') || ""
    const userId = urlParams.get('userId') || ""
    const corpId = urlParams.get('corpId') || ""
    const timestamp = urlParams.get('timestamp') || ""

    authStore.setActivityCode(activityCode)
    authStore.setUserId(userId)
    authStore.setCorpId(corpId)
    authStore.setTimeStamp(timestamp)

    if (tid && openid && sign) {
      //初次登陆或者重新登陆
      authStore.setTid(tid)
      authStore.setClientOpenId(openid)
      authStore.setSign(sign)
      navigateAccessPage()
    } else if (tid && phone && sign) {
      //绑定手机号
      authStore.setTid(tid)
      authStore.setPhone(phone)
      authStore.setSign(sign)
      navigateAccessPage()
    } else {
      //微信跳回
      const code = urlParams.get('code')
      if (code) {
        bindIds(code)
      } else {
        recordState()
        setTips("授权参数不完整")
      }
    }
  }, [])

  return (
    <>
      <div>{tips}</div>
    </>
  )
}

export default Home
