import { defineStore } from "pinia";
import { ref, watch, defineEmits } from "vue";
import type { QTableProps } from "quasar";
import type { DataRows } from "@/modules/09_leave/interface/response/specialTime";
import type { DataDateMonthObject } from "@/modules/09_leave/interface/request/specialTime";

import { useCounterMixin } from "@/stores/mixin";
import type { DataOption } from "@/modules/09_leave/interface/index/Main";
import http from "@/plugins/http";
import config from "@/app.config";
import { useQuasar } from "quasar";
import { mount } from "@vue/test-utils";

const $q = useQuasar();
const mixin = useCounterMixin();
const {
  date2Thai,
  messageError,
  showLoader,
  dialogMessageNotify,
  dialogConfirm,
  success,
  hideLoader,
} = mixin;

export const useSpecialTimeStore = defineStore("LeaveSpecialTime", () => {
  const rows = ref<any[]>([]);
  const selectDate = ref<Date | null>(new Date());
  const fiscalYear = ref<string | null>("0");
  const DataMainOrig = ref<DataRows[]>([]); // ข้อมูลหลักดั้งเดิม
  const DataMainUpdate = ref<DataRows[]>([]); // ข้อมูลเปลี่ยนแปลง
  const DataMain = (val: DataRows[]) => (DataMainOrig.value = val);
  const DataUpdate = (filterYear: string) => {
    DataMainUpdate.value = [];
    if (filterYear === "") {
      DataMainUpdate.value = DataMainOrig.value;
    }
  };
  const checkInStatus = ref<String>("ปกติ");
  const checkOutStatus = ref<String>("ปกติ");

  // paging
  const toDay = ref<Date>(new Date());
  const monthToday = toDay.value.getMonth();
  const yearToday = toDay.value.getFullYear();
  console.log(monthToday + 1);

  const month = ref<number>(monthToday + 1);
  const year = ref<number>(yearToday);
  const page = ref<number>(1);
  const total = ref<number>(0);
  const pageSize = ref<number>(10);
  const filter = ref<string>(""); //search data table
  const maxPage = ref<number>(0);

  /**
   * ฟังชั้นเรียกดูข้อมูล
   */
  const fetchData = async () => {
    showLoader();
    await http
      .get(
        config.API.specialTime() +
          `?year=${year.value}&month=${month.value}&page=${page.value}&pageSize=${pageSize.value}&keyword=${filter.value}`
      )
      .then(async (res) => {
        let data = res.data.result.data;
        total.value = res.data.result.total;
        maxPage.value = await Math.ceil(total.value / pageSize.value);
        maxPage.value = maxPage.value < 1 ? 1 : maxPage.value;
        rows.value = [];
        data.map((e: any) => {
          rows.value.push({
            id: e.id,
            fullname: e.fullName,
            date: date2Thai(new Date(e.createdAt), false, true),
            dateFix: date2Thai(new Date(e.checkDate)),
            timeMorning:
              e.startTimeMorning == null
                ? "-"
                : e.checkInEdit == true
                ? e.startTimeMorning + " - " + e.endTimeMorning
                : "-",
            timeAfternoon:
              e.startTimeAfternoon == null
                ? "-"
                : e.checkOutEdit == true
                ? e.startTimeAfternoon + " - " + e.endTimeAfternoon
                : "-",
            startTimeMorning: e.startTimeMorning,
            endTimeMorning: e.endTimeMorning,
            startTimeAfternoon: e.startTimeAfternoon,
            endTimeAfternoon: e.endTimeAfternoon,
            checkIn: e.checkInTime,
            checkOut: e.checkOutTime,
            status: e.status,
            checkInStatus: convertStatus(e.checkInStatus),
            checkOutStatus: convertStatus(e.checkOutStatus),
            reason: e.reason,
            description: e.description,
            checkInEdit: e.checkInEdit,
            checkOutEdit: e.checkOutEdit,
          });
        });
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
        console.log(month.value);
      });
  };

  /**
   * ฟังก์ชั่น api เปลี่ยนหน้า
   * @param pageVal page
   * @param pageSizeVal pagesize
   */
  async function changePage(pageVal: number, pageSizeVal: number) {
    page.value = await pageVal;
    pageSize.value = await pageSizeVal;
    console.log(pageSize.value);

    fetchData();
    console.log("page");
  }

  //--------------|ฟิลเตอร์|--------------------------------------//
  const searchFilterTable = async (searchDate: any) => {
    rows.value = [];

    if (fiscalYear.value !== undefined && searchDate.value !== null) {
      await DataUpdate(searchDate.value === "0" ? "all" : searchDate.value!);
      let filteredData = DataMainOrig.value;
      if (searchDate.value !== "0") {
        filteredData = filteredData.filter(
          (item: DataRows) => item.date === searchDate.value
        );
        console.log(searchDate.value);
      }
      const dataArr = filteredData.map((e: any) => ({
        fullname: e.fullname,
        date: date2Thai(new Date(e.date)),
        dateFix: date2Thai(new Date(e.dateFix)) + (e.timeStamp || ""),
        type: e.type,
        reason: e.reason,
        timeStamp: e.timeStamp,
      }));
      rows.value = dataArr;
    }
  };
  const optionStatus = ref<DataOption[]>([
    { id: "NORMAL", name: "ปกติ" },
    { id: "LATE", name: "สาย" },
    { id: "ABSENT", name: "ขาดราชการ" },
    { id: "NOT_COMPLETE", name: "ปฏิบัติงานไม่ครบตามกำหนดเวลา" },
  ]);

  //   const filterSelector = (val: any, update: Function, refData: string) => {
  //     switch (refData) {
  //       case "":
  //         update(() => {
  //           selectDate.value = selectDate.value.filter(
  //             (v: any) => v.name.indexOf(val) > -1
  //           );
  //         });
  //         break;

  //       default:
  //         break;
  //     }
  //   };

  const visibleColumns = ref<String[]>([
    "no",
    "fullname",
    "date",
    "dateFix",
    "timeMorning",
    "timeAfternoon",
    "description",
  ]);

  const columns = ref<QTableProps["columns"]>([
    {
      name: "no",
      align: "center",
      label: "ลำดับ",
      sortable: false,
      field: "no",
      headerStyle: "font-size: 14px",
      style: "font-size: 14px",
    },
    {
      name: "fullname",
      align: "left",
      label: "ชื่อ-นามสกุล",
      sortable: true,
      field: "fullname",
      headerStyle: "font-size: 14px",
      style: "font-size: 14px",
    },
    {
      name: "date",
      align: "left",
      label: "วันที่ยื่นเรื่อง",
      sortable: true,
      field: "date",
      headerStyle: "font-size: 14px",
      style: "font-size: 14px",
    },
    {
      name: "dateFix",
      align: "left",
      label: "วันที่ขอแก้ไข",
      sortable: true,
      field: "dateFix",
      headerStyle: "font-size: 14px",
      style: "font-size: 14px",
    },
    {
      name: "timeMorning",
      align: "left",
      label: "ช่วงเช้า",
      sortable: true,
      field: "timeMorning",
      headerStyle: "font-size: 14px",
      style: "font-size: 14px",
    },
    {
      name: "timeAfternoon",
      align: "left",
      label: "ช่วงบ่าย",
      sortable: true,
      field: "timeAfternoon",
      headerStyle: "font-size: 14px",
      style: "font-size: 14px",
    },
    {
      name: "description",
      align: "left",
      label: "เหตุผล",
      sortable: true,
      field: "description",
      headerStyle: "font-size: 14px",
      style: "font-size: 14px",
    },
  ]);

  // convertSatatus
  function convertStatus(val: string) {
    switch (val) {
      case "normal":
        return "ปกติ";
      case "late":
        return "สาย";
      case "absent":
        return "ขาดราชการ";
    }
  }

  return {
    // fecthList,
    rows,
    visibleColumns,
    columns,
    DataMain,
    searchFilterTable,
    selectDate,
    checkInStatus,
    checkOutStatus,
    optionStatus,
    fetchData,
    changePage,
    total,
    maxPage,
    year,
    page,
    pageSize,
    month,
    filter,
    // changeMonth,
  };
});
