<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

/** importType*/
import type { QTableColumn } from "quasar";
import type { DataOption } from "@/modules/04_registryNew/interface/index/Main";
import type { DataPerson } from "@/modules/04_registryNew/interface/response/Main";
import type { FormFilter } from "@/modules/04_registryNew/interface/request/Main";

/** importComponents*/
import TableView from "@/modules/04_registryNew/components/TableView.vue";

/** importStore*/
import { useRegistryNewDataStore } from "@/modules/04_registryNew/store";
import { useCounterMixin } from "@/stores/mixin";

const $q = useQuasar();
const store = useRegistryNewDataStore();
const { showLoader, hideLoader, messageError } = useCounterMixin();

const mode = ref<"table" | "card">("table");

const isShowFilter = ref<boolean>(false);
const isShowBtnFilter = ref<boolean>(true);
const empType = ref<string>("officer"); // ประเภท ขรก./ลูกจ้างประจำ/ลูกจ้างชั่วคราว
const labelOption = reactive({
  type: "ข้าราชการ กทม.สามัญ",
  posType: "ทั้งหมด",
  posLevel: "ทั้งหมด",
  retireYear: "",
});

const searchType = ref<string>("fullName");
const formFilter = reactive<FormFilter>({
  page: 1,
  pageSize: 12,
  keyword: "",
  type: "",
  posType: "",
  posLevel: "",
  retireYear: "",
  rangeYear: { min: 0, max: 60 },
  isShowRetire: null,
  isProbation: null,
});
const maxPage = ref<number>(1);

const dataPersonMain = ref<DataPerson[]>([]);

const conditionTotal = computed(() => {
  let num: string = "";
  if (formFilter.isProbation && formFilter.isShowRetire) {
    num = "(2)";
  } else if (formFilter.isProbation || formFilter.isShowRetire) {
    num = "(1)";
  } else "";

  return num;
});

