<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import type { QTableProps } from "quasar";
import { useQuasar } from "quasar";
import type {
  DataOption,
  DataOption1,
} from "@/modules/05_placement/interface/index/Main";
import { useCounterMixin } from "@/stores/mixin";
import { usePlacementDataStore } from "@/modules/05_placement/store";
import router from "@/router";
import http from "@/plugins/http";
import config from "@/app.config";

const DataStore = usePlacementDataStore();
const $q = useQuasar();
const mixin = useCounterMixin();
const { showLoader, hideLoader, messageError, date2Thai } = mixin;

// หัวตาราง
const columns = ref<QTableProps["columns"]>([
  {
    name: "id",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "id",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "examRound",
    align: "left",
    label: "รอบการสอบ",
    sortable: true,
    field: "examRound",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "examOrder",
    align: "left",
    label: "ครั้งที่",
    sortable: true,
    field: "examOrder",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fiscalYear",
    align: "left",
    label: "ปีงบประมาณ",
    sortable: true,
    field: "fiscalYear",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "numberOfCandidates",
    align: "left",
    label: "จำนวนผู้สอบได้",
    sortable: false,
    field: "numberOfCandidates",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "examTypeName",
    align: "left",
    label: "ประเภทการสอบ",
    sortable: false,
    field: "examTypeName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "accountStartDate",
    align: "left",
    label: "วันที่บัญชีใช้ได้ตั้งแต่",
    sortable: true,
    field: "accountStartDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "accountExpirationDate",
    align: "left",
    label: "วันที่บัญชีใช้ได้ถึง",
    sortable: true,
    field: "accountExpirationDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
// ข้อมูลตาราง (จำลอง)
const rows = ref<QTableProps["rows"]>([]);
// const yearValue = ref<number>(0); // เพิ่มตัวแปรในโมดูล

// let OriginalData = ref<FormPlacementMainData[]>([]);
// let UpdataData = ref<FormPlacementMainData[]>([]);
const searchYear = ref();
const yearOptions = reactive<DataOption[]>([{ id: 0, name: "ทั้งหมด" }]);

const dataPlacement = ref<any>([]);
const visibleColumns = ref([
  "id",
  "examRound",
  "examOrder",
  "examOrder",
  "fiscalYear",
  "numberOfCandidates",
  "examTypeName",
  "accountStartDate",
  "accountExpirationDate",
]);

onMounted(async () => {
  await fetchYearOptions();
});
const fetchPlacementData = async (val: number) => {
  showLoader();
  rows.value = [];
  http
    .get(config.API.MainDetail(val))
    .then(async (res) => {
      dataPlacement.value = res.data.result;
      DataStore.DataMainOrig = dataPlacement.value;
      console.log(DataStore.DataMainOrig);

      // rows.value = DataStore.DataMainOrig;
      const dataArr: any = [];
      await DataStore.DataMainOrig.map((e: any) => {
        dataArr.push({
          id: e.id,
          examRound: e.examRound,
          examOrder: e.examOrder,
          examTypeName: e.examTypeName,
          examTypeValue: e.examTypeValue,
          accountEndDate: date2Thai(e.accountEndDate),
          accountExpirationDate: date2Thai(e.accountExpirationDate),
          accountStartDate: date2Thai(e.accountStartDate),
          fiscalYear: e.fiscalYear,
          numberOfCandidates: e.numberOfCandidates,
        });
      });

      rows.value = dataArr;

      examTypeFilter();
      examTimeFilter();
      expiredAccountFilter();
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      filterKeyword.value = "";
      examTime.value = "all"
      examType.value = "all"
      expiredAccount.value = false
      hideLoader();
    });
};

const fetchYearOptions = async () => {
  http
    .get(config.API.yearOptions())
    .then((res) => {
      const response = res.data.result;
      yearOptions.push(...response);
      const maxNumber = yearOptions.reduce((max: any, e: any) => {
        return e.id > max ? e.id : max;
      }, "");
      searchYear.value = maxNumber;
      DataStore.DataMainYearSet(searchYear.value);
      // DataStore.DataMainYear = yearOptions.value;
      fetchPlacementData(searchYear.value);
    })
    .catch((e) => {
      messageError($q, e);
    });
};
const filterYear = () => {
  // console.log("searchYear", searchYear.value);
  fetchPlacementData(searchYear.value);
};

// ดูรายการสอบแข่งขัน หน้าต่อไป
const redirectToPage = (examId?: number) => {
  router.push(`/placement/personal-list/${examId}`);
};

//-------------------|ค้นหาในตาราง|-----------------//
const filterKeyword = ref<string>("");
const filterRef = ref<any>(null);
const resetFilter = () => {
  filterKeyword.value = "";
  filterRef.value.focus();
};

//-------------------|ครั้งที่สอบ|------------------------------//
const examTime = ref<number | string>("all");
const examTimeOP = reactive<DataOption1[]>([{ id: "all", name: "ทั้งหมด" }]);
const addedExamTimeValues: Set<number> = new Set();

const examTimeFilter = async () => {
  // examTimeOP.push({ id: "all", name: "ทั้งหมด" });
  for (const data of dataPlacement.value) {
    const examOrder = data.examOrder;
    if (examOrder !== null && !addedExamTimeValues.has(examOrder)) {
      examTimeOP.push({ id: examOrder.toString(), name: examOrder.toString() });
      addedExamTimeValues.add(examOrder);
    }
  }
  examTimeOP.sort((a, b) => {
    if (a.id === "all") return -1; // ให้ตัวเลือก "ทั้งหมด" อยู่ด้านหน้า
    if (b.id === "all") return 1;
    return Number(a.id) - Number(b.id);
  }); // เรียงลำดับตาม id ที่แปลงเป็นตัวเลข
};

// ประเภทการสอบ
const examType = ref<string | null>("all");
const examTypeOP = ref<DataOption1[]>([{ id: "all", name: "ทั้งหมด" }]);
const addedExamTypeValues: Set<string> = new Set();
const examTypeFilter = () => {
  dataPlacement.value.forEach((item: any) => {
    const examTypeName = item.examTypeName;
    const examTypeValue = item.examTypeValue;
    if (examTypeName && !addedExamTypeValues.has(examTypeName)) {
      examTypeOP.value.push({
        id: examTypeValue,
        name: examTypeName,
      });
      addedExamTypeValues.add(examTypeName);
    }
  });
};
//--------------|ฟิลเตอร์|--------------------------------------//
const searchFilterTable = async () => {
  rows.value = [];
  if (examType.value !== undefined && examType.value !== null) {
    await DataStore.DataUpdateMain(
      examTime.value,
      examType.value,
      expiredAccount.value
    );

    const dataArr: any = [];
    await DataStore.DataMainUpdate.map((e: any) => {
      dataArr.push({
        id: e.id,
        examRound: e.examRound,
        examOrder: e.examOrder,
        examTypeName: e.examTypeName,
        examTypeValue: e.examTypeValue,
        accountEndDate: date2Thai(e.accountEndDate),
        accountExpirationDate: date2Thai(e.accountExpirationDate),
        accountStartDate: date2Thai(e.accountStartDate),
        fiscalYear: e.fiscalYear,
        numberOfCandidates: e.numberOfCandidates,
      });
    });
    rows.value = dataArr;
  }
};

//----------------|บัญชีหมดอายุ|-----------------------------//
const expiredAccount = ref<boolean>(false);
const expiredAccountFilter = async () => {
  // const currentDate = new Date();
  const updatedRows = dataPlacement.value.map((data: any) => {
    // let expirationDate = new Date(data.accountExpirationDate);
    // let isExpired = currentDate > expirationDate;
    let isExpired = data.isExpired == expiredAccount;

    return { ...data, isExpired };
  });
  await DataStore.DataMain(updatedRows);
};

const paging = ref<boolean>(true);
const pagination = ref({
  sortBy: "accountStartDate",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});
const paginationLabel = (start: number, end: number, total: number) => {
  if (paging.value == true) return " " + start + "-" + end + " ใน " + total;
  else return start + "-" + end + " ใน " + total;
};
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการสอบแข่งขัน / คัดเลือก
  </div>
  <q-card flat bordered class="col-12 q-mt-sm q-pa-md">
    <div class="row q-col-gutter-sm">
      <div class="row col-12 q-col-gutter-sm">
        <q-select
          class="col-xs-12 col-sm-3 col-md-2"
          v-model="searchYear"
          label="ปีงบประมาณ"
          dense
          emit-value
          map-options
          :options="yearOptions"
          option-value="id"
          option-label="name"
          lazy-rules
          hide-bottom-space
          :readonly="false"
          :borderless="false"
          :outlined="true"
          :hide-dropdown-icon="false"
          @update:model-value="filterYear"
        />
        <q-space />
        <q-input
          class="col-xs-12 col-sm-3 col-md-2"
          standout
          dense
          v-model="filterKeyword"
          ref="filterRef"
          outlined
          debounce="300"
          placeholder="ค้นหา"
        >
          <template v-slot:append>
            <q-icon v-if="filterKeyword == ''" name="search" />
            <q-icon
              v-if="filterKeyword !== ''"
              name="clear"
              class="cursor-pointer"
              @click="resetFilter"
            />
          </template>
        </q-input>
        <q-select
          class="col-xs-12 col-sm-3 col-md-2"
          v-model="visibleColumns"
          multiple
          outlined
          dense
          options-dense
          :display-value="$q.lang.table.columns"
          emit-value
          map-options
          :options="columns"
          option-value="name"
          options-cover
        />
      </div>
      <div class="col-12">
        <q-card bordered class="col-12 filter-card q-pa-sm">
          <div class="row col-12 q-col-gutter-sm">
            <q-select
              class="col-xs-12 col-sm-3 col-md-2"
              v-model="examTime"
              label="ครั้งที่"
              dense
              emit-value
              map-options
              :options="examTimeOP"
              option-value="id"
              option-label="name"
              lazy-rules
              hide-bottom-space
              :readonly="false"
              :borderless="false"
              :outlined="true"
              :hide-dropdown-icon="false"
              @update:model-value="searchFilterTable"
            />
            <q-select
              class="col-xs-12 col-sm-3 col-md-2"
              v-model="examType"
              label="ประเภทการสอบ"
              dense
              emit-value
              map-options
              option-label="name"
              :options="examTypeOP"
              option-value="id"
              lazy-rules
              hide-bottom-space
              :readonly="false"
              :borderless="false"
              :outlined="true"
              :hide-dropdown-icon="false"
              @update:model-value="searchFilterTable"
            />
            <q-toggle
              class="col-xs-12 col-sm-5 col-md-5 toggle-expired-account"
              v-model="expiredAccount"
              color="blue"
              label="แสดงบัญชีหมดอายุ"
              @update:model-value="searchFilterTable"
            />
          </div>
        </q-card>
      </div>
      <div class="col-12">
        <q-table
          ref="table"
          :rows="rows"
          :columns="columns"
          :filter="filterKeyword"
          row-key="id"
          flat
          bordered
          dense
          class="custom-header-table"
          :visible-columns="visibleColumns"
          :pagination-label="paginationLabel"
          v-model:pagination="pagination"
        >
          <template v-slot:pagination="scope">
            <q-pagination
              v-model="pagination.page"
              active-color="primary"
							color="dark"
              :max="scope.pagesNumber"
              :max-pages="5"
              size="sm"
              boundary-links
              direction-links
            ></q-pagination>
          </template>
          <template v-slot:body="props">
            <q-tr
              :props="props"
              class="cursor-pointer"
              @click="redirectToPage(props.row.id)"
            >
              <q-td key="id" :props="props">
                {{ props.rowIndex + 1 }}
              </q-td>
              <q-td key="examRound" :props="props">
                {{ props.row.examRound }}
              </q-td>
              <q-td key="examOrder" :props="props">
                {{ props.row.examOrder }}
              </q-td>
              <q-td key="fiscalYear" :props="props">
                {{ props.row.fiscalYear }}
              </q-td>
              <q-td key="numberOfCandidates" :props="props">
                {{ props.row.numberOfCandidates }}
              </q-td>
              <q-td key="examTypeName" :props="props">
                {{ props.row.examTypeName }}
              </q-td>
              <q-td key="accountStartDate" :props="props">
                {{ props.row.accountStartDate }}
              </q-td>
              <q-td key="accountExpirationDate" :props="props">
                {{ props.row.accountExpirationDate }}
              </q-td>
            </q-tr>
          </template>
        </q-table>
      </div>
    </div>
  </q-card>
</template>

<style lang="scss" scope>
.filter-card {
  background-color: #f1f1f1b0;
}

.toggle-expired-account {
  font-size: 12px;
  font-weight: 400;
  font-size: 15px;
  line-height: 150%;
  color: #35373c;
}

.icon-color {
  color: #4154b3;
}

.custom-header-table {
  max-height: 64vh;

  .q-table tr:nth-child(odd) td {
    background: white;
  }

  .q-table tr:nth-child(even) td {
    background: #f8f8f8;
  }

  .q-table thead tr {
    background: #ecebeb;
  }

  .q-table thead tr th {
    position: sticky;
    z-index: 1;
  }

  /* this will be the loading indicator */
  .q-table thead tr:last-child th {
    /* height of all previous header rows */
    top: 48px;
  }

  .q-table thead tr:first-child th {
    top: 0;
  }
}
</style>
