import type { NdmPermissionResultVO, Station } from '@/apis';
import { NDM_PERMISSION_STORE_ID } from '@/constants';
import { PERMISSION_TYPE_NAMES, type PermissionType } from '@/enums';
import { useStationStore } from '@/stores';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { objectEntries } from '@vueuse/core';

type Permissions = Record<Station['code'], PermissionType[]>;

export const usePermissionStore = defineStore(
  NDM_PERMISSION_STORE_ID,
  () => {
    const stationStore = useStationStore();

    const permissionRecords = ref<NdmPermissionResultVO[] | null>(null);

    const permissions = computed<Permissions>(() => {
      const result: Permissions = {};

      const records = permissionRecords.value;

      // 如果权限记录不存在，则不做权限配置
      if (!records) return result;

      // 如果该用户没有任何权限记录，则开放所有权限，否则根据记录配置权限
      if (records.length === 0) {
        stationStore.stations.forEach((station) => {
          result[station.code] = [...objectEntries(PERMISSION_TYPE_NAMES).map(([permType]) => permType)];
        });
      } else {
        stationStore.stations.forEach((station) => {
          result[station.code] = [];
          const stationPermRecords = records.filter((record) => record.stationCode === station.code);
          if (stationPermRecords.length === 0) return;
          stationPermRecords.forEach(({ type: permType }) => {
            if (!permType) return;
            result[station.code]?.push(permType);
          });
        });
      }

      return result;
    });

    // 按权限对车站进行分类
    const stations = computed(() => {
      const result: Partial<Record<PermissionType, Station[]>> = {};
      // 按原始的车站顺序进行遍历，保持显示顺序不变
      stationStore.stations.forEach((station) => {
        const permissionTypes = permissions.value[station.code];
        if (!permissionTypes) return;
        permissionTypes.forEach((permissionType) => {
          if (!result[permissionType]) result[permissionType] = [];
          result[permissionType].push(station);
        });
      });
      return result;
    });

    const setPermRecords = (records: NdmPermissionResultVO[]) => {
      permissionRecords.value = records;
    };

    return {
      permissionRecords,

      permissions,
      stations,

      setPermRecords,
    };
  },
  {
    persist: true,
  },
);
