import { defineStore } from 'pinia'
import {
  getToken,
  getUserInfoData,
  setUserInfoData,
  removeUserInfoData,
  getSig,
  setSig,
  removeSig,
  getFontSize,
  setFontSize,
  removeFontSize
} from '@/utils/storage'
// #ifdef APP-PLUS
import { useLoginState } from '@/uni_modules/tuikit-atomic-x/state/LoginState'
// #endif
// #ifdef H5
import { useLoginState } from 'tuikit-atomicx-vue3'
// #endif
import { useTokenStore } from './token'
import { getUserData, userLogout, updateUserData } from '@/api'
import { ref } from 'vue'
import { useUI } from '@/utils/use-ui'
import { reLaunch } from '@/utils/router'
import { getTencentUserSig } from '@/api'
import { TUILogin } from '@tencentcloud/tui-core-lite'
import { TUIChatEngine } from '@tencentcloud/chat-uikit-engine-lite'
import { getUserIntegral } from '@/api/my-index'

export const useUserStore = defineStore('user', () => {
  const { clearToken } = useTokenStore()
  const { showDialog, showToast } = useUI()

  const userInfo = ref(
    getUserInfoData() ? JSON?.parse(getUserInfoData()) : {}
  )
  /** 用户字体大小 */
  const fontSizeData = ref(getFontSize())

  /** 腾讯 IM 存储数据 */
  const tencentUserSig = ref(getSig() ? JSON?.parse(getSig()) : {})

  /** 用户积分数 */
  const integralData = ref(0)

  /**
   * 获取用户信息（可从缓存或接口）
   */
  const fetchUserInfo = async () => {
    // 尝试从本地缓存读取
    const cachedToken = getToken()
    const cachedUserInfo = getUserInfoData()
    const cachedSig = getSig()

    if (cachedToken && cachedUserInfo) {
      userInfo.value = JSON.parse(cachedUserInfo)
      tencentUserSig.value = JSON.parse(cachedSig)
      loginTencentIM()
      return
    }
    await getIntegral()
    const res = await getUserData()
    await setUserInfo(res.data)
    loginTencentIM()
    return
  }

  /**
   * 设置用户信息
   */
  const setUserInfo = async data => {
    const res = await getTencentUserSig()
    tencentUserSig.value = res.data
    userInfo.value = data
    setUserInfoData(data)
    setSig(res.data)
  }

  /** 获取用户积分 */
  const getIntegral = async () => {
    const res = await getUserIntegral()
    integralData.value = res.data.availablePoints
  }

  /**
   * 登录腾讯 IM
   */
  const loginTencentIM = async () => {
    await refreshUserInfo()
    await TUILogin.login({
      SDKAppID: tencentUserSig.value.sdkappID,
      userID: tencentUserSig.value.userId,
      userSig: tencentUserSig.value.userSig,
      framework: `vue3`
    })

    await TUIChatEngine.login({
      SDKAppID: tencentUserSig.value.sdkappID,
      userID: tencentUserSig.value.userId,
      userSig: tencentUserSig.value.userSig,
      useUploadPlugin: true // 使用文件上传插件
    })
    // #ifdef H5
    await useLoginState().login({
      SDKAppID: tencentUserSig.value.sdkappID,
      userID: tencentUserSig.value.userId,
      userSig: tencentUserSig.value.userSig
    })
    // #endif

    // #ifdef APP-PLUS
    await useLoginState().login({
      sdkappID: tencentUserSig.value.sdkappID,
      userID: tencentUserSig.value.userId,
      userSig: tencentUserSig.value.userSig
    })
    uni.$TUICallKit = uni.requireNativePlugin('TencentCloud-TUICallKit')

    console.log(uni.$TUICallKit, "TUICallKit ｜ ok"); // 本地日志 
    // try {
    //   await uni.$TUICallKit.login({
    //     SDKAppID: tencentUserSig.value.sdkappID,
    //     userID: tencentUserSig.value.userId,
    //     userSig: tencentUserSig.value.userSig
    //   })
    // } catch (err) {
    //   console.log(err, '===========2222222222')
    // }

    // #endif
  }

  /**
   * 清除用户信息（退出登录）
   */
  const clearUserInfo = async () => {
    const show = await showDialog('提示', '确定要退出登录吗？')
    if (show) {
      await logout()
    }
  }

  /**
   * 退出登录（不带提示）
   */
  const logout = async () => {
    if (!userInfo.value) return
    try {
      userInfo.value = null
      await userLogout()
      await TUILogin.logout()
      await TUIChatEngine.logout()
      // #ifdef APP-PLUS
      await useLoginState().logout()
      // #endif
      // #ifdef H5
      await useLoginState().logout()
      // #endif
      clearAllUserInfo()
      await showToast('退出登录成功', 'success')
      reLaunch('/pages/login/login')
    } catch (error) {
      clearAllUserInfo()
      await showToast('退出登录成功', 'success')
      reLaunch('/pages/login/login')
    }
  }

  /** 清空所有用户缓存 */
  const clearAllUserInfo = async () => {
    userInfo.value = null
    tencentUserSig.value = null
    fontSizeData.value = 26
    clearToken()
    removeUserInfoData()
    removeSig()
    removeFontSize()
  }

  /** 刷新用户信息（如用户信息被修改） */
  const refreshUserInfo = async () => {
    const res = await getUserData()
    await getIntegral()
    await setUserInfoData(res.data)
    userInfo.value = res.data
  }

  /**
   * 更新部分用户信息（例如昵称、头像）
   */
  const updateUserInfo = async partialData => {
    if (!userInfo.value) return
    await updateUserData(partialData)
    await refreshUserInfo()
  }

  /** 更新字体大小 */
  const updateFontSize = async fontSize => {
    fontSizeData.value = fontSize
    setFontSize(fontSize)
  }

  return {
    userInfo,
    integralData,
    tencentUserSig,
    fontSizeData,
    getIntegral,
    clearAllUserInfo,
    updateFontSize,
    logout,
    refreshUserInfo,
    fetchUserInfo,
    loginTencentIM,
    setUserInfo,
    clearUserInfo,
    updateUserInfo
  }
})
