<script setup lang="ts">
import { onMounted, reactive, ref, useAttrs } from 'vue';
import type { QTableProps } from 'quasar';
import type { FormPlacementMainData } from  "@/modules/05_placement/interface/request/Main";
import type { DataOption } from "@/modules/05_placement/interface/index/Main";
import { useCounterMixin } from "@/stores/mixin";
import { usePlacementDataStore } from "@/modules/05_placement/store";
import router from '@/router';

const DataStore = usePlacementDataStore()

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

// แปลงเวลา ค.ศ ให้เป็น พ.ศ
const textDate = (value: Date) => {
  return dateText(value);
};

// หัวตาราง
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: "ExamType",
    align: "left",
    label: "ประเภทการสอบ",
    sortable: false,
    field: "ExamType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "AccountExpirationDate",
    align: "left",
    label: "วันที่บัญชีหมดอายุ",
    sortable: true,
    field: "AccountExpirationDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },

]);

// ข้อมูลตาราง (จำลอง)
const rows = ref<FormPlacementMainData[]>([{
  id: 1,
  ExamRound: "การสอบแข่งขันเพื่อรับบุคคลทั่วไปเข้ารับราชการ ส่วนการจัดการทั่วไป",
  ExamOrder: 3,
  FiscalYear: 2023,
  NumberofCandidates: 8,
  ExamType: 1,
  AccountExpirationDate: "2023-02-28T14:47:04.1785384Z"
},
{
  id: 2,
  ExamRound: "การสอบแข่งขันเพื่อรับบุคคลทั่วไปเข้ารับราชการ ส่วนการจัดการทั่วไป",
  ExamOrder: 2,
  FiscalYear: 2023,
  NumberofCandidates: 12,
  ExamType: 1,
  AccountExpirationDate: "2023-02-28T14:47:04.1785384Z"
},
{
  id: 3,
  ExamRound: "การสอบแข่งขันเพื่อรับบุคคลทั่วไปเข้ารับราชการ ส่วนการจัดการทั่วไป",
  ExamOrder: 2,
  FiscalYear: 2023,
  NumberofCandidates: 20,
  ExamType: 1,
  AccountExpirationDate: "2023-01-31T14:47:04.1785384Z"
},
{
  id: 4,
  ExamRound: "การสอบแข่งขันเพื่อรับบุคคลทั่วไปเข้ารับราชการ ส่วนการจัดการทั่วไป",
  ExamOrder: 2,
  FiscalYear: 2022,
  NumberofCandidates: 16,
  ExamType: 2,
  AccountExpirationDate: "2023-11-30T14:47:04.1785384Z"
},
{
  id: 5,
  ExamRound: "การสอบแข่งขันเพื่อรับบุคคลทั่วไปเข้ารับราชการ ส่วนการจัดการทั่วไป",
  ExamOrder: 1,
  FiscalYear: 2021,
  NumberofCandidates: 20,
  ExamType: 2,
  AccountExpirationDate: "2024-05-21T14:47:04.1785384Z",
},
]);

let OriginalData = ref<FormPlacementMainData[]>([]);
let UpdataData = ref<FormPlacementMainData[]>([]);

const OriginalDataFetch = async () => {
  await DataStore.DataMain(rows.value)
  OriginalData.value = await DataStore.DataMainOrig
  UpdataData.value = OriginalData.value
}

onMounted( async () => {
 await OriginalDataFetch()
  fiscalyearfilter()
  examTimefilter()
  examTypefilter()
})

// ดูรายการสอบแข่งขัน หน้าต่อไป
const redirectToPage = (id:number) => {
  router.push({
      name: 'placementDetail',
      params: {
        id: id 
      }
    });
};

// เลือกปีงบประมาณ
const fiscalyear = ref<number | null>(0);
const fiscalyearOP = reactive<DataOption[]>([{id: 0, name: 'ทั้งหมด'}]);
  const addedFiscalYearValues: number[] = [];
const fiscalyearfilter = async () => {
  for (let data of OriginalData.value) {
    const year = data.FiscalYear + 543;
    if (!addedFiscalYearValues.includes(year)) {
        fiscalyearOP.push({ id: year, name: year.toString() });
        addedFiscalYearValues.push(year);
    }
  }
}

// เลือกปีงบประมาณตาม API
const searchFiscalyear = () => {
  // API
  console.log('Input value changed:', fiscalyear.value);
};

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

const attrs = ref<any>(useAttrs());
const visibleColumns = ref<string[]>([ 'id', 'ExamRound', 'ExamOrder', 'FiscalYear', 'NumberofCandidates', 'ExamType', 'AccountExpirationDate']) //ค้นหา คอลัมน์ คอลัมน์ที่แสดง

// ครั้งที่สอบ
const examTime = ref<number | null>(null);
const examTimeOP = ref<number[]>([]);
const examTimefilter = async () => {
    for (let data of OriginalData.value) {
      if (!examTimeOP.value.includes(data.ExamOrder)) {
        examTimeOP.value.push(data.ExamOrder);
      }
  }
  examTimeOP.value.sort((a, b) => a - b); // เรียงลำดับ
}

// แสดงครั้งที่สอบตามที่เลือก
const searchExamTime = async () => {
  if (examTime.value !== null) {
    const selectExamTime = OriginalData.value.filter((data: { ExamOrder: number | null; }) => data.ExamOrder === examTime.value);
    await DataStore.DataUpdateMain(selectExamTime);
    UpdataData.value = DataStore.DataMainUpdate
  } else {
    OriginalDataFetch();
  }
};

