<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useRoute, useRouter } from "vue-router";
import { useEditPosDataStore } from "@/modules/04_registryPerson/stores/Edit";
import { usePagination } from "@/composables/usePagination";

/** importType*/
import type { QTableColumn } from "quasar";
import type { DataStructureTree } from "@/interface/main";
import type {
  DataOption,
  Pagination,
} from "@/modules/04_registryPerson/interface/index/Main";
import type { DataSalaryPos } from "@/modules/04_registryPerson/interface/response/Edit";
import type { DataFilter } from "@/modules/04_registryPerson/interface/request/Edit";

const $q = useQuasar();
const route = useRoute();
const router = useRouter();
const store = useEditPosDataStore();
const { showLoader, hideLoader, messageError } = useCounterMixin();
const { pagination, params, onRequest } = usePagination("", fetchData);

const organizationOps = ref<DataOption[]>([]);
const organizationOpsMain = ref<DataOption[]>([]);
const employeeClassOpsMain = ref<DataOption[]>([
  { id: "officer", name: "ข้าราชการ กทม.สามัญ" },
  { id: "employee", name: "ลูกจ้างประจำ" },
]);
const employeeClassOps = ref<DataOption[]>(employeeClassOpsMain.value);
const statusOpsMain = ref<DataOption[]>([
  {
    id: "ALL",
    name: "ทั้งหมด",
  },
  {
    id: "PENDING",
    name: "ยังไม่ได้แก้ไข",
  },
  {
    id: "EDITED",
    name: "แก้ไขแล้ว",
  },
  {
    id: "CHECKED",
    name: "ตรวจสอบแล้ว",
  },
]);
const statusOps = ref<DataOption[]>(statusOpsMain.value);

//Table
const organization = ref<string>(store.orgId);
const filter = reactive<DataFilter>({
  status: store.status,
  empType: store.empType,
  keyword: store.keyword,
});
const rows = ref<DataSalaryPos[]>([]);
const columns = ref<QTableColumn[]>([
  {
    name: "posNo",
    align: "left",
    label: filter.empType === "officer" ? "เลขที่ตำแหน่ง" : "ตำแหน่งเลขที่",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px",
  },
  {
    name: "firstName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullName",
    format(val, row) {
      return `${row.prefix}${row.firstName} ${row.lastName}`;
    },
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posType",
    align: "left",
    label: filter.empType === "officer" ? "ตำแหน่งประเภท" : "กลุ่มงาน",
    sortable: true,
    field: "posType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posLevel",
    align: "left",
    label: filter.empType === "officer" ? "ระดับ" : "ระดับชั้นงาน",
    sortable: true,
    field: "posLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.posTypeShortName
        ? row.posTypeShortName + " " + row.posLevel
        : row.posLevel;
    },
  },
  {
    name: "org",
    align: "left",
    label: "สังกัด",
    sortable: false,
    field: "org",
    headerStyle: "font-size: 14px;min-width: 280px",
    style: "font-size: 14px",
  },
  {
    name: "statusCheckEdit",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "statusCheckEdit",
    format(val, row) {
      return statusOpsMain.value.find((e) => e.id === val)?.name;
    },
    headerStyle: "font-size: 14px;pointer-events: none;",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "posNo",
  "citizenId",
  "firstName",
  "position",
  "posType",
  "posLevel",
  "org",
  "statusCheckEdit",
]);

