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("获取活动页失败")
      recordError(e.message)
      // 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 recordError = async (str:string) => {
    try {
      const code = "error"
      const state = str
      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) {
        recordError(res.message)
        throw new Error(res.message);
      }

      const activityCode = authStore.activityCode
      const userId = authStore.userId
      const corpId = authStore.corpId
      const tradeNo = authStore.tradeNo
      const redirectUrl = authStore.redirect_url
      // const code = authStore.code
      authStore.clear()

      let url = ""
      if(redirectUrl != ""){
        url = redirectUrl
      }else if (activityCode != "") {
        url = res.data.url + `?activityCode=${activityCode}&userId=${userId}&corpId=${corpId}`
      } else if(tradeNo != ""){
        url = res.data.url + `?code=${urlParams.get('code')}`
      }else {
        url = res.data.url
      }

      if (res.data.type == "h5") {
        window.location.href = url
      } else {
        wx.miniProgram.navigateTo({
          url: url
        })
      }
    } catch (e: any) {
      recordError(e.message)
      // 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) {
      recordError(e.message)
      // console.error(e.message);
      setTips("授权失败")
    }
  }

  const parseRedirectUrl = (redirect_url:string) => {
    if(redirect_url=="")return ""
    const urlDecode = decodeURIComponent(redirect_url)
    const urlJson = JSON.parse(urlDecode)
    const paramJson = JSON.parse(urlJson.params)
    let redirectUrl = urlJson.path
    if(paramJson.length > 0){
      redirectUrl+="?"
      for (let i=0;i<paramJson.length;i++) {
        if(i != 0){
          redirectUrl += "&"
        }
        redirectUrl += `${paramJson[i]}`
      }
    }
    console.log(redirectUrl)
    return redirectUrl
  }

  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 redirect_url = urlParams.get('redirect_url') || ""
    //裂变专用参数
    const activityCode = urlParams.get('activityCode') || ""
    const userId = urlParams.get('userId') || ""
    const corpId = urlParams.get('corpId') || ""
    const timestamp = urlParams.get('timestamp') || ""
    const tradeNo = urlParams.get('tradeNo') || ""

    if(activityCode!="")authStore.setActivityCode(activityCode)
    if(userId!="")authStore.setUserId(userId)
    if(corpId!="")authStore.setCorpId(corpId)
    if(timestamp!="")authStore.setTimeStamp(timestamp)
    if(redirect_url!="")authStore.setRedirectUrl(parseRedirectUrl(redirect_url))    

    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 if(tid && tradeNo){
      authStore.setTid(tid)
      authStore.setTradeNo(tradeNo)
      console.log("tid: ",authStore.tid)
      navigateAccessPage()
    } else {
      //微信跳回
      const code = urlParams.get('code')
      // const redirectUrl = urlParams.get('redirect_url')
      console.log("tid: ",authStore.tid)
      const tid = authStore.tid
      const tids = [783, 795, 788, 790, 797, 798, 799, 10081, 10084, 10088, 10090, 10092, 10096, 10097, 10099, 10100, 10101];
      if (code) {
        // if(tid == 783 || tid == 788 || tid == 790 || tid == 797 || tid == 10081 || tid == 10084 || tid == 10088 || tid == 10090 || tid == 10092 || tid == 10096 || tid == 10099){
        if(tids.some(v => v == tid)){
          const tid = authStore.tid
          authStore.setCode(code)
          navigateActivityPage(tid)
        }else{
          bindIds(code)
        }
      } else {
        recordState()
        recordError("没有获取到code")
        setTips("授权参数不完整")
      }
    }
  }, [])

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

export default Home
