
import { defineStore } from "pinia";
import { ref } from "vue";
import { store } from "@/store";
import { QyUserLoginDTO } from "@/api/common/login";
import { QyAuthCorpBasicInfoDTO } from "@/api/qy/corp";


export const useWxStore = defineStore("wx", () => {
  // 授权企业id
  const corpid = ref<string>("wpZ1ZrEgAA2QTxIRcB4cMtY7hQbTcPAw")
  // 微信授权 code
  const code = ref<string>("")
  // 防止 CSRF 攻击的 state 参数
  const state = ref<string>("")
  // 用户 userid
  const userid = ref<string>("")
  // 初始化
  const isInit = ref<boolean>(false);
  const qyUser = ref<QyUserLoginDTO>(null);
  // 企业授权基本信息
  const authCorpBasicInfo = ref<QyAuthCorpBasicInfoDTO>(null);

  // 设置 userid
  const setUserid = (id: string) => {
    userid.value = id
  }

  const setQyUser = (user: QyUserLoginDTO) => {
    if (!user) return;
    qyUser.value = user;
  }

  // 设置企业授权基本信息
  const setAuthCorpBasicInfo = (info: QyAuthCorpBasicInfoDTO) => {
    if (!info) return;
    authCorpBasicInfo.value = info;
  }

  const initWx = () => {
    if (isInit.value) return;
    isInit.value = true;
  }

  const handleWxCallback = async (params: { corpid: string; code: string; state: string }) => {
    console.log('handleWxCallback:', params)
    if (params.code && params.corpid) {
      corpid.value = params.corpid;
      code.value = params.code;
      state.value = params.state || state.value;

      // try {
      //   // 调用获取 userid 的接口
      //   const res = await getQyUserinfo({
      //     corpid: params.corpid,
      //     code: params.code
      //   })
      //   console.log('获取 userid 成功:', res)
      //   if (res && res.code == 0) {
      //     userid.value = res.data
      //   }
      // } catch (err) {
      //   console.error('获取 userid 失败:', err)
      // }
    }
  }

  return {
    corpid, code, state, userid, isInit, qyUser, authCorpBasicInfo,
    setUserid, handleWxCallback, initWx, setQyUser, setAuthCorpBasicInfo
  }
})

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