import { ref } from 'vue';
import { defineStore } from 'pinia';
import { LeaderTeamType, TeamAndPersonInfoType } from '../type';
import { queryLeaderTeam, queryEmergencyTeamDetail } from '@/api/emergency-organization/teams';
import { PositionType, saveTeamPosition } from '@/api/emergency-organization/teams';
import {
  SetTeamInfoType,
  updateEmergencyTeamInfo,
  deleteEmergencyTeam,
  saveEmergencyTeamInfo,
} from '@/api/emergency-organization/teams';

const useTeamStore = defineStore('useTeam', () => {
  // 左侧的领导队伍树
  const leaderTeamTree = ref<LeaderTeamType>({
    teamId: -1, // -1默认为无队伍
    teamName: '',
    level: 1,
    memberCount: 0,
    children: [],
  });

  const curTeam = ref<LeaderTeamType>();
  const teamAndPersonInfo = ref<TeamAndPersonInfoType>(); // 右侧的队伍信息和人员信息表格数据

  const loadingTeams = ref(false);
  const loadingTeamInfo = ref(false);

  async function getLeaderTeams() {
    loadingTeams.value = true;

    const res = await queryLeaderTeam();
    if (res) leaderTeamTree.value = setLevel(res);

    loadingTeams.value = false;
    return leaderTeamTree.value;
  }

  function setLevel(emergencySystem, level = 1): LeaderTeamType {
    return {
      ...emergencySystem,
      level,
      children: emergencySystem.children.map((child) => setLevel(child, level + 1)),
    };
  }

  async function createFirstLevelTeam(teamName: string) {
    loadingTeams.value = true;

    // 一级队伍parentId默认为0
    const data = { parentId: 0, teamName };
    await saveEmergencyTeamInfo(data).finally(() => {
      loadingTeams.value = false;
    });
  }

  async function createTeam(team: LeaderTeamType, teamName: string) {
    loadingTeams.value = true;

    const data = { parentId: team.teamId, teamName };
    const id = await saveEmergencyTeamInfo(data);

    team.children.push({
      teamId: id,
      teamName,
      level: team.level + 1,
      memberCount: 0,
      children: [],
    });

    loadingTeams.value = false;
  }

  async function deleteTeam(team: LeaderTeamType) {
    // 由于请求接口有延迟，先本地删除后再调用接口
    if (leaderTeamTree.value.teamId === team.teamId) {
      clearData();
    } else leaderTeamTree.value = filterNode(leaderTeamTree.value, team.teamId)!;

    deleteEmergencyTeam(team.teamId);

    if (team.teamId === curTeam.value?.teamId) {
      clearCurTeam();
    }
  }

  function filterNode(team: LeaderTeamType, id: number): LeaderTeamType | null {
    return team.teamId === id
      ? null
      : {
          ...team,
          children: team.children.map((child) => filterNode(child, id)).filter(Boolean) as LeaderTeamType[],
        };
  }

  function getTeamInfo(teamId: number) {
    return queryEmergencyTeamDetail(teamId);
  }

  async function refreshCurTeamInfo() {
    teamAndPersonInfo.value = await getTeamInfo(curTeam.value!.teamId);
  }

  async function getSelectTeamInfo(team: LeaderTeamType) {
    loadingTeamInfo.value = true;

    curTeam.value = team;
    refreshCurTeamInfo();

    loadingTeamInfo.value = false;
  }

  function setPositionInfo(positionList: PositionType[]) {
    loadingTeamInfo.value = true;

    const data = {
      teamId: curTeam.value!.teamId!,
      positionList: positionList,
    };
    saveTeamPosition(data);

    loadingTeamInfo.value = false;
  }

  async function setTeamInfo(data: SetTeamInfoType) {
    loadingTeamInfo.value = true;

    await updateEmergencyTeamInfo(data);

    refreshCurTeamInfo();

    loadingTeamInfo.value = false;
  }

  function clearData() {
    leaderTeamTree.value = {
      teamId: -1,
      teamName: '',
      level: 1,
      memberCount: 0,
      children: [],
    };
    clearCurTeam();
  }

  function clearCurTeam() {
    curTeam.value = undefined;
    teamAndPersonInfo.value = undefined;
  }

  return {
    leaderTeamTree,
    curTeam,
    teamAndPersonInfo,
    loadingTeams,
    loadingTeamInfo,
    getLeaderTeams,
    createFirstLevelTeam,
    createTeam,
    deleteTeam,
    refreshCurTeamInfo,
    getSelectTeamInfo,
    setPositionInfo,
    setTeamInfo,
    clearData,
  };
});

export default useTeamStore;
