import { type VersionInfo } from '@/apis';
import { VERSION_CHECK_QUERY_KEY } from '@/constants';
import { useQuery } from '@tanstack/vue-query';
import axios from 'axios';
import { useThemeVars } from 'naive-ui';
import { h, ref, watch } from 'vue';

export const useVersionCheckQuery = () => {
  const localVersionInfo = ref<VersionInfo>();
  const showDialog = ref<boolean>(false);
  const themeVars = useThemeVars();

  const { data: remoteVersionInfo, dataUpdatedAt } = useQuery({
    queryKey: [VERSION_CHECK_QUERY_KEY],
    refetchInterval: 10 * 1000,
    queryFn: async ({ signal }) => {
      const { data } = await axios.get<VersionInfo>(`/manifest.json?t=${Date.now()}`, { signal });
      return data;
    },
  });

  watch(dataUpdatedAt, () => {
    const newVersionInfo = remoteVersionInfo.value;
    if (!newVersionInfo) return;

    if (!localVersionInfo.value) {
      localVersionInfo.value = newVersionInfo;
      return;
    }

    const { version: localVersion, buildTime: localBuildTime } = localVersionInfo.value;
    const { version: remoteVersion, buildTime: remoteBuildTime } = newVersionInfo;

    if ((localVersion !== remoteVersion || localBuildTime !== remoteBuildTime) && !showDialog.value) {
      showDialog.value = true;
      window.$dialog.info({
        title: '发现新版本',
        content: () =>
          h('div', {}, [
            h('div', {}, { default: () => `当前版本：${localVersionInfo.value?.version}` }),
            h('div', {}, { default: () => `最新版本：${newVersionInfo.version}` }),
            h('div', {}, { default: () => '请点击刷新页面以更新' }),
            h('div', { style: { marginTop: '8px', fontWeight: '700', color: themeVars.value.warningColor } }, { default: () => '⚠️ 注意，更新后可能需要重新登录或调整系统设置！' }),
          ]),
        positiveText: '刷新页面',
        maskClosable: false,
        onPositiveClick: () => {
          window.location.reload();
        },
        negativeText: '稍后检查',
        onNegativeClick: () => {
          showDialog.value = false;
        },
        onClose: () => {
          showDialog.value = false;
        },
      });
    }
  });
};
