import { useEffect, useState } from "react";
import { View,Image } from "@tarojs/components";
import Taro, { useDidShow, useReady } from "@tarojs/taro";
import NavBarNormal from "@/components/NavBarNormal/index";
import LogoImage from '@/images/logo.png'
import PageCustom from "@/components/page-custom/index";
import { UserInfoResponse } from '@/xiaolanbenlib/api/auth'
import { onLogout, useIsLogin } from '@/xiaolanbenlib/hooks/data/useAuth'
import refreshUserId, { clearUserInfo, getOpenIdAsync } from '@/xiaolanbenlib/utils/auth'

import WelcomeTips from '../WelcomeTips/index'
import { useAgentStore } from '@/store/agentStore'
import { useSystemStore } from '@/store/systemStore'
import { TAgent } from "@/types/agent";
import { useUserStore } from "@/store/userStore";
interface IProps {
  // setDefault: (agent: TAgent) => void
}
export default function Index({}: IProps) {

  const [userInfo, setUserInfo] = useState<UserInfoResponse>()
  const isLogin = useIsLogin()

  const {fetchAgents} =  useAgentStore()
  const { fetchSysCoreCnf } =  useSystemStore()
  const { fetchtMyInfo } = useUserStore()

  async function initUserInfo() {
    await refreshUserId()
      .then( async (value) => {
        setUserInfo(value)
        getOpenIdAsync().then((openId) => {
          console.log('🚀 ~ getOpenIdAsync ~ value:', openId)
        })
      })
      .catch((error) => {
        if (error.message === 'unauthorized' || error.code === 401) {
          Taro.showToast({
            title: '未登录',
            icon: 'none',
            duration: 2000,
          })
        }
      })
    await fetchSysCoreCnf()
    await fetchtMyInfo()
    
    // 获取智能体
    await fetchAgents()
  }

  useEffect(() => {
    if (isLogin) {
      initUserInfo()
    }
  }, [isLogin])
  

  const renderLogo = ()=> {
    return <View><Image className="w-68 h-24" src={LogoImage}></Image></View>
  }

  return (
    <PageCustom>
      <NavBarNormal leftColumn={renderLogo}></NavBarNormal>
      <View className="relative w-full">
        <WelcomeTips></WelcomeTips>
      </View>
      </PageCustom>
  );
}
