import { defineStore } from "pinia";
import { useQuasar } from "quasar";
import { ref } from "vue";

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

import type {
  changeShow,
  historyShow,
  DataInterface,
} from "@/modules/09_leave/interface/response/changeRound";
import type { QTableProps } from "quasar";

const mixin = useCounterMixin();
const $q = useQuasar();
const { date2Thai, messageError, showLoader, hideLoader } = mixin;
const checkCilck = ref<boolean>(false);
const profileId = ref<string>("");

export const useChangeRoundDataStore = defineStore(
  "changeRoundDataStore",
  () => {
    //ค้นหา คอลัมน์ คอลัมน์ที่แสดง
    const visibleColumns = ref<string[]>([
      "cardId",
      "fullName",
      "currentRound",
      "effectiveDate",
    ]);
    const visibleColumnsHistory = ref<string[]>([
      "round",
      "time",
      "effectiveDate",
      "reson",
    ]);

    // หัวตาราง
    const columns = ref<QTableProps["columns"]>([
      {
        name: "cardId",
        align: "left",
        label: "เลขประจำตัวประชาชน",
        sortable: true,
        field: "cardId",
        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: "currentRound",
        align: "left",
        label: "รอบปัจจุบัน",
        sortable: true,
        field: "currentRound",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
      },
      {
        name: "effectiveDate",
        align: "left",
        label: "วันที่มีผล",
        sortable: true,
        field: "effectiveDate",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
      },
    ]);
    const columnsHistory = ref<QTableProps["columns"]>([
      {
        name: "round",
        align: "left",
        label: "ครั้งที่",
        sortable: true,
        field: "round",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
      },
      {
        name: "time",
        align: "left",
        label: "รอบเวลา",
        sortable: true,
        field: "time",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
      },
      {
        name: "effectiveDate",
        align: "left",
        label: "วันที่มีผล",
        sortable: true,
        field: "effectiveDate",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
      },
      {
        name: "reson",
        align: "left",
        label: "เหตุผล",
        sortable: true,
        field: "reson",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
      },
    ]);

    // ข้อมูลในตาราง
    function setProfileId(id: string) {
      profileId.value = id;
    }

    const maxPageMain = ref<number>(0);
    const totalListMain = ref<number>(0);

    async function fetchDataForCardId(dataDetail: any) {
      if (dataDetail) {
        showLoader();
        await http
          .post(config.API.leaveSearch(), {
            citizenId: dataDetail.cardId || "", //เลขประจำตัวประชาชน
            firstname: dataDetail.firstName || "", //ชื่อจริง
            lastname: dataDetail.lastName || "", //นามสกุล
            page: dataDetail.page, //หน้า
            pageSize: dataDetail.pageSize || 10, //จำนวนแถวต่อหน้า
            keyword: dataDetail.keyword || "", //keyword ค้นหา
          })
          .then((res) => {
            const apiData = res.data.result.data;
            totalListMain.value = res.data.result.total;
            maxPageMain.value = Math.ceil(
              totalListMain.value / dataDetail.pageSize
            );
            if (apiData.length > 0) {
              checkCilck.value = false;
              rows.value = apiData.map((e: any) => ({
                profileId: e.profileId,
                cardId: e.citizenId,
                fullName: e.fullName,
                roundStart: e.startTimeMorning,
                roundEnd: e.leaveTimeAfterNoon,
                currentRound: `${e.startTimeMorning}-${e.leaveTimeAfterNoon}`,
                effectiveDate: e.effectiveDate
                  ? date2Thai(e.effectiveDate)
                  : "-",
              }));
            } else {
              rows.value = [];
              checkCilck.value = true;
            }
          })
          .catch((e) => {
            messageError($q, e);
          })
          .finally(() => {
            hideLoader();
          });
      }
    }
    const rows = ref<changeShow[]>([]);
    const rowsHistory = ref<historyShow[]>([]);
    // paging
    const page = ref<number>(1);
    const total = ref<number>(0);
    const pageSize = ref<number>(10);
    const maxPage = ref<number>(0);
    const filter = ref<string>(""); //search data table
    /**
     * ฟังก์ชั่น api เปลี่ยนหน้า
     * @param pageVal page
     * @param pageSizeVal pagesize
     */
    async function changePage(pageVal: number, pageSizeVal: number) {
      page.value = pageVal;
      pageSize.value = pageSizeVal;
      fetchDatainHistory();
    }
    /**ฟังก์ชั่นดึงดาต้าประวัติ */
    async function fetchDatainHistory() {
      rowsHistory.value = [];
      showLoader();
      await http
        .get(
          config.API.leaveRoundById(profileId.value) +
            `?page=${page.value}&pageSize=${pageSize.value}&keyword=${filter.value}`
        )
        .then((res) => {
          const dataHistory = res.data.result.data;
          dataHistory.map((e: DataInterface) => {
            rowsHistory.value.push({
              round: e.round,
              startTimeMorning: e.startTimeMorning,
              leaveTimeAfternoon: e.leaveTimeAfternoon,
              time: `${e.startTimeMorning}-${e.leaveTimeAfternoon}`,
              effectiveDate: date2Thai(e.effectiveDate),
              reson: e.remark ?? "-",
            });
            total.value = res.data.result.total;
            maxPage.value = Math.ceil(total.value / pageSize.value);
          });
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    }

    return {
      visibleColumns,
      columns,
      columnsHistory,
      rows,
      rowsHistory,
      fetchDatainHistory,
      visibleColumnsHistory,
      fetchDataForCardId,
      checkCilck,
      setProfileId,
      changePage,
      total,
      maxPage,
      page,
      pageSize,

      totalListMain,
      maxPageMain,
    };
  }
);
