<template>
  <BContainer v-if="asyncReady" id="container" :toast="{ root: true }">
    <TopBackBar title="감찰부" :reloadable="true" @reload="reload" />

    <div class="row gx-0">
      <BFormSelect v-model="targetGeneralID">
        <BFormSelectOption v-for="general of orderedGeneralList" :key="general.no" :value="general.no">
          <span
            :style="{
              color: getNpcColor(general.npc),
            }"
            >{{ general.name }}</span
          >
        </BFormSelectOption>
      </BFormSelect>
    </div>
    <div class="row gx-0">
      <GeneralBasicCard v-if="targetGeneral && nationInfo" class="col-12 col-md-6" :general="targetGeneral" :nation="nationInfo" />
    </div>

    <BottomBar></BottomBar>
  </BContainer>
</template>

<script lang="ts">
declare const staticValues: {
  serverNick: string;
  mapName: string;
  unitSet: string;
};
declare const queryValues: {
  generalID: number | null;
};
</script>
<script lang="ts" setup>
import { BContainer, useToast, BFormSelect, BFormSelectOption } from "bootstrap-vue-3";
import { onMounted, provide, ref, watch } from "vue";
import { getGameConstStore, type GameConstStore } from "./GameConstStore";
import TopBackBar from "@/components/TopBackBar.vue";
import BottomBar from "@/components/BottomBar.vue";
import type { GeneralListItemP1 } from "./defs/API/Nation";
import { SammoAPI } from "./SammoAPI";
import { unwrap } from "@/util/unwrap";
import { merge2DArrToObjectArr } from "@/util/merge2DArrToObjectArr";
import { getNpcColor } from "@/common_legacy";
import GeneralBasicCard from "./components/GeneralBasicCard.vue";
import type { NationStaticItem } from "./defs";

const toasts = unwrap(useToast());

const generalList = ref(new Map<number, GeneralListItemP1>());
const textMap = {
  recent_war: ["최근 전투", (gen: GeneralListItemP1) => gen.recent_war, false],
  warnum: ["전투 횟수", (gen: GeneralListItemP1) => gen.warnum, false],
  turntime: ["최근 턴", (gen: GeneralListItemP1) => gen.turntime, false],
  name: ["이름", (gen: GeneralListItemP1) => `${gen.npc} ${gen.name}`, false],
} as const;

const orderedGeneralList = ref<GeneralListItemP1[]>([]);
const orderBy = ref<keyof typeof textMap>("turntime");
const targetGeneral = ref<GeneralListItemP1>();
const targetGeneralID = ref(queryValues.generalID ?? undefined);

const nationInfo = ref<NationStaticItem>();

watch([generalList, targetGeneralID], ([generalList, targetGeneralID]) => {
  if (targetGeneralID === undefined) return;
  targetGeneral.value = generalList.get(targetGeneralID);
});

watch([generalList, orderBy], ([generalList, orderBy]) => {
  console.log(generalList);
  const list = Array.from(generalList.values());
  list.sort((a, b) => {
    const [, getter, isAsc] = textMap[orderBy];
    const aVal = getter(a);
    const bVal = getter(b);
    if (aVal === bVal) return 0;
    return isAsc ? (aVal > bVal ? 1 : -1) : aVal < bVal ? 1 : -1;
  });
  orderedGeneralList.value = list;
  targetGeneralID.value = list[0].no;
});

const asyncReady = ref(false);
const gameConstStore = ref<GameConstStore>();
provide("gameConstStore", gameConstStore);
const storeP = getGameConstStore().then((store) => {
  gameConstStore.value = store;
});

void Promise.all([storeP]).then(() => {
  asyncReady.value = true;
});

async function reload(): Promise<void> {
  console.log("갱신 시도");

  try {
    const nationP = SammoAPI.Nation.GetNationInfo({});
    const { column, list, permission, troops, env } = await SammoAPI.Nation.GeneralList();

    if (permission === 0) {
      throw "권한이 부족합니다.";
    }

    console.log(list);
    const rawGeneralList = merge2DArrToObjectArr(column, list);

    const newList = new Map<number, GeneralListItemP1>();
    for (const general of rawGeneralList) {
      newList.set(general.no, general);
    }
    generalList.value = newList;

    const { nation } = await nationP;
    nationInfo.value = nation;
  } catch (e) {
    toasts.danger({
      title: "오류",
      body: `${e}`,
    });
    console.error(e);
  }
}

onMounted(async () => {
  await reload();
});
</script>