// ประเภทการสอบ
const examType = ref<number | null>(0); 
const examTypeOP = reactive<DataOption[]>([{ id: 0, name: "ทั้งหมด" }]);
const addedExamTypeValues: number[] = [];
const examTypefilter = async () => {
  for (let data of OriginalData.value) {
    const examTypeValue = data.ExamType;
    if (examTypeValue == 1 && !addedExamTypeValues.includes(1)) {
      examTypeOP.push({ id: 1, name: "คัดเลือก" });
      addedExamTypeValues.push(1);
    } else if (examTypeValue == 2 && !addedExamTypeValues.includes(2)) {
      examTypeOP.push({ id: 2, name: "สอบแข่งขัน" });
      addedExamTypeValues.push(2);
    }
  }
}

// แสดงประเภทการสอบตามที่เลือก
const searchExamType = async () => {
  if (examType.value !== null) {
    const selectExamType = OriginalData.value.filter((data: { ExamType: number | null; }) => {
      if (examType.value === 0) {
        OriginalDataFetch();
        return data.ExamType === 1 || data.ExamType === 2;
      } else {
        return data.ExamType === examType.value;
      }
    });
    await DataStore.DataUpdateMain(selectExamType);
    UpdataData.value = DataStore.DataMainUpdate
  }
};

// บัญชีหมดอายุ
const expiredAccount = ref<boolean>(false); 
const searchExpiredAccount = async () => {
  const currentDate = new Date();
  const updatedRows = OriginalData.value.map((data) => {
    let expirationDate = new Date(data.AccountExpirationDate);
    let isExpired = expirationDate < currentDate;

    return { ...data, isExpired };
  });
  if (expiredAccount.value) {
    const expiredRows = updatedRows.filter((data) => data.isExpired);
    await DataStore.DataUpdateMain(expiredRows);
    UpdataData.value = DataStore.DataMainUpdate
  } else {
    OriginalDataFetch();
  }
};

const paging = ref<boolean>(true);
const paginationLabel = (start: string, end: string, total: string) => {
    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>
  <div>
    <q-card flat bordered class="col-12 q-mt-sm"> 
      <div class="row q-pa-md" >
        <div class="col-xs-12 col-sm-3 col-md-2">
          <q-select
                v-model="fiscalyear"
                label="ปีงบประมาณ"
                dense
                clearable 
                emit-value
                map-options
                :options="fiscalyearOP"
                option-value="id"
                option-label="name"
                lazy-rules
                hide-bottom-space
                :readonly="false"
                :borderless="false"
                :outlined="true"
                :hide-dropdown-icon="false"
                @update:model-value="searchFiscalyear"
              />
        </div>
        <div class="col-xs-12 col-sm-3 col-md-6"></div>
        <div class="col-xs-12 col-sm-3 col-md-2">
          <q-input
            standout
            dense
            v-model="filterKeyword"
            ref="filterRef"
            outlined
            debounce="300"
            placeholder="ค้นหา"
            class="q-ml-sm"
          >
            <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>
        </div>
        <div class="col-xs-12 col-sm-3 col-md-2">
          <q-select
            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
            style="min-width: 150px"
            class="gt-xs q-ml-sm"
          />
        </div>
      </div>
      <div class="q-pt-sm q-pl-md q-pr-md q-pb-md">
        <q-card bordered class="col-12 filter-card">
          <div class="row q-pa-sm">
            <div class="col-xs-12 col-sm-3 col-md-2 q-pl-sm">
              <q-select
                  v-model="examTime"
                  label="ครั้งที่"
                  dense
                  clearable 
                  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="searchExamTime"
                />
            </div>
            <div class="col-xs-12 col-sm-3 col-md-2 q-pl-sm">
              <q-select
                  v-model="examType"
                  label="ประเภทการสอบ"
                  dense
                  clearable 
                  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="searchExamType"
                />
            </div>
            <div class="col-xs-12 col-sm-3 col-md-3">
              <q-toggle
                v-model="expiredAccount"
                class="toggle-expired-account"
                color="blue" 
                label="แสดงบัญชีหมดอายุ"
                @update:model-value="searchExpiredAccount"
              />
            </div>
          </div>
        </q-card>
      </div>
      <div class="q-pt-sm q-pl-md q-pr-md q-pb-md">
        <q-table
          ref="table"
          :columns="columns" 
          :rows="UpdataData" 
          :filter="filterKeyword"
          row-key="id"
          flat
          bordered
          dense
          class="custom-header-table"
          v-bind="attrs"
          :visible-columns="visibleColumns"
          :pagination-label="paginationLabel"
        >
        <template v-slot:body="props" >
          <q-tr :props="props" class="cursor-pointer" @click="redirectToPage(props.row.id)">
            <q-td key="id" :props="props">
                {{ props.row.id }}
            </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 + 543 }}
            </q-td>
            <q-td key="NumberofCandidates" :props="props">
                {{ props.row.NumberofCandidates }}
            </q-td>
            <q-td key="ExamType" :props="props">
                {{ props.row.ExamType == 1 ? 'คัดเลือก' : 'สอบแข่งขัน' }}
            </q-td>
            <q-td key="AccountExpirationDate" :props="props">
                {{ textDate(props.row.AccountExpirationDate) }}
            </q-td>
          </q-tr>
        </template>
      </q-table>
      </div>
    </q-card>
  </div>
</template>

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

.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>
