import { pinia } from "@/pinia"
import { getOpenIdApi, getBalanceApi, qyLogin, getBalanceByQyUserid } from "@/common/apis/shop"


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);
  // 企业id
  const corpid = ref<string>("");
  // 是否企业微信登录
  const corpidLogin = ref<boolean>(false);
  // 是否是柜子管理员
  const isCabinetAdmin = ref<boolean>(false);

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

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

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

  const handleWxCallback = async (params: { corpid?: string; code?: string; state?: string; }) => {
    console.log('handleWxCallback:', params)
    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;
          }
        }

        if (openid.value) {
          // 获取用户余额
          let balanceRes = null;

          if(corpid.value) {
            balanceRes = await getBalanceByQyUserid(corpid.value, userid.value); 
          } else {
            balanceRes = await getBalanceApi(openid.value)
          }
          console.log('获取余额成功:', balanceRes)
          if (balanceRes && balanceRes.code == 0) {
            balance.value = balanceRes.data.balance
            if (!userid.value) {
              userid.value = balanceRes.data.userid;
            }
            if (!corpid.value) {
              corpid.value = balanceRes.data.corpid;
            }
          }
        }
      } catch (err) {
        console.error('获取 openid 失败:', err)
      }
      
    }
  }

  return { code, state, openid, corpid, userid, balance, isCabinetAdmin, corpidLogin, 
    setOpenid, setBalance, handleWxCallback, setIsCabinetAdmin }
})

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