import { defineStore } from "pinia";
import { getAllTeamByCorp, getTeamList } from "@/api/corp.js";
import { getRolesByRoleId } from "@/api/corp";
import { memberStore } from "@/store/member";
const teamStore = defineStore("team", {
  state: () => {
    return {
      currentTeam: {},
      teams: [],
      allTeams: [],
      roles: [],
      isAdmin: false,
      managerList: [],
    };
  },
  getters: {
    currentTeamId(state) {
      return state.currentTeam && state.currentTeam.teamId ? state.currentTeam.teamId : "";
    },
    currentTeamName(state) {
      return state.currentTeam && state.currentTeam.name ? state.currentTeam.name : "";
    },
    managerList(state) {
      const mergedManagerList = state.roles.reduce((acc, role) => {
        // 将当前角色的managerList与累加器中的列表合并
        return acc.concat(role.managerList || []);
      }, []);
      return Array.from(new Set(mergedManagerList));
    },
  },
  actions: {
    getArchiveLink(teamId, qrid) {
      return `${import.meta.env.VITE_PATIENT_PAGE_BASE_URL}pages/external/memberManage/index?qrid=${qrid}&teamId=${teamId}&corpId=${sessionStorage.getItem("corpId")}`;
    },
    async getTeams() {
      const { data } = await getTeamList();
      const teams = Array.isArray(data.data) ? data.data : [];
      this.teams = teams;
      return teams;
    },
    async getAllTeams() {
      const { success, data } = await getAllTeamByCorp();
      if (success) {
        this.allTeams = data.data;
        await this.setCurrentTeam();
      }
    },
    teamSubscribe(callback) {
      this.$subscribe((mutation, state) => {
        callback && callback(state);
      });
    },
    async getUserRole() {
      const { memberInfo } = memberStore();
      const { roleIds } = memberInfo;
      let { data } = await getRolesByRoleId(roleIds);

      this.roles = data.data;
      this.isAdmin = data.data?.some((i) => i.roleId === "admin");
    },
    async setCurrentTeam(id) {
      // 从sessionStorage中获取当前团队id
      let storeTeamId = sessionStorage.getItem("currentTeamId");
      const { memberInfo } = memberStore();
      //判断当前团队id是否在当前用户的团队列表中;
      if (!this.roles || this.roles.length === 0) await this.getUserRole();
      if (!memberInfo.teamId?.some((i) => i === storeTeamId) && !this.isAdmin) {
        storeTeamId = "";
        sessionStorage.removeItem("currentTeamId");
      }
      const teamId = id || this.currentTeamId || storeTeamId;
      const arr = this.isAdmin ? this.allTeams : this.teams;
      const team = teamId ? arr.find((i) => teamId === i.teamId) : null;
      const currentTeam = team || arr[0] || {};
      this.currentTeam = currentTeam;
      if (currentTeam.teamId) sessionStorage.setItem("currentTeamId", currentTeam.teamId);
      else sessionStorage.removeItem("currentTeamId");
    },
  },
});
export { teamStore };