/** function fetch ข้อมูลโครงสร้างปัจจุบัน*/
async function fetchActiveOrg() {
  showLoader();
  await http
    .get(config.API.activeOrganization)
    .then(async (res) => {
      const data = res.data.result;
      await fetchListOrg(data.activeId);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function fetch ข้อมูลหน่วยงาน
 * @param id โครงสร้างปัจจุบัน
 */
async function fetchListOrg(id: string) {
  showLoader();
  await http
    .get(config.API.orgByIdSystem(id, route.meta.Key as string))
    .then(async (res) => {
      store.orgData = await res.data.result.map((item: DataStructureTree) => ({
        id: item.orgTreeId,
        name: item.orgName,
      }));
      if (store.orgData.length === 1) {
        organization.value = store.orgData[0].id;
        onSearchData();
      }
      organizationOpsMain.value = store.orgData;
      organizationOps.value = store.orgData;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function ค้นหาคำใน select
 * @param val คำค้นหา
 * @param update function
 * @param type ประเภท select
 */
function filterSelector(val: string, update: Function, type: string) {
  switch (type) {
    case "organization":
      update(() => {
        organizationOps.value = organizationOpsMain.value.filter(
          (v: DataOption) => v.name.toLowerCase().indexOf(val) > -1
        );
      });
      break;
    case "employeeClass":
      update(() => {
        employeeClassOps.value = employeeClassOpsMain.value.filter(
          (v: DataOption) => v.name.toLowerCase().indexOf(val) > -1
        );
      });
      break;

    case "status":
      update(() => {
        statusOps.value = statusOpsMain.value.filter(
          (v: DataOption) => v.name.toLowerCase().indexOf(val) > -1
        );
      });
      break;
    default:
      break;
  }
}

/** function fetch รายการแก้ไขทะเบียนประวัติ ตำแหน่ง/เงินเดือน*/
async function fetchData() {
  let queryParams = {
    ...params.value,
    type: filter.empType?.toLocaleUpperCase(),
    searchKeyword: filter.keyword,
    statusCheckEdit: filter.status?.toLocaleUpperCase(),
    rootId: organization.value,
  };

  store.status = filter.status;
  store.empType = filter.empType;
  store.keyword = filter.keyword;
  store.page = pagination.value.page;
  store.pageSize = pagination.value.rowsPerPage;

  if (organization.value !== "" && filter.empType !== "") {
    rows.value = [];
    showLoader();
    await http
      .get(config.API.salaryTemp, { params: queryParams })
      .then((res) => {
        const data = res.data.result;
        pagination.value.rowsNumber = data.total;
        rows.value = data.data;
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

/**
 * function ค้นหาข้อมูล
 * @param val true จะค้นหาหน้าแรก
 */
function onSearchData(val: boolean = true) {
  store.orgId = organization.value;
  if (val) {
    pagination.value.page = 1;
  }

  fetchData();
}

/**
 * function ไปหน้ารายการประวัติตำแหน่ง/เงินเดือน
 * @param id ProfileID
 * @param type ประเภทของข้าราชการ
 */
function onRedirectToPosition(id: string, type: string) {
  const tyepeLower = type?.toLocaleLowerCase();
  router.push(`/registry/edit/salary/${tyepeLower}/${id}`);
}

/** hook เมื่อมีการเรียกใช้ Components*/
onMounted(async () => {
  if (store.orgData.length === 0) {
    await fetchActiveOrg();
  } else {
    organizationOpsMain.value = store.orgData;
    organizationOps.value = store.orgData;
    pagination.value.page = store.page;
    pagination.value.rowsPerPage = store.pageSize;
    fetchData();
  }
});
</script>

<template>
  <div class="row items-center q-gutter-sm q-mb-xs">
    <div class="toptitle text-dark row items-center q-py-xs">
      แก้ไขทะเบียนประวัติ ตำแหน่ง/เงินเดือน
    </div>
  </div>
  <q-card flat bordered class="q-pa-md q-col-gutter-sm">
    <div class="row">
      <q-select
        outlined
        dense
        borderless
        hide-selected
        fill-input
        hide-bottom-space
        option-label="name"
        option-value="id"
        emit-value
        map-options
        v-model="organization"
        :options="organizationOps"
        label="หน่วยงาน"
        use-input
        @update:model-value="onSearchData()"
        @filter="(inputValue: string,
            doneFn: Function) => filterSelector(inputValue, doneFn,'organization' )"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
          </q-item>
        </template>
      </q-select>
    </div>

    <div class="row q-col-gutter-sm">
      <q-select
        outlined
        dense
        borderless
        hide-selected
        fill-input
        hide-bottom-space
        option-label="name"
        option-value="id"
        emit-value
        map-options
        v-model="filter.empType"
        :options="employeeClassOps"
        label="ประเภทตำแหน่ง"
        use-input
        @update:model-value="onSearchData()"
        @filter="(inputValue: string,
          doneFn: Function) => filterSelector(inputValue, doneFn,'employeeClass' )"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
          </q-item>
        </template>
      </q-select>

      <q-select
        outlined
        dense
        borderless
        hide-selected
        fill-input
        hide-bottom-space
        option-label="name"
        option-value="id"
        emit-value
        map-options
        v-model="filter.status"
        :options="statusOps"
        label="สถานะ"
        use-input
        @update:model-value="onSearchData()"
        @filter="(inputValue: string,
        doneFn: Function) => filterSelector(inputValue, doneFn,'status' )"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
          </q-item>
        </template>
      </q-select>

      <q-space />
      <q-input
        dense
        outlined
        v-model="filter.keyword"
        label="ค้นหา"
        @keydown.enter.prevent="onSearchData()"
      >
        <template v-slot:append>
          <q-icon name="search" />
        </template>
      </q-input>

      <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"
        style="min-width: 140px"
      />
    </div>

    <div class="col-12">
      <p-table
        ref="table"
        row-key="id"
        flat
        bordered
        dense
        :columns="columns"
        :rows="rows"
        :paging="true"
        :rows-per-page-options="[20, 50, 100]"
        :visible-columns="visibleColumns"
        @request="onRequest"
        v-model:pagination="pagination"
      >
        >
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th />
            <q-th v-for="col in props.cols" :key="col.name" :props="props">
              <span class="text-weight-medium">{{ col.label }}</span>
            </q-th>
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr
            :props="props"
            class="cursor-pointer"
            @click.stop.prevent="
              onRedirectToPosition(props.row.id, props.row.type)
            "
          >
            <q-td>
              <q-icon
                size="sm"
                v-if="props.row.statusCheckEdit !== 'PENDING'"
                :name="
                  props.row.statusCheckEdit === 'CHECKED'
                    ? 'mdi-check-circle'
                    : 'mdi-alert-circle'
                "
                :color="
                  props.row.statusCheckEdit === 'CHECKED' ? 'green' : 'orange-5'
                "
              />
            </q-td>
            <q-td v-for="col in props.cols" :key="col.id">
              <div v-if="col.name === 'org'" class="text-html">
                {{ col.value ? col.value : "-" }}
              </div>
              <div v-else>
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </p-table>
    </div>
  </q-card>
</template>

<style scoped></style>
