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

import { useRouter } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useDataStoreRetirement } from "@/modules/06_retirement/store/storeRetirement";
import { checkPermission } from "@/utils/permissions";
import { calculateFiscalYear } from "@/utils/function";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableProps } from "quasar";
import type { resMain } from "@/modules/06_retirement/interface/response/Main";

import DialogAddListRetirement from "@/modules/06_retirement/components/01_retirement/DialogAddListRetirement.vue";

const $q = useQuasar(); //ใช้ noti quasar
const router = useRouter();
const mixin = useCounterMixin();
const useStoreRetire = useDataStoreRetirement();
const { tab, type } = storeToRefs(useDataStoreRetirement());
const { clickTab } = useStoreRetire;
const { messageError, date2Thai, showLoader, hideLoader, onSearchDataTable } =
  mixin;

const fiscalyear = ref<number>(calculateFiscalYear(new Date())); // ปี
const actionOption = ref<resMain[]>([]);

const pagination = ref({
  sortBy: "",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});

const visibleColumns = ref<string[]>([
  "no",
  "signDate",
  "Date",
  "retireNumber",
  "typeReport",
]);

// หัวตาราง
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "signDate",
    align: "left",
    label: "ประกาศ ณ วันที่",
    field: "signDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "Date",
    align: "left",
    label: "วันที่สร้าง",
    field: "Date",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "retireNumber",
    align: "left",
    label: "จำนวนผู้เกษียณ",
    field: "retireNumber",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "typeReport",
    align: "left",
    label: "ประเภทประกาศ",
    field: "typeReport",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

// ข้อมูลตาราง (จำลอง)
const currentYear = ref<number | null>(calculateFiscalYear(new Date()));
const rows = ref<resMain[]>([]);
const rowsData = ref<resMain[]>([]);

