import { pinia } from "@/pinia"
import { getOpenIdApi, getBalanceApi, qyLogin, getBalanceByQyUserid, fakeQyLoginApi } from "@/common/apis/shop"
import { ab98UserDTO, GetBalanceResponse } from "@/common/apis/shop/type"
import { useAb98UserStore } from "./ab98-user"


export const useWxStore = defineStore("wx", () => {
  // 微信授权 code
  const code = ref<string>("")
  // 防止 CSRF 攻击的 state 参数
  const state = ref<string>("")
  // 用户 openid
  const openid = ref<string>("")
  // 用户 userid
  const userid = ref<string>("");
  // 剩余借呗
  const balance = ref<number>(0);
  // 已用借呗
  const useBalance = ref<number>(0);
  // 借呗总额
  const balanceLimit = ref<number>(0);
  // 企业id
  const corpid = ref<string>("");
  // 是否企业微信登录
  const corpidLogin = ref<boolean>(false);
  // 是否是柜子管理员
  const isCabinetAdmin = ref<boolean>(false);
  // 企业微信用户姓名
  const name = ref<string>("");
  // 企业微信用户id
  const qyUserId = ref<number>(0);
  // 汇邦云用户信息
  const ab98User = ref<ab98UserDTO | null>(null);

  const isFakeQyLogin = ref<boolean>(false);
  // handleWxCallback 是否完成
  const isHandleWxCallbackComplete = ref<boolean>(false);

  // 设置 openid
  const setOpenid = (id: string) => {
    openid.value = id
  }

  const setBalance = (amount: number) => {
    balance.value = amount;
  }

  const setCorpid = (id: string) => {
    corpid.value = id;
  }

  const setIsCabinetAdmin = (isAdmin: boolean) => {
    isCabinetAdmin.value = isAdmin;
  }

  const setAb98User = (user: ab98UserDTO) => {
    ab98User.value = user;
    const ab98UserStore = useAb98UserStore();
    ab98UserStore.setUserInfo({
      face_img: ab98User.value.faceImg || "",
      success: true,
      sex: ab98User.value.sex || "",
      name: ab98User.value.name || "",
      userid: ab98User.value.userid || "",
      registered: true,
      tel: ab98User.value.tel || "",
    });
  }
  
  const refreshBalance = async () => {
    if (corpid.value && userid.value) {
      const res = await getBalanceByQyUserid(corpid.value, userid.value);
      if (res && res.code == 0) {
        balance.value = res.data.balance;
        useBalance.value = res.data.useBalance;
        balanceLimit.value = res.data.balanceLimit;
        
        if (res.data.ab98User) {
          setAb98User(res.data.ab98User);
        }
      }
    }
  }

  const handleWxCallback = async (params: { corpid?: string; code?: string; state?: string; }) => {
    console.log('handleWxCallback:', params)
    isHandleWxCallbackComplete.value = false; // 开始处理，标记为未完成
    if (params.code) {
      code.value = params.code
      state.value = params.state || state.value
      corpid.value = params.corpid || corpid.value
      corpidLogin.value = !!corpid.value;
      console.log('corpid:', corpid.value)
      console.log('corpidLogin:', corpidLogin.value)
      
      try {
        if (!corpid.value) {
          // 调用获取 openid 的接口
          const res = await getOpenIdApi({ code: params.code });
          if (res && res.code == 0) {
            openid.value = res.data
          }
        } else {
          // 企业微信登录
          const res = await qyLogin({ corpid: corpid.value, code: params.code, state: params.state})
          if (res && res.code == 0) {
            userid.value = res.data.userid;
            openid.value = res.data.openid;
            isCabinetAdmin.value = res.data.isCabinetAdmin === 1;
            name.value = res.data.name;
            qyUserId.value = res.data.qyUserId;
            setAb98User(res.data.ab98User);
          }
        }

        if (openid.value) {
          // 获取用户余额
          let balanceRes: ApiResponseData<GetBalanceResponse> | null = null;

          if(corpid.value) {
            balanceRes = await getBalanceByQyUserid(corpid.value, userid.value); 
          } else {
            corpid.value = "wpZ1ZrEgAA2QTxIRcB4cMtY7hQbTcPAw";
            balanceRes = await getBalanceApi(corpid.value, openid.value)
          }
          console.log('获取余额成功:', balanceRes)
          if (balanceRes && balanceRes.code == 0) {
            balance.value = balanceRes.data.balance;
            useBalance.value = balanceRes.data.useBalance;
            balanceLimit.value = balanceRes.data.balanceLimit;
            if (!userid.value) {
              userid.value = balanceRes.data.userid;
            }
            if (!ab98User.value && balanceRes.data.ab98User) {
              setAb98User(balanceRes.data.ab98User);
            }
            /* if (!corpid.value) {
              corpid.value = balanceRes.data.corpid;
            } */
          }
        }
      } catch (err) {
        console.error('获取 openid 失败:', err)
      } finally {
        isHandleWxCallbackComplete.value = true; // 处理完成，标记为已完成
      }
      
    } else {
      isHandleWxCallbackComplete.value = true; // 没有code参数，直接标记为已完成
    }
  }

  const fakeQyLogin = async () => {
    isFakeQyLogin.value = true;
    corpid.value = "wpZ1ZrEgAA2QTxIRcB4cMtY7hQbTcPAw";
    corpidLogin.value = true;
    userid.value = "woZ1ZrEgAAV9AEdRt1MGQxSg-KDJrDlA";
    const res = await fakeQyLoginApi({ corpid: corpid.value, userid: userid.value})
    if (res && res.code == 0) {
      userid.value = res.data.userid;
      openid.value = "oMRxw6Eum0DB1IjI_pEX_yrawBHw";
      isCabinetAdmin.value = res.data.isCabinetAdmin === 1;
      name.value = res.data.name;
      qyUserId.value = res.data.qyUserId;
      setAb98User(res.data.ab98User);
    }
  }

  // 检测 handleWxCallback 是否完成的异步函数
  const waitForHandleWxCallbackComplete = async (timeout = 30000): Promise<boolean> => {
    const startTime = Date.now();
    while (!isHandleWxCallbackComplete.value) {
      if (Date.now() - startTime > timeout) {
        console.warn('等待 handleWxCallback 完成超时');
        return false;
      }
      await new Promise(resolve => setTimeout(resolve, 100)); // 每100ms检查一次
    }
    return true;
  }


  return { code, state, openid, corpid, userid, balance, useBalance, 
    balanceLimit, isCabinetAdmin, corpidLogin, name, ab98User, qyUserId, isFakeQyLogin,
    isHandleWxCallbackComplete, setOpenid, setBalance, setCorpid, handleWxCallback, setIsCabinetAdmin, 
    refreshBalance, setAb98User, fakeQyLogin, waitForHandleWxCallbackComplete }
})

/**
 * @description 用于在 setup 外使用 store
 */
export function useWxStoreOutside() {
  return useWxStore(pinia)
}