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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { calculateFiscalYear } from "@/utils/function";

/** importType*/
import type { DataProfilePosition } from "@/interface/response/main";
import type { DateFilter } from "@/modules/09_leave/interface/request/leave";
import type {
  DataRows,
  ListLeave,
  LeaveType,
} from "@/modules/09_leave/interface/response/leave";
import type { FormData } from "@/modules/09_leave/interface/request/leave";

const mixin = useCounterMixin();
const { date2Thai } = mixin;

export const useLeavelistDataStore = defineStore("leave", () => {
  const dataToobar = ref<any[]>([]);
  /** ข้อมูล Main*/
  const tabMenu = ref<string>("1");

  /** ข้อมูล Tab 1*/
  const tabView = ref<string>("list");
  /** filter*/
  const filter = reactive<DateFilter>({
    year: calculateFiscalYear(new Date()), //*ปีในการยื่นขอใบลา(ใช้เป็น คศ.)
    type: "00000000-0000-0000-0000-000000000000", //*Id ประเภทการลา
    status: "ALL", //*สถานะการของลา
    keyword: "", //keyword ค้นหา
  });

  /**ข้อมูลใน Table*/
  const mainData = ref<any[]>([]);
  const rows = ref<DataRows[]>([]);
  const columns = ref<QTableProps["columns"]>([]);
  const visibleColumns = ref<string[]>([]);
  const profilePositionData = ref<DataProfilePosition>();

  const leaveType = ref<LeaveType[]>([]);

  /**
   * ฟังก์ชั่น fetchListLeave
   * @param data รับข้อมูลจาก Page
   */
  async function fetchListLeave(data: ListLeave[]) {
    let datalist = data.map((e: ListLeave) => ({
      id: e.id,
      leaveTypeName: e.leaveTypeName ?? "-",
      profileType: e.profileType ?? "-",
      leaveTypeId: e.leaveTypeId ?? "-",
      citizenId: e.citizenId ?? "-",
      leaveSubTypeName: e.leaveSubTypeName,
      leaveRange: e.leaveRange ?? "-",
      leaveRangeEnd: e.leaveRangeEnd ?? "-",
      fullName:
        e.fullName !== undefined && e.fullName !== null && e.fullName !== ""
          ? e.fullName
          : "-",
      agency:
        e.agency !== undefined && e.agency !== null && e.agency !== ""
          ? e.agency
          : "-",
      org: e.org !== undefined && e.org !== null && e.org !== "" ? e.org : "-",
      position: e.position ?? "-",
      level: e.level ?? "-",
      hajjDayStatus: e.hajjDayStatus,
      dateSendLeave: e.dateSendLeave && date2Thai(e.dateSendLeave),
      dateLeave:
        e.leaveStartDate && e.leaveEndDate
          ? e.leaveStartDate === e.leaveEndDate
            ? e.leaveRange === "ALL"
              ? date2Thai(e.leaveEndDate)
              : date2Thai(e.leaveEndDate) +
                ` (${converstType(e.leaveRangeEnd)})`
            : `${date2Thai(e.leaveStartDate)}${
                e.leaveRange !== "ALL" ? ` (${converstType(e.leaveRange)})` : ""
              } - ${date2Thai(e.leaveEndDate)}${
                e.leaveRangeEnd !== "ALL"
                  ? ` (${converstType(e.leaveRangeEnd)})`
                  : ""
              }`
          : "-",
      status: e.status && convertSatatus(e.status),
      statusText: e.status,
      leaveTotal: e.leaveTotal,
    }));
    mainData.value = datalist;
    rows.value = mainData.value;
  }

  function converstType(val: string) {
    switch (val) {
      case "ALL":
        return "";
      case "MORNING":
        return "ครึ่งวันเช้า";
      case "AFTERNOON":
        return "ครึ่งวันบ่าย";
    }
  }

  /**
   * ฟังก์ชั่น fetchListLeave
   * @param data รับข้อมูลจาก Page
   */
  async function fetchListLeaveReject(data: any[]) {
    let datalist = data.map((e: FormData) => ({
      id: e.id,
      profileType: e.profileType ?? "-",
      leaveTypeName: e.leaveTypeName,
      leaveSubTypeName: e.leaveSubTypeName,
      leaveTypeId: e.leaveTypeId,
      fullName: e.fullName,
      dateSendLeave: e.dateSendLeave && date2Thai(e.dateSendLeave),
      status: convertSatatus2(e.status),
      statusText: e.status,
    }));

    mainData.value = datalist;
    rows.value = mainData.value;
  }

  /**
   * ฟังก์ชั่นแปลงสถานะ tab1
   * @param val ค่าสถานะ
   */
  function convertSatatus(val: string) {
    switch (val) {
      case "NEW":
        return "ใหม่";
      case "PENDING":
        return "กำลังดำเนินการ";
      case "APPROVE":
        return "อนุญาต";
      case "REJECT":
        return "ไม่อนุญาต";
      case "DELETING":
        return "กำลังดำเนินการยกเลิก";
      case "DELETE":
        return "ยกเลิกสำเร็จ";
    }
  }

  /**
   * ฟังก์ชั่นแปลงสถานะ tab2
   * @param val ค่าสถานะ
   */
  function convertSatatus2(val: string) {
    switch (val) {
      case "NEW":
        return "ใหม่";
      case "APPROVE":
        return "อนุญาต";
      case "REJECT":
        return "ไม่อนุญาต";
    }
  }

  /**
   * ฟังชั่นแปลงค่าการลา
   * @param val ค่าของการลา
   */
  function convertLeaveDaytype(val: string) {
    switch (val) {
      case "ALL_DAY":
        return "ลาทั้งวัน";
      case "HAFT_MORNING":
        return "ลาครึ่งวันเช้า";
      case "HAFT_AFTERNOON":
        return "ลาครึ่งวันบ่าย";
    }
  }

  /** function ข้อมูลประเภทการลา*/
  async function leaveTypeList() {
    if (leaveType.value.length == 0) {
      try {
        const res = await http.get(config.API.leaveType());
        leaveType.value = res.data.result;
        leaveTypeOption();
        return res.data.result;
      } catch (error) {
        throw error; // re-throw ถ้าต้องการให้ caller handle error
      }
    } else {
      return leaveType.value;
    }
  }

  function colorType(val: string) {
    const dataType = leaveType.value.find((item: LeaveType) => item.id === val);
    if (dataType) {
      switch (dataType.code) {
        case "LV-001":
          return "#FFD1D1"; // Light Red
        case "LV-002":
          return "#C8E6C9"; // Light Green
        case "LV-003":
          return "#BBDEFB"; // Light Blue
        case "LV-004":
          return "#E1BEE7"; // Light Purple
        case "LV-005":
          return "#DCEDC8"; // Light Lime
        case "LV-006":
          return "#FFE0B2"; // Light Orange
        case "LV-007":
          return "#FFECB3"; // Light Amber
        case "LV-008":
          return "#CFD8DC"; // Light Blue Grey
        case "LV-009":
          return "#FFCCBC"; // Light Deep Orange
        case "LV-010":
          return "#FFF9C4"; // Light Amber Lighten
        case "LV-011":
          return "#B2DFDB"; // Light Teal
      }
    }
  }

  function leaveTypeOption() {
    dataToobar.value = leaveType.value.map((e: LeaveType) => ({
      id: e.id,
      name: e.name,
      code: e.code,
    }));
  }

  /** ฟังก์ชั่นดึงข้อมูลตำแหน่งจาก Keycloak */
  async function fetchKeycloakPosition() {
    if (!profilePositionData.value) {
      try {
        const res = await http.get(config.API.keycloakPosition());
        profilePositionData.value = res.data.result;
        return res.data.result;
      } catch (error) {
        throw error;
      }
    } else {
      return profilePositionData.value; // Return cached data if available
    }
  }

  return {
    dataToobar,
    tabMenu,
    filter,
    tabView,
    rows,
    fetchListLeave,
    columns,
    visibleColumns,
    fetchListLeaveReject,
    convertSatatus,
    convertLeaveDaytype,
    leaveType,
    colorType,
    converstType,
    leaveTypeOption,
    leaveTypeList,
    fetchKeycloakPosition,
  };
});
