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

/** importType*/
import type { DataOption } from "@/modules/04_registryPerson/interface/index/Main";
import type {
  DataPerson,
  DataType,
} from "@/modules/04_registryPerson/interface/response/Main";

/** importComponents*/
import TableView from "@/modules/04_registryPerson/components/TableView.vue";
import avatar from "@/assets/avatar_user.jpg";
import DialogHeader from "@/components/DialogHeader.vue";

/** importStore*/
import { useRegistryNewDataStore } from "@/modules/04_registryPerson/store";
import { useCounterMixin } from "@/stores/mixin";
import { useRoute } from "vue-router";

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

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

const isShowFilter = ref<boolean>(true);
const isShowBtnFilter = ref<boolean>(false);
const empType = ref<string>("officer"); // officer / employee / perm

const searchType = ref<string>("fullName");

const maxPage = ref<number>(1);
const total = ref<number>(0);
const selectNode = ref<boolean>(false);

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

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

  return num;
});

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

/**
 * function เรียกข้อมูลกลุ่มงาน
 */
function fetchOptionGroup() {
  http
    .get(config.API.orgEmployeeType)
    .then((res) => {
      store.fetchType(res.data.result);
    })
    .catch((err) => {
      messageError($q, err);
    });
}

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);
    }
  }
}

/**
 * function fetch รายชื่อข้อมูลทะเบียนประวัติ
 */
