import { computed, ref, watch } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { DateUtils, ObjectUtils } from '@imengyu/imengyu-utils';
import type { IHomeCommonCategoryDefine } from '../../CommonCategoryDefine';
import DefaultEditorJson from '../../DefaultCategory.json';
import CommonCategoryApi, { type ICommonCategoryConfigItem } from '../../api/CommonCategoryApi';

/** 历史版本列表项（接口返回的 items 元素） */
export interface IHistoryListItem {
  id?: number;
  data?: IHomeCommonCategoryDefine;
  createTime?: string;
  name?: string;
  [key: string]: any;
}

export function useEditorConfig() {
  const currentEditorJson = ref<IHomeCommonCategoryDefine>(DefaultEditorJson as IHomeCommonCategoryDefine);
  const selectedPage = ref<(IHomeCommonCategoryDefine['page'][0]) | null>(null);
  const historyList = ref<IHistoryListItem[]>([]);
  const currentConfig = ref<ICommonCategoryConfigItem>();
  const currentHistoryId = ref<number>(0);
  /** 是否使用开发版接口（true=开发版，false=正式版） */
  const isDev = ref(true);

  const currentShowConfigName = computed(() => {
    if (currentHistoryId.value === 0) return '默认配置';
    return historyList.value.find(item => item.id === currentHistoryId.value)?.name ?? '未知';
  });

  // 另存为弹窗
  const saveAsModalVisible = ref(false);
  const saveAsVersionName = ref('');
  const saveAsLoading = ref(false);

  // 帮助弹窗
  const helpModalVisible = ref(false);

  async function loadEditorJson(selectDefault = false) {
    try {
      currentConfig.value = await CommonCategoryApi.getConfigWithoutCache(isDev.value);
      if (!currentConfig.value) throw new Error('加载基础配置失败');
      if (selectDefault) currentHistoryId.value = currentConfig.value.activeHistoryId;
      if (currentHistoryId.value > 0) {
        const activeHistory = historyList.value.find(item => item.id === currentHistoryId.value);
        if (activeHistory) {
          currentEditorJson.value = ObjectUtils.clone(activeHistory.data!) as IHomeCommonCategoryDefine;
        } else {
          throw new Error('当前激活的历史版本不存在');
        }
      } else {
        currentEditorJson.value = ObjectUtils.clone(currentConfig.value.data) as IHomeCommonCategoryDefine;
      }
      message.success('加载分类成功');
    } catch (error) {
      Modal.error({
        title: '加载分类失败',
        content: '' + error,
      });
    }
  }

  async function loadEditorJsonHistorys() {
    try {
      const res = await CommonCategoryApi.getConfigHistoryList(isDev.value, 1, 10);
      const items = res?.items ?? [];
      historyList.value = Array.isArray(items) ? items : [];
    } catch (error) {
      historyList.value = [];
      Modal.error({
        title: '加载历史版本列表失败',
        content: '' + error,
      });
    }
  }

  function onSelectDefault() {
    currentHistoryId.value = 0;
    loadEditorJson(true);
  }

  function onSelectHistory(id: number) {
    currentHistoryId.value = id;
    loadEditorJson(false);
  }

  async function saveEditorJson() {
    try {
      const saveToHistoryId = currentHistoryId.value === 0 ? undefined : currentHistoryId.value;
      await CommonCategoryApi.editConfig(
        isDev.value,
        currentEditorJson.value,
        undefined,
        saveToHistoryId
      );
      message.success('保存成功');
    } catch (error) {
      Modal.error({
        title: '保存失败',
        content: '' + error,
      });
    }
  }

  function openSaveAsModal() {
    saveAsVersionName.value = '';
    saveAsModalVisible.value = true;
  }

  async function confirmSaveAs() {
    const name = saveAsVersionName.value?.trim();
    if (!name) {
      message.warning('请输入版本名称');
      return;
    }
    saveAsLoading.value = true;
    try {
      await CommonCategoryApi.editConfig(isDev.value, currentEditorJson.value, name, 0);
      message.success('已另存为历史版本');
      saveAsModalVisible.value = false;
      await loadEditorJsonHistorys();
    } catch (error) {
      Modal.error({
        title: '另存为失败',
        content: '' + error,
      });
    } finally {
      saveAsLoading.value = false;
    }
  }

  async function setActiveHistory() {
    await CommonCategoryApi.setActiveConfigHistory(isDev.value, currentHistoryId.value);
    message.success('设置为激活版本成功');
  }

  function deleteHistory() {
    Modal.confirm({
      title: '删除历史版本',
      content: '确定要删除该历史版本吗？注意：此操作将会删除该历史版本，无法恢复。',
      onOk: async () => {
        await CommonCategoryApi.deleteConfigHistory(isDev.value, currentHistoryId.value);
        message.success('删除历史版本成功');
        await loadEditorJsonHistorys();
        await loadEditorJson(true);
      },
    });
  }

  function exportToJsonFile() {
    const json = JSON.stringify(currentEditorJson.value);
    const blob = new Blob([json], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'editor.json';
    a.click();
  }

  async function syncToProduction() {
    if (!isDev.value) {
      message.warning('当前是正式版，无需同步至正式版');
      return;
    }
    Modal.confirm({
      title: '同步至正式版',
      content: '确定要同步至正式版吗？注意：此操作将会在正式版创建一个同步后的版本并设置为激活版本。',
      onOk: async () => {
        await CommonCategoryApi.editConfig(
          false, currentEditorJson.value, 
          `同步正式版-${DateUtils.formatDate(new Date(), 'YYYY-MM-DD HM')}`, 
          0,
          true
        );
        message.success('同步至正式版成功');
        await loadEditorJsonHistorys();
      },
    });
  }

  async function init() {
    await loadEditorJsonHistorys();
    await loadEditorJson(true);
  }

  watch(isDev, async () => {
    await loadEditorJsonHistorys();
    await loadEditorJson(true);
  });

  return {
    currentEditorJson,
    selectedPage,
    historyList,
    helpModalVisible,
    currentConfig,
    currentHistoryId,
    currentShowConfigName,
    isDev,
    saveAsModalVisible,
    saveAsVersionName,
    saveAsLoading,
    loadEditorJson,
    loadEditorJsonHistorys,
    onSelectDefault,
    onSelectHistory,
    syncToProduction,
    saveEditorJson,
    openSaveAsModal,
    confirmSaveAs,
    setActiveHistory,
    deleteHistory,
    exportToJsonFile,
    init,
  };
}
