import { useUserStore } from './user';
import { LINE_ALARMS_QUERY_KEY, LINE_DEVICES_QUERY_KEY, LINE_STATIONS_QUERY_KEY, NDM_SETTING_STORE_ID } from '@/constants';
import router from '@/router';
import { useQueryClient } from '@tanstack/vue-query';
import { darkTheme, lightTheme } from 'naive-ui';
import { defineStore } from 'pinia';
import { computed, ref, watch } from 'vue';

export const useSettingStore = defineStore(
  NDM_SETTING_STORE_ID,
  () => {
    const queryClient = useQueryClient();

    // 主题设置
    const darkMode = ref(true);
    const themeMode = computed(() => {
      return darkMode.value ? darkTheme : lightTheme;
    });

    // 布局设置
    const menuCollpased = ref(false);
    const stationGridCols = ref(6);

    // 调试模式
    const debugMode = ref(false);
    /* 数据设置 */
    // 显示设备原始数据
    const showDeviceRawData = ref(false);
    /* 网络设置 */
    // 轮询车站
    const pollingStations = ref(true);
    // 主动请求
    const activeRequests = ref(true);
    // 订阅消息
    const subscribeMessages = ref(true);
    // 模拟用户
    const mockUser = ref(false);
    /* 数据库设置 */
    // 使用本地数据库
    const useLocalDB = ref(false);

    watch(debugMode, (newValue, oldValue) => {
      // 监听关闭调试模式
      if (oldValue && !newValue) {
        showDeviceRawData.value = false;
        pollingStations.value = true;
        activeRequests.value = true;
        subscribeMessages.value = false;
        mockUser.value = false;
        useLocalDB.value = false;
      }
    });

    watch(pollingStations, (newValue, oldValue) => {
      // 监听关闭车站轮询
      if (oldValue && !newValue) {
        queryClient.cancelQueries({ queryKey: [LINE_STATIONS_QUERY_KEY] });
        queryClient.cancelQueries({ queryKey: [LINE_DEVICES_QUERY_KEY] });
        queryClient.cancelQueries({ queryKey: [LINE_ALARMS_QUERY_KEY] });
        queryClient.invalidateQueries({ queryKey: [LINE_STATIONS_QUERY_KEY] });
        queryClient.invalidateQueries({ queryKey: [LINE_DEVICES_QUERY_KEY] });
        queryClient.invalidateQueries({ queryKey: [LINE_ALARMS_QUERY_KEY] });
      }
    });

    watch(mockUser, (newValue, oldValue) => {
      // 监听启用模拟用户
      if (!oldValue && newValue) {
        // 如果启当前未登录，填写token以绕过路由守卫
        const userStore = useUserStore();
        if (!userStore.userLoginResult) {
          userStore.userLoginResult = {
            tenantId: '',
            uuid: '',
            token: 'test',
            refreshToken: '',
            expire: '',
            expiration: '',
          };
        }
        // 如果token为空，填写token
        if (!userStore.userLoginResult.token) {
          userStore.userLoginResult.token = 'test';
        }
        // 如果用户信息为空，填写用户信息
        if (!userStore.userInfo) {
          userStore.userInfo = {
            id: '2',
            username: 'lamp',
            nickName: '内置超管',
            mobile: '15211111110',
            employeeId: '2',
            tenantId: '1',
          };
        }
        // 如果当前路由为登录页，跳转到首页
        if (router.currentRoute.value.path === '/login') {
          router.push({ path: '/' });
        }
        // 开启模拟用户时，也开启调试模式，但关闭其他的网络设置
        debugMode.value = true;
        pollingStations.value = false;
        activeRequests.value = false;
        subscribeMessages.value = false;
      }
    });

    return {
      darkMode,
      themeMode,

      menuCollpased,
      stationGridCols,

      debugMode,
      showDeviceRawData,
      pollingStations,
      activeRequests,
      subscribeMessages,
      mockUser,
      useLocalDB,
    };
  },
  {
    persist: [
      {
        omit: ['showDeviceRawData'],
        storage: window.localStorage,
      },
      {
        pick: ['showDeviceRawData'],
        storage: window.sessionStorage,
      },
    ],
  },
);