// ประกาศเกษียณอายุราชการ
async function fetchRetirement(type: string, year: any) {
  showLoader();
  rows.value = [];
  await http
    .get(config.API.retirement(type, year))
    .then((res) => {
      let data = res.data.result;
      if (data.length !== 0) {
        const listData = data.map((items: any) => ({
          id: items.id,
          signDate: date2Thai(items.signDate) ?? "-",
          Date: date2Thai(items.createdAt),
          year: items.year + 543,
          retireNumber: items.round,
          total: items.total,
          round: items.round,
          typeReport: typeReportChangeName(items.typeReport), // เปลี่ยนสถานะ
          json: items.json,
          document: items.document,
        }));
        rows.value = listData;
        rowsData.value = listData;
        actionOption.value = rows.value;
        rows.value.sort((a, b) => a.round - b.round); // เรียงรอบมากไปน้อย
        checkststus(rows.value);
      } else {
        rows.value = [];
        rowsData.value = [];
        actionOption.value = [];
        checkjson.value = false;
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

const checkjson = ref<boolean>();
// เช็คสถานะ document ของประกาศเกษียณอายุราชการ
function checkststus(data: any) {
  let jsonfasle = data.find((e: any) => e.document == false);
  if (jsonfasle) {
    checkjson.value = true;
  } else checkjson.value = false;
}

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

/**
 * ไปหน้าแก้ไขรายละเอียด
 * @param prop ข้อมูล
 */
function nextPage(prop: any) {
  router.push(`/retirement/${prop.id}`);
}

/**
 * ไปหน้ารายละเอียด
 * @param prop ข้อมูล
 */
function nextPageDetail(prop: any) {
  router.push(`/retirement-detail/${prop.id}`);
}

/** แปลง status เป็น text */
function typeReportChangeName(val: string) {
  switch (val) {
    case "EDIT":
      return "ประกาศแก้ไขเกษียณ";
    case "ADD":
      return "ประกาศเพิ่มเกษียณ";
    case "REMOVE":
      return "ประกาศยกเลิกเกษียณ";
    default:
      return "ประกาศข้อมูลเกษียณ";
  }
}

function onSearch() {
  rows.value = onSearchDataTable(
    filterKeyword.value,
    rowsData.value,
    columns.value ? columns.value : []
  );
}

watch(type, () => {
  fetchRetirement(type.value, fiscalyear.value);
});

onMounted(async () => {
  await fetchRetirement(type.value, fiscalyear.value);
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    ประกาศเกษียณอายุราชการ
  </div>
  <q-card flat bordered class="col-12 q-mt-sm">
    <div class="row col-12">
      <q-tabs
        dense
        v-model="tab"
        align="left"
        class="bg-white text-grey"
        active-color="primary"
        indicator-color="primary"
      >
        <div v-for="item in useStoreRetire.taboption">
          <q-tab
            :name="item.name"
            :label="item.label"
            @click="clickTab(item.name)"
          />
        </div>
      </q-tabs>
    </div>
    <q-separator />
    <q-tab-panels v-model="tab" animated>
      <q-tab-panel
        v-for="item in useStoreRetire.taboption"
        :key="item.name"
        :name="item.name"
        class="q-pa-none"
      >
        <div class="col-12 row q-pa-md q-col-gutter-sm">
          <div class="row col-12">
            <div class="row col-12 q-col-gutter-sm">
              <datepicker
                v-model="fiscalyear"
                style="width: 150px"
                :locale="'th'"
                autoApply
                year-picker
                :enableTimePicker="false"
                :max-date="`${calculateFiscalYear(new Date())}, 12, 31`"
                @update:model-value="fetchRetirement(type, fiscalyear)"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    hide-bottom-space
                    :model-value="
                      fiscalyear === null ? 'ทั้งหมด' : Number(fiscalyear) + 543
                    "
                    :label="`${'ปี พ.ศ.'}`"
                  >
                  </q-input>
                </template>
              </datepicker>

              <!-- use-input -->
              <div
                v-if="
                  checkPermission($route)?.attrIsCreate &&
                  fiscalyear === currentYear
                "
              >
                <DialogAddListRetirement
                  :type="useStoreRetire.type"
                  :year="fiscalyear"
                  :rows="rows"
                  :actionOptio="actionOption"
                  :checkjson="checkjson"
                />
              </div>
              <q-space />

              <q-input
                standout
                dense
                v-model="filterKeyword"
                ref="filterRef"
                outlined
                placeholder="ค้นหา"
                @keydown.enter.prevent="onSearch"
              >
                <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>

          <div class="col-12">
            <d-table
              ref="table"
              :columns="columns"
              :rows="rows"
              row-key="name"
              flat
              bordered
              :paging="true"
              dense
              :visible-columns="visibleColumns"
              v-model:pagination="pagination"
            >
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th auto-width> </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">
                  <q-td auto-width>
                    <q-btn
                      v-if="checkPermission($route)?.attrIsGet"
                      flat
                      round
                      dense
                      icon="mdi-eye"
                      color="info"
                      @click="nextPageDetail(props.row)"
                    >
                      <q-tooltip>รายละเอียด</q-tooltip>
                    </q-btn>

                    <q-btn
                      v-if="
                        checkPermission($route)?.attrIsGet &&
                        checkPermission($route)?.attrIsUpdate &&
                        fiscalyear === currentYear
                      "
                      flat
                      round
                      dense
                      icon="edit"
                      :disable="props.row.document"
                      :color="!props.row.document ? 'edit' : 'grey-5'"
                      @click="nextPage(props.row)"
                    >
                      <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                    </q-btn>
                  </q-td>
                  <q-td key="no" :props="props">
                    {{ props.rowIndex + 1 }}
                  </q-td>
                  <q-td key="signDate" :props="props">
                    {{ props.row.signDate ? props.row.signDate : "-" }}
                  </q-td>
                  <q-td key="Date" :props="props">
                    {{ props.row.Date }}
                  </q-td>
                  <q-td key="retireNumber" :props="props">
                    {{ props.row.total }}
                  </q-td>
                  <q-td key="typeReport" :props="props">
                    {{ props.row.typeReport }}
                  </q-td>
                </q-tr>
              </template>
            </d-table>
          </div>
        </div>
      </q-tab-panel>
    </q-tab-panels>
  </q-card>
</template>

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

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

.icon-color {
  color: #4154b3;
}
</style>