/** function เรียกข้อมูลประเภทตำแหน่ง*/
function fetchType() {
  if (store.posTypeOps.length === 0) {
    http
      .get(config.API.orgPosType)
      .then((res) => {
        store.fetchType(res.data.result);
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

/** function เรียกข้อมูลระดับตำแหน่ง*/
function fetchLevel() {
  if (store.posLevelOps.length === 0) {
    http
      .get(config.API.orgPosLevel)
      .then((res) => {
        store.fetchLevel(res.data.result);
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

function fetchYearOption() {
  if (store.yearOps.length === 0) {
    const options = [];
    const year = new Date().getFullYear();

    for (let i = year - 40; i <= year + 60; i++) {
      options.push({ id: i.toString(), name: (i + 543).toString() });
    }
    if (options) {
      store.yearOps.push(...options);
    }
  }
}

const total = ref<number>(0);
async function fetchDataPerson(search: boolean = false) {
  showLoader();

  let queryParams: any = {
    page: formFilter.page,
    pageSize: formFilter.pageSize,
  };

  if (search) {
    queryParams = Object.assign({}, queryParams, {
      searchField: searchType.value,
      searchKeyword: formFilter.keyword,
    });
  }

  if (labelOption.posLevel != "ทั้งหมด") {
    queryParams = Object.assign({}, queryParams, {
      posLevel: labelOption.posLevel,
    });
  }

  if (labelOption.posType != "ทั้งหมด") {
    queryParams = Object.assign({}, queryParams, {
      posType: labelOption.posType,
    });
  }

  if (formFilter.isProbation != null) {
    queryParams.isProbation = formFilter.isProbation;
  }

  if (formFilter.isShowRetire != null) {
    queryParams.isRetire = formFilter.isShowRetire;
  }

  // check type person empType.value
  http
    .get(config.API.registryNew, { params: queryParams })
    .then((res) => {
      maxPage.value = Math.ceil(res.data.result.total / formFilter.pageSize);
      dataPersonMain.value = res.data.result.data;
      total.value = res.data.result.total;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      // setTimeout(() => {
      hideLoader();
      // }, 500);
    });
}

function onClickShowFilter() {
  isShowFilter.value = !isShowFilter.value;
  isShowBtnFilter.value = false;
  if (isShowFilter.value) {
    fetchType();
    fetchLevel();
    fetchYearOption();
  }
}

function onclickSearch() {
  isShowFilter.value = true;
  isShowBtnFilter.value = false;
  if (isShowFilter.value) {
    fetchType();
    fetchLevel();
    fetchYearOption();
  }
  formFilter.keyword = formFilter.keyword === null ? "" : formFilter.keyword;
  fetchDataPerson(true);
}

function selectType(item: DataOption) {
  labelOption.type = item.name;
  empType.value = item.id;
  fetchDataPerson();
}

function selectPosType(item: DataOption) {
  labelOption.posType = item.name;
  fetchDataPerson();
}

function selectPosLevel(item: DataOption) {
  labelOption.posLevel = item.name;
  fetchDataPerson();
}

function selectRetireYear(item: DataOption) {
  labelOption.retireYear = item.name;
}

function clearSelect(t: string) {
  if (t === "posType") {
    labelOption.posType = "ทั้งหมด";
  } else if (t === "posLevel") {
    labelOption.posLevel = "ทั้งหมด";
  } else if (t === "retireYear") {
    labelOption.retireYear = "";
  } else if (t === "rangeYear") {
    formFilter.rangeYear.min = 0;
    formFilter.rangeYear.max = 60;
  }

  fetchDataPerson();
}

onMounted(async () => {
  fetchDataPerson();
});
</script>
<template>
  <!-- <div class="toptitle text-dark col-12 row items-center">
    ข้อมูลทะเบียนประวัติ
  </div> -->

  <q-card class="q-mt-md ">
    <q-card-section class="card-img q-pb-lg">
      <div class="text-h5 text-center q-py-md text-weight-medium">
        ค้นหาข้อมูลทะเบียนประวัติ
      </div>
      <div class="row justify-center">
        <div
          class="col-xs-12 col-sm-12 col-md-11 q-pa-md bg-Search rounded-borders"
        >
          <q-form @submit="onclickSearch">
            <div class="bg-white row col-12 q-pa-none rounded-borders">
              <div class="row col-11">
                <div class="col-3 row wrap">
                  <q-select
                    borderless
                    bg-color="white"
                    v-model="searchType"
                    :options="store.searchTypeOption"
                    emit-value
                    dense
                    emit-option
                    option-label="name"
                    option-value="id"
                    map-options
                    class="selectS col-11 q-px-md"
                    color="deep-orange"
                    dropdown-icon="mdi-chevron-down"
                  />
                  <q-separator vertical />
                </div>
                <q-input
                  borderless
                  dense
                  bg-color="white"
                  v-model="formFilter.keyword"
                  clearable
                  placeholder="ค้นหา"
                  class="col-9 q-pr-md"
                  @clear="fetchDataPerson"
                >
                  <template v-slot:before>
                    <q-icon name="search" color="deep-orange" />
                  </template>
                </q-input>
              </div>
              <div class="row col-1">
                <q-btn
                  class="fit btnSearch"
                  unelevated
                  color="deep-orange"
                  label="ค้นหา"
                  type="submit"
                />
              </div>
            </div>
          </q-form>
          <div v-if="isShowBtnFilter" class="col-12 row q-mt-sm">
            <q-space />
            <q-btn
              flat
              label="ตัวเลือกเพิ่มเติม"
              icon-right="mdi-tune"
              @click="onClickShowFilter"
              dense
              class="q-px-sm"
            ></q-btn>
          </div>

          <div
            class="row q-mt-sm q-gutter-sm justify-center"
            v-if="isShowFilter"
          >
            <q-btn-dropdown
              flat
              rounded
              dense
              label-color="white"
              dropdown-icon="mdi-chevron-down"
              class="q-px-sm"
            >
              <template v-slot:label>
                {{ `${labelOption.type}` }}

                <!-- <q-btn
                  size="10px"
                  flat
                  round
                  color="white"
                  icon="close"
                  v-if="labelOption.type !== 'ประเภททั้งหมด'"
                  @click.stop.prevent="clearSelect('type')"
                /> -->
              </template>
              <q-list>
                <q-item
                  v-for="(item, index) in store.employeeClassOps"
                  :key="index"
                  clickable
                  v-close-popup
                  @click="selectType(item)"
                >
                  <q-item-section>
                    <q-item-label>{{ item.name }}</q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown>

            <q-separator inset vertical class="lineFil" />

            <q-btn-dropdown
              rounded
              flat
              dense
              label-color="white"
              dropdown-icon="mdi-chevron-down"
              class="q-px-sm"
              ><!-- class="custom-btn" -->
              <template v-slot:label>
                {{
                  labelOption.posType !== "ทั้งหมด"
                    ? labelOption.posType
                    : `ประเภทตำแหน่ง${labelOption.posType}`
                }}
                <q-btn
                  size="10px"
                  flat
                  round
                  color="white"
                  icon="close"
                  v-if="labelOption.posType !== 'ทั้งหมด'"
                  @click.stop.prevent="clearSelect('posType')"
                />
              </template>
              <q-list>
                <q-item
                  v-for="(item, index) in store.posTypeOps"
                  :key="index"
                  clickable
                  v-close-popup
                  @click="selectPosType(item)"
                >
                  <q-item-section>
                    <q-item-label>{{ item.name }}</q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown>

            <q-separator inset vertical class="lineFil" />

            <q-btn-dropdown
              flat
              dense
              rounded
              label-color="white"
              dropdown-icon="mdi-chevron-down"
              class="q-px-sm"
              ><!-- class="custom-btn" -->
              <template v-slot:label>
                {{
                  labelOption.posLevel !== "ทั้งหมด"
                    ? labelOption.posLevel
                    : `ระดับตำแหน่ง${labelOption.posLevel}`
                }}
                <q-btn
                  size="10px"
                  flat
                  round
                  color="white"
                  icon="close"
                  v-if="labelOption.posLevel !== 'ทั้งหมด'"
                  @click.stop.prevent="clearSelect('posLevel')"
                />
              </template>
              <q-list style="height: 300px">
                <q-item
                  v-for="(item, index) in store.posLevelOps"
                  :key="index"
                  clickable
                  v-close-popup
                  @click="selectPosLevel(item)"
                >
                  <q-item-section>
                    <q-item-label>{{ item.name }}</q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown>

            <q-separator inset vertical class="lineFil" />

            <!-- <q-btn-dropdown
              flat
              dense
              rounded
              label-color="white"
              dropdown-icon="mdi-chevron-down"
              class="q-px-sm"
              >
              <template v-slot:label>
                {{ `ปีเกษียณ${labelOption.retireYear}` }}
                <q-btn
                  size="10px"
                  flat
                  round
                  color="white"
                  icon="close"
                  v-if="labelOption.retireYear !== ''"
                  @click.stop.prevent="clearSelect('retireYear')"
                />
              </template>
              <q-list style="height: 300px">
                <q-item
                  v-for="(item, index) in store.yearOps"
                  :key="index"
                  clickable
                  v-close-popup
                  @click="selectRetireYear(item)"
                >
                  <q-item-section>
                    <q-item-label>{{ item.name }}</q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown> -->

            <!-- <q-separator inset vertical class="lineFil" /> -->

            <!-- <datepicker
              menu-class-name="modalfix"
              v-model="formFilter.retireYear"
              :locale="'th'"
              autoApply
              year-picker
              :enableTimePicker="false"
              clearable
              style="width: 120px"
            >
              <template #year="{ year }">{{ year + 543 }}</template>
              <template #year-overlay-value="{ value }">{{
                parseInt(value + 543)
              }}</template>
              <template #trigger>
                <q-input
                  class="cursor-pointer custom-select"
                  rounded
                  label-color="white"
                  outlined
                  dense
                  input-style="color:white;"
                  borderless
                  :model-value="
                    formFilter.retireYear === null
                      ? null
                      : formFilter.retireYear + 543
                  "
                  :label="`${'ปีเกษียณ'}`"
                >
                  <template v-slot:append>
                    <q-btn
                      size="10px"
                      flat
                      round
                      color="white"
                      icon="close"
                      v-if="formFilter.retireYear !== null"
                      @click.stop.prevent="clearSelect('retireYear')"
                    />
                  </template>
                </q-input>
              </template>
            </datepicker> -->

            <!-- <q-btn-dropdown
              flat
              dense
              rounded
              label-color="white"
              dropdown-icon="mdi-chevron-down"
              class="q-px-sm"
              >
              <template v-slot:label>
                {{
                  `อายุราชการ (${formFilter.rangeYear.min} - ${formFilter.rangeYear.max} ปี)`
                }}
                <q-btn
                  size="10px"
                  flat
                  round
                  color="white"
                  icon="close"
                  v-if="
                    formFilter.rangeYear.min !== 0 ||
                    formFilter.rangeYear.max !== 60
                  "
                  @click.stop.prevent="clearSelect('rangeYear')"
                />
              </template>
              <div class="row justify-center">
                <div class="col-12 q-pa-md text-center">
                  <div>
                    <span>จำนวนปี</span>
                    <q-badge
                      color="grey-4"
                      text-color="black"
                      class="q-ml-sm"
                      :label="`${formFilter.rangeYear.min}-${formFilter.rangeYear.max}`"
                    />
                  </div>
                  <div class="q-mt-lg">
                    <q-range
                      v-model="formFilter.rangeYear"
                      :min="0"
                      :max="60"
                      :step="1"
                      label
                      color="primary"
                      selection-color="blue"
                      label-color="primary"
                      thumb-color="blue"
                    />
                  </div>
                </div>
              </div>
            </q-btn-dropdown> -->

            <!-- <q-separator inset vertical class="lineFil" /> -->

            <q-btn-dropdown
              flat
              dense
              rounded
              label-color="white"
              dropdown-icon="mdi-chevron-down"
              :label="`เงื่อนไขอื่นๆ  ${conditionTotal}`"
              class="q-px-sm"
              ><!-- class="custom-btn" -->
              <q-list>
                <q-item clickable v-close-popup>
                  <q-item-section>
                    <q-toggle
                      v-model="formFilter.isProbation"
                      color="primary"
                      label="ทดลองปฏิบัติหน้าที่ราชการ"
                      @update:model-value="fetchDataPerson"
                    />
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup>
                  <q-item-section>
                    <q-toggle
                      v-model="formFilter.isShowRetire"
                      color="primary"
                      label="แสดงข้อมูลผู้พ้นจากราชการ"
                      @update:model-value="fetchDataPerson"
                    />
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown>
          </div>
        </div>
      </div>
    </q-card-section>

    <q-separator />

    <q-card-section>
      <TableView
        v-model:mode="mode"
        :rows="dataPersonMain"
        v-model:formFilter="formFilter"
        v-model:maxPage="maxPage"
        :fetchData="fetchDataPerson"
        :fetchType="fetchType"
        :total="total"
      />
    </q-card-section>
  </q-card>
</template>

<style scoped>
.card-img {
  background: url("@/assets/registry-banner.png");
  background-size: cover;
  color: white;
}

:deep(.custom-select.q-field--outlined .q-field__control) {
  color: white;
  background-color: #36969f;
}
:deep(.custom-select.q-field--outlined .q-field__control::before) {
  border: 1px solid #fff;
}

:deep(.custom-btn.q-btn--outline::before) {
  background-color: #36969f;
}

.btnSearch {
  border-radius: 0px 4px 4px 0px;
}
.bg-Search {
  background: #00000015;
}
.lineFil {
  transform: rotate(30deg);
  height: 20px;
  margin-top: 15px;
  background: #ffffff7b !important;
}
.selectS .q-field__control .q-field__append .q-icon {
  color: #ff5722 !important;
}
</style>
