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'
import * as CallLib from '@/uni_modules/RongCloud-CallWrapper/lib/index'
import RCIMIWEngine from '@/uni_modules/RongCloud-IMWrapper-V2/js_sdk/RCIMEngine'
import { reasonDeal, errorDeal, imCode } from '@/utils/code.js'
// #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'
import { removeFriendList, removeGroupList } from '../utils/storage'
import { getRongYunLoginInfo } from '../api'

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)
  /** 融云 IM 引擎 */
  const imEngine = ref(null)

  /**
   * 获取用户信息（可从缓存或接口）
   */
  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()
    const ryData = await getRongYunLoginInfo()
    const IM_DATA = {
      ...res.data,
      ...ryData.data
    }
    tencentUserSig.value = IM_DATA
    userInfo.value = data
    setUserInfoData(data)
    setSig(IM_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
    })
    console.log(tencentUserSig.value.appKey, '====')
    await connectIM()
    // #endif
	// #ifdef APP-PLUS
	// CallLib.init({})
	CallLib.onCallReceived(res => {
	    console.log(
	      'Engine:OnCallReceived=>' + '监听通话呼入, 目标id=>',
	      res.data
	    )
		console.log('res: ',res.data);
	    if (res.data.targetId) {
			// let url = res.data.mediaType == 0 ? "" : "/pages/room/room"
			uni.setStorageSync('room-parameters', {
				callType: 'in',
				mediaType: res.data.mediaType === 0 ? 'audio' : 'video'
			});
	      uni.navigateTo("/pages/room/incom", {
	        type: res.data.extra,
	  		callType: 'in',
	  		mediaType: res.data.mediaType == 0 ? "audio" : "video",
	        userID: res.data.mine.userId // 对方的用户id
	      })
	    }
	  })
	  
	  /** 挂断电话 */
	  CallLib.onCallDisconnected(res => {
	    console.log(
	      'Engine:OnCallDisconnected=>' + '挂断成功, 挂断原因=>',
	      res.data.reason
	    )
	    uni.navigateBack()
	  })
	  
	  CallLib.onError(res => {
	    console.log('通话过程中，发生异常，异常原因=>', res.data.reason)
	  		uni.navigateBack()
	  })
	  
	
	  // #endif
  }

  //连接融云IM
  const connectIM = async () => {
    const options = {
      naviServer: ''
    }
    imEngine.value = await RCIMIWEngine.create(
      tencentUserSig.value.appKey,
      options
    )
    imEngine.value.setOnConnectedListener(res => {
      if (res.code != 0) {
        uni.hideLoading()
        uni.showToast({
          title: 'OnCon:' + res.code,
          icon: 'error'
        })
        return
      }
      //连接成功
      CallLib.init({})
      console.log('call.init')
      // this.libPage = true;
      // this.loginUserId = res.userId;
      uni.hideLoading()
      console.log('登录成功')
    })
    const callback = {
      onDatabaseOpened: res => {
        console.log('数据库打开')
      },
      onConnected: res => {
        console.log(res)
        if (res.code === 0) {
          // uni.showToast({
          //   title: '连接成功',
          //   icon: 'none'
          // })
          console.log('连接成功')
        } else if (res.code === 34001) {
          // uni.showToast({
          //   title: '连接已存在，不需要再连接',
          //   icon: 'none'
          // })
					console.log('连接已存在，不需要再连接')
        }
		
      }
    }
    let code = await imEngine.value.connect(
      tencentUserSig.value.ryToken,
      10,
      callback
    )
    if (code != 0) {
      uni.hideLoading()
      uni.showToast({
        title: 'connect:' + code,
        icon: 'error'
      })
    }
  }

  /**
   * 清除用户信息（退出登录）
   */
  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
      removeFriendList()
      removeGroupList()
      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 {
    imEngine,
    userInfo,
    integralData,
    tencentUserSig,
    fontSizeData,
    getIntegral,
    clearAllUserInfo,
    updateFontSize,
    logout,
    refreshUserInfo,
    fetchUserInfo,
    loginTencentIM,
    setUserInfo,
    clearUserInfo,
    updateUserInfo
  }
})
