import { defineStore } from "pinia";
import { ref, reactive } from "vue";

import type { DataOption } from "@/modules/04_registryPerson/interface/index/Main";
import type {
  DataType,
  DataLevel,
} from "@/modules/04_registryPerson/interface/response/Main";
import type { FormFilter } from "@/modules/04_registryPerson/interface/request/Main";

export const useRegistryNewDataStore = defineStore("registryNew", () => {
  const searchTypeOption = ref<DataOption[]>([
    { id: "fullName", name: "ชื่อ-นามสกุล" },
    { id: "citizenId", name: "เลขประจำตัวประชาชน" },
    { id: "position", name: "ตำแหน่งในสายงาน" },
    { id: "posNo", name: "ตำแหน่งเลขที่" },
  ]);
  const employeeClassOps = ref<DataOption[]>([
    { id: "officer", name: "ข้าราชการ กทม.สามัญ" },
    { id: "perm", name: "ลูกจ้างประจำ" },
    // { id: "temp", name: "ลูกจ้างชั่วคราว" },
  ]);
  const posTypeOps = ref<DataOption[]>([]);
  const posTypeMain = ref<DataType[]>([]);
  const posLevelOps = ref<DataOption[]>([]);
  const yearOps = ref<DataOption[]>([]);
  const mode = ref<string>("table");
  const isLeave = ref<boolean>(false);
  const tabs = ref<string>("Main");
  const tabsManu = ref<DataOption[]>([
    { name: "ข้อมูลส่วนตัว", id: "Main" },
    { name: "ข้อมูลการพัฒนารายบุคคล (IDP)", id: "IDP" },
  ]);
  function fetchType(data: DataType[]) {
    posTypeMain.value = data;

    const list: DataOption[] = data.map((e: DataType) => ({
      id: e.id,
      name: e.posTypeName,
    }));
    posTypeOps.value = list;
  }
  function fetchLevel(data: DataLevel[], shortName: string = "") {
    const list: DataOption[] = data.map((e: DataLevel) => ({
      id: e.id,
      name: shortName ? `${shortName} ${e.posLevelName}` : e.posLevelName,
    }));
    const seen = new Set();
    posLevelOps.value = list.filter((item: DataOption) => {
      if (seen.has(item.name)) {
        return false;
      } else {
        seen.add(item.name);
        return true;
      }
    });
  }

  const formFilter = reactive<FormFilter>({
    page: 1,
    pageSize: 12,
    keyword: "",
    type: "officer",
    posType: "",
    posLevel: "",
    retireYear: "",
    rangeYear: { min: 0, max: 60 },
    isShowRetire: false,
    isProbation: false,
    isAll: true,
    nodeId: null,
    node: null,
    searchType: "fullName",
  });

  const labelOption = reactive({
    type: "ข้าราชการ กทม.สามัญ",
    posType: "ทั้งหมด",
    posLevel: "ทั้งหมด",
    retireYear: "",
    node: "เลือกหน่วยงาน",
  });

  return {
    fetchType,
    fetchLevel,
    posTypeMain,
    searchTypeOption,
    employeeClassOps,
    posTypeOps,
    posLevelOps,
    yearOps,
    mode,
    formFilter,
    labelOption,
    isLeave,
    tabs,
    tabsManu,
  };
});
