<script setup lang="ts">
import Layout from "@/layout/index.vue"
import { useUserStore } from "@/pinia/stores/user"
import { useDark } from "@@/composables/useDark"
import { useWxStore } from "@/pinia/stores/wx"
import { tokenLogin } from '@/common/apis/ab98'
import { useAb98UserStore } from '@/pinia/stores/ab98-user'
import { useProductStore } from "./pinia/stores/product"
import { getCorpidByIdApi } from "./common/apis/qy"

// const userStore = useUserStore()
const wxStore = useWxStore();
const route = useRoute();
const router = useRouter();
const ab98UserStore = useAb98UserStore();
const productStore = useProductStore();

const { isDark, initDark } = useDark()

const isLoading = false;
// const isLoading = computed(() => userStore.token && !userStore.username)

// watch(
//   () => userStore.token,
//   (newVal) => {
//     newVal && userStore.getInfo()
//   },
//   {
//     immediate: true
//   }
// )

initDark()
onMounted(async () => {
  const urlParams = new URLSearchParams(window.location.search);
  console.log('urlParams', urlParams);
  const code = urlParams.get('code') || undefined;
  const state = urlParams.get('state') || undefined;
  let corpid = urlParams.get('corpid') || undefined;
  const cid = urlParams.get('cid') || undefined;
  let isAdmin = urlParams.get('isAdmin') || undefined;
  // 模拟管理员
  // isAdmin = '1';

  if (cid && Number(cid)) {
    try {
      const corpidRes = await getCorpidByIdApi(Number(cid));
      if (corpidRes?.code === 0 && corpidRes.data) {
        corpid = corpidRes.data;
        wxStore.setCorpid(corpid);
      }
    } catch (error) {
      console.log('getCorpidByIdApi error', error);
    }
  }

  if (state && state.indexOf('token') !== -1) {
    const token = state.split('token_')[1];
    if (token) {
      ab98UserStore.setTokenLogin(token);

      watch(
        () => wxStore.userid,
        (newVal) => {
          const isLogin = ab98UserStore.isLogin;
          if (newVal) {
            tokenLogin(ab98UserStore.tokenLogin, newVal, wxStore.openid).then(res => {
              if (res?.code === 0 && res.data?.success) {
                ab98UserStore.setTel(res.data.tel)
                ab98UserStore.setUserInfo(res.data)
                if (!isLogin) {
                  ab98UserStore.setIsLogin(true)
                  router.push('/')
                }
              }
            })
          }
        },
        { immediate: true }
      )
    }
  }

  if (isAdmin == '1') {
    wxStore.setIsCabinetAdmin(true);
  }
  if (code || state) {
    wxStore.handleWxCallback({ corpid, code, state })
  }
})
</script>

<template>
  <van-config-provider :theme="isDark ? 'dark' : 'light'" un-h-full>
    <van-loading v-if="isLoading" un-h-full un-flex-center>
      加载中...
    </van-loading>
    <Layout v-else />
  </van-config-provider>
</template>
