import { inject, provide, ref, type Ref } from "vue";
import { showError } from "@/common/composeabe/ErrorDisplay";
import DefaultCofig from "./DefaultCategory.json";
import type { IHomeCommonCategoryDefine } from "./CommonCategoryDefine";
import CommonCategoryApi from "./api/CommonCategoryApi";
import { getIsDevtoolsPlatform, getMpEnvVersion } from "@/common/utils/MpVersions";

// 全局加载默认分类

export const COMMON_CATEGORY_KEY = 'DefaultCategory';

const defaultCommonCategory = ref<IHomeCommonCategoryDefine>({
  page: [],
});

export function injectCommonCategory() {
  return inject(COMMON_CATEGORY_KEY, defaultCommonCategory) as Ref<IHomeCommonCategoryDefine>;
}
export function useCommonCategoryGlobalLoader() {

  const commonCategoryData = ref<IHomeCommonCategoryDefine>(defaultCommonCategory.value);

  provide(COMMON_CATEGORY_KEY, commonCategoryData);

  async function loadCommonCategory() {
    uni.showLoading({ title: '加载中' });
    try {
      //本地开发时，使用默认配置
      if (false && getIsDevtoolsPlatform()) {
        commonCategoryData.value = DefaultCofig as IHomeCommonCategoryDefine;
        return;
      }
      //根据环境版本，使用正式配置或体验配置
      const category = (await CommonCategoryApi.getConfig(
        // #ifdef MP-WEIXIN
        getMpEnvVersion() === 'release' ? false : 
        // #endif
        true
      )) as any as IHomeCommonCategoryDefine;
      if (category)
        commonCategoryData.value = category;
      else
        showError(undefined, '默认分类未配置');
    } catch (error) {
      console.error('加载默认分类失败', error);
      // 加载失败时，使用默认配置
      commonCategoryData.value = DefaultCofig as IHomeCommonCategoryDefine;
    } finally {
      uni.hideLoading();
    }
  }

  return {
    loadCommonCategory,
  }
}