function fetchDataPerson() {
  showLoader();
  let queryParams: any = {
    page: store.formFilter.page,
    pageSize: store.formFilter.pageSize,
  };

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

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

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

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

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

  if (empType.value !== "officer") {
    queryParams.type = empType.value;
  }

  http
    .get(
      config.API.registryNew(empType.value !== "officer" ? "-employee" : ""),
      { params: queryParams }
    )
    .then((res) => {
      maxPage.value = Math.ceil(
        res.data.result.total / store.formFilter.pageSize
      );
      dataPersonMain.value = res.data.result.data;
      total.value = res.data.result.total;
      isShowBtnFilter.value = true;
      insertAvatar(res.data.result.data);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function fetch รูปโปรไฟล์
 * @param items ข้อมูลคน
 */
function insertAvatar(items: DataPerson[]) {
  items.map((x: any, index: number) => {
    if (x.avatarName != null) {
      http
        .get(
          config.API.fileByFile("ทะเบียนประวัติ", "โปรไฟล์", x.id, x.avatarName)
        )
        .then((img) => {
          dataPersonMain.value[index] = {
            ...x,
            avatar: img.data.downloadUrl,
          };
        })
        .catch(() => {
          dataPersonMain.value[index] = {
            ...x,
            avatar: avatar,
          };
        });
    } else {
      dataPersonMain.value[index] = {
        ...x,
        avatar: avatar,
      };
    }
  });
}

/**
 * funciotn แสดงตัวเลือกเพิ่มเติม
 */
// function onClickShowFilter() {
//   isShowFilter.value = !isShowFilter.value;
//   isShowBtnFilter.value = false;
//   if (isShowFilter.value) {
//     // fetchLevel();
//     fetchYearOption();
//   }
// }

/**
 * funciotn ค้นหาข้อมูล
 */
function onclickSearch() {
  isShowFilter.value = true;
  // isShowBtnFilter.value = false;
  store.formFilter.page = 1;
  if (isShowFilter.value) {
    fetchType();
    // fetchLevel();
    fetchYearOption();
  }
  store.formFilter.keyword =
    store.formFilter.keyword === null ? "" : store.formFilter.keyword;
  fetchDataPerson();
}

/**
 * function เลือกประเภทข้าราชการ
 * @param item ประเภทข้าราชการ
 */
async function selectType() {
  empType.value = await (route.name == "registryNew" ? "officer" : "perm");

  if (empType.value !== "officer") {
    store.formFilter.isShowRetire = null;
    store.formFilter.isProbation = null;
    fetchOptionGroup();
  } else {
    fetchType();
  }

  // เช็ค store ถ้าเปลี่ยนประเภททะเบียนประวัติ ให้ล่างค่า filter ใหม่
  if (store.formFilter.type != empType.value) {
    store.labelOption.posType = "ทั้งหมด";
    store.labelOption.posLevel = "ทั้งหมด";
    store.formFilter.type = empType.value;
  } else {
    // แต่ถ้าประเภทเดิมระบบจะใช้ filter เดิมที่เคยค้นหาไว้
    if (
      store.formFilter.keyword != "" ||
      store.labelOption.posType != "ทั้งหมด" ||
      store.labelOption.posLevel != "ทั้งหมด" ||
      store.formFilter.isShowRetire != null ||
      store.formFilter.isProbation != null
    ) {
      store.formFilter.page = 1;
      fetchDataPerson();
    }
  }
}

/**
 * function เลือกประเภทตำแหน่ง
 * @param item ประเภทตำแหน่ง
 */
function selectPosType(item: DataOption) {
  const dataType = store.posTypeMain.find((e: DataType) => e.id === item.id);
  store.fetchLevel(dataType?.posLevels);
  store.labelOption.posType = item.name;
  store.labelOption.posLevel = "ทั้งหมด";
  store.formFilter.page = 1;
  fetchDataPerson();
}

/**
 * function เลือกประเภทตำแหน่ง
 * @param item ประเภทระดับ
 */
function selectPosLevel(item: DataOption) {
  store.labelOption.posLevel = item.name;
  store.formFilter.page = 1;
  fetchDataPerson();
}

/**
 * function เคลีย์ตัวเลือก
 * @param t ประเภทตัวเลือก
 */
function clearSelect(t: string) {
  if (t === "posType") {
    store.labelOption.posType = "ทั้งหมด";
    store.labelOption.posLevel = "ทั้งหมด";
  } else if (t === "posLevel") {
    store.labelOption.posLevel = "ทั้งหมด";
  } else if (t === "retireYear") {
    store.labelOption.retireYear = "";
  } else if (t === "rangeYear") {
    store.formFilter.rangeYear.min = 0;
    store.formFilter.rangeYear.max = 60;
  }
  store.formFilter.page = 1;
  fetchDataPerson();
}

onMounted(async () => {
  selectType();
});
</script>

<template>
  <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">
        ค้นหาข้อมูลทะเบียนประวัติ
        {{
          empType === "officer" ? "ข้าราชการ กทม. สามัญ" : "ลูกจ้างประจำ กทม."
        }}
      </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="store.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 />
            พบข้อมูลทั้งหมด {{ total }} รายการ
            <!-- <q-btn
              flat
              label="ตัวเลือกเพิ่มเติม"
              icon-right="mdi-tune"
              @click="onClickShowFilter"
              dense
              class="q-px-sm"
            ></q-btn> -->
          </div>

          <div
            :class="
              !isShowBtnFilter
                ? 'row q-mt-sm q-gutter-sm justify-center'
                : 'row 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"
              @click="() => (selectNode = true)"
            >
              <template v-slot:label>
                {{ `${store.labelOption.node}` }}
              </template>
            </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"
            >
              <template v-slot:label>
                {{
                  store.labelOption.posType !== "ทั้งหมด"
                    ? store.labelOption.posType
                    : empType === "officer"
                    ? `ตำแหน่งประเภท${store.labelOption.posType}`
                    : `กลุ่มงาน${store.labelOption.posType}`
                }}
                <q-btn
                  v-if="store.labelOption.posType !== 'ทั้งหมด'"
                  size="10px"
                  flat
                  round
                  color="white"
                  icon="close"
                  @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"
              :disable="store.labelOption.posType === 'ทั้งหมด' ? true : false"
            >
              <template v-slot:label>
                {{
                  store.labelOption.posLevel !== "ทั้งหมด"
                    ? store.labelOption.posLevel
                    : empType === "officer"
                    ? `ระดับ${store.labelOption.posLevel}`
                    : `ระดับชั้นงาน${store.labelOption.posLevel}`
                }}
                <q-btn
                  size="10px"
                  flat
                  round
                  color="white"
                  icon="close"
                  v-if="store.labelOption.posLevel !== 'ทั้งหมด'"
                  @click.stop.prevent="clearSelect('posLevel')"
                />
              </template>
              <q-list
                :style="store.posLevelOps.length > 9 ? 'height: 450px' : ''"
              >
                <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"
              v-if="empType === 'officer'"
            />

            <q-btn-dropdown
              v-if="empType === 'officer'"
              flat
              dense
              rounded
              label-color="white"
              dropdown-icon="mdi-chevron-down"
              :label="`เงื่อนไขอื่นๆ  ${conditionTotal}`"
              class="q-px-sm"
            >
              <q-list>
                <q-item clickable v-close-popup>
                  <q-item-section>
                    <q-toggle
                      v-model="store.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="store.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="store.formFilter"
        v-model:maxPage="maxPage"
        :fetchData="fetchDataPerson"
        :fetchType="fetchType"
        :total="total"
        :empType="empType"
        :is-filter="isShowBtnFilter"
      />
    </q-card-section>
  </q-card>

  <!-- แสดง dialog เลือกหน่วยงาน/ส่วนราชการ -->
  <q-dialog v-model="selectNode" persistent>
    <q-card style="width: 850px; max-width: 80vw">
      <DialogHeader
        tittle="เลือกหน่วยงาน/ส่วนราชการ"
        :close="() => (selectNode = false)"
      />

      <q-separator />

      <q-card-section class="q-pa-sm"> </q-card-section>
    </q-card>
  </q-dialog>
</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>
