import { ref, watch, computed } from "vue";
import { defineStore } from "pinia";
import api from '@/utils/api';
import { toast } from '@/utils/widget';
import { initGlobalTIM, globalTimChatManager } from "@/utils/tim-chat.js";
import { globalUnreadListenerManager } from "@/utils/global-unread-listener.js";
import { normalizeCorpId, normalizeCorpIdFields } from "@/utils/api-base-config";
const env = __VITE_ENV__;

export default defineStore("accountStore", () => {
  const appid = env.MP_WX_APP_ID;
  const account = ref(null);
  const loading = ref(false)
  const isIMInitialized = ref(false);
  const openid = ref("");
  const externalUserId = ref('');
  const teams = ref([]);
  const hasImCorpId = computed(() => {
    // 正式环境IM账号优先 暂时只有wpLgjyawAA8N0gWmXgyJq8wpjGcOT7fg机构的才开启IM账号
    if (env.MP_VERIFY_IM_CORP_ID === 'YES') {
      return teams.value.some(i => i.corpId === 'wpLgjyawAA8N0gWmXgyJq8wpjGcOT7fg')
    }
    return true
  });
  const teamsPromise = ref(null);

  async function login(phoneCode = '', options = {}) {
    if (loading.value) return;
    if (account.value && account.value.mobile) {
      return account.value
    }
    loading.value = true;
    try {
      const { code } = await uni.login({
        appid,
        provider: "weixin",
        scope: "snsapi_base",
      });
      if (code) {
        const res = await api('wxAppLogin', {
          appId: appid,
          phoneCode,
          code
        });
        loading.value = false
        if (res.success && res.data) {
          const normalizedAccount = normalizeCorpIdFields(res.data);
          account.value = normalizedAccount;
          openid.value = normalizedAccount.openid;

          // 保存账户信息和 openId 到本地存储
          uni.setStorageSync('account', normalizedAccount);
          uni.setStorageSync('openid', normalizedAccount.openid);

          // initIMAfterLogin(openid.value)
          return normalizedAccount
        }
      }
      if (!options.silent) toast('登录失败，请重新登录');
    } catch (e) {
      if (!options.silent) toast('登录失败，请重新登录');
    }
    loading.value = false
  }

  async function initIMAfterLogin() {
    if (isIMInitialized.value) {
      return true;
    }
    try {
      // 使用 openid 作为 userID 初始化 IM
      const userID = openid.value || uni.getStorageSync('openid');
      if (!userID) {
        console.log('未获取到有效的 userId，跳过 IM 初始化');
        return false;
      }

      console.log('开始初始化 IM，userID:', userID);
      const success = await initGlobalTIM(userID);

      if (!success) {
        console.log('initGlobalTIM 返回失败，跳过 IM 初始化');
        return false;
      }

      // 验证 TIM 实例是否真正创建成功
      if (!globalTimChatManager || !globalTimChatManager.tim) {
        console.log('IM 初始化后 TIM 实例不存在，跳过 IM 初始化');
        return false;
      }

      isIMInitialized.value = true;
      console.log('IM 初始化成功');

      // IM 初始化成功后，设置全局未读消息监听
      // globalUnreadListenerManager.setup();

      return true;
    } catch (error) {
      console.log('IM初始化异常，跳过 IM 初始化:', error.message);
      return false;
    }
  }
  // 退出登录
  async function logout() {
    try {
      // 退出腾讯IM
      if (globalTimChatManager && globalTimChatManager.tim) {
        console.log('开始退出腾讯IM');
        await globalTimChatManager.destroy();
        console.log('腾讯IM退出成功');
      }

      // 清除全局未读监听
      if (globalUnreadListenerManager.isInitialized) {
        // globalUnreadListenerManager.destroy();
      }
    } catch (error) {
      console.error('退出腾讯IM失败:', error);
    }

    // 清空账户信息
    account.value = null;
    openid.value = "";
    isIMInitialized.value = false;

    // 清除本地存储
    uni.removeStorageSync('account');
    uni.removeStorageSync('openid');

    // 清除 tabBar 徽章
    uni.removeTabBarBadge({
      index: 1
    });
  }

  async function searchTeams() {
    const res = await api('getWxappRelateTeams', { openid: account.value.openid });
    teams.value = res && Array.isArray(res.data) ? normalizeCorpIdFields(res.data) : [];
    return teams.value;
  }

  async function getTeams() {
    if (!teamsPromise.value) {
      teamsPromise.value = searchTeams();
    }
    await teamsPromise.value;
    teamsPromise.value = null;
    return teams.value;
  }

  async function getExternalUserId(corpId) {
    const normalizedCorpId = normalizeCorpId(corpId);
    const unionid = account.value?.unionid;
    const openid = account.value?.openid;
    if (!(normalizedCorpId && unionid && openid)) {
		externalUserId.value = '';
		return
	};
    const res = await api('getUnionidToExternalUserid', { unionid, openid, corpId: normalizedCorpId }, false);
    const id = res && res.success && typeof res.data === 'string' && res.data.trim() ? res.data.trim() : '';
    externalUserId.value = id;
    return id;
  }

  watch(hasImCorpId, n => {
    if (n) {
      initIMAfterLogin();
    }
  }, { immediate: true })

  watch(openid, (n, o) => {
    if (n && !o) {
      getTeams();
    }
  }, { immediate: true })

  return { account, teams, hasImCorpId, login, initIMAfterLogin, logout, openid, isIMInitialized, externalUserId, getExternalUserId, getTeams }
})
