<script setup lang="ts">
import { onMounted, ref, useAttrs, reactive, watch } from "vue";
import type { QTableProps } from "quasar";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useDataStoreRetirement } from "@/modules/06_retirement/storeRetirement";
import type { resMain } from "@/modules/06_retirement/interface/response/Main";
import { storeToRefs } from "pinia";
import popupAdd from "../components/ListRetirement/popupAdd.vue";

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

const fiscalyear = ref<number>();
const yearOptionsFilter = ref<any>({
  yearOptions: [],
});
const actionOption = ref<resMain[]>([]);

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 = new Date().getFullYear();
const rows = ref<resMain[]>([]);
const yearOptions = ref<any>([{ id: "", year: "ทั้งหมด" }]);

onMounted(async () => {
  await fetchRetirement(type.value, currentYear);
  // fiscalyear.value = currentYear + 543
  //   await fetchRetirement(type.value, currentYear);
});
// หาปีปัจจุบัน
const filteryear = () => {
  //   yearOptions.value.push({ id: currentYear, name: currentYear + 543 });
  //   yearOptionsFilter.value = [{ id: currentYear, name: currentYear + 543 }];
  //   yearOptionsFilter.value.push({ id: currentYear, name: currentYear + 543 });
  fetchRetirement(type.value, currentYear);
};
// ประกาศเกษียณอายุราชการ
const fetchRetirement = async (type: string, year: any) => {
  showLoader();
  await http
    .get(config.API.retirement(type, year))
    .then((res) => {
      rows.value = [];
      let data = res.data.result;
      rows.value = 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,
      }));
      let option: any[] = [];
      data.map((items: any) => {
        option.push({
          id: items.year,
          year: (items.year + 543).toString(),
          typeReport: typeReportChangeName(items.typeReport), // เปลี่ยนสถานะ
        });
      });
      yearOptions.value = [{ id: 0, year: "ทั้งหมด" }];
      // yearOptions.value.push(...option);
      if (option.length !== 0) {
        const double_name = [...new Set(option.map((item: any) => item.id))];
        for (let i = 1; i <= double_name.length; i++) {
          const type = double_name[i - 1];
          const listtype = {
            id: type,
            year: (Number(type) + 543).toString(),
          };
          yearOptions.value.push(listtype);
        }
      }
      yearOptionsFilter.value = yearOptions.value;
      if (yearOptionsFilter.value.length == 1) {
        fiscalyear.value = yearOptionsFilter.value[0].id;
      } else {
        fiscalyear.value = year;
      }
      actionOption.value = rows.value;

      rows.value.sort((a, b) => a.round - b.round); // เรียงรอบมากไปน้อย
      checkststus(rows.value);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const checkjson = ref<boolean>();
// เช็คสถานะ document ของประกาศเกษียณอายุราชการ
const 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);
const resetFilter = () => {
  filterKeyword.value = "";
  filterRef.value.focus();
};
const attrs = ref<any>(useAttrs());

const paging = ref<boolean>(true);
const pagination = ref({
  sortBy: "",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});
const filterSelector = (val: any, update: Function) => {
  update(() => {
    yearOptions.value = yearOptionsFilter.value.filter(
      (v: any) => v.year.indexOf(val) > -1
    );
  });
};

const paginationLabel = (start: string, end: string, total: string) => {
  if (paging.value == true) return " " + start + "-" + end + " ใน " + total;
  else return start + "-" + end + " ใน " + total;
};
const nextPage = (prop: any) => {
  router.push(`/retirement/${prop.id}`);
};

watch(type, () => {
  fetchRetirement(type.value, currentYear);
});
//เปลี่ยนสถานะ
const typeReportChangeName = (val: string) => {
  switch (val) {
    case "EDIT":
      return "ประกาศแก้ไขเกษียณ";
    case "ADD":
      return "ประกาศเพิ่มเกษียณ";
    case "REMOVE":
      return "ประกาศยกเลิกเกษียณ";
    default:
      return "ประกาศข้อมูลเกษียณ";
  }
};
</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">
          <div class="row col-12">
            <div class="row col-12 q-col-gutter-sm">
              <q-select
                v-model="fiscalyear"
                label="ปีงบประมาณ"
                dense
                emit-value
                map-options
                :options="yearOptions"
                option-value="id"
                option-label="year"
                lazy-rules
                use-input
                hide-bottom-space
                :readonly="false"
                :borderless="false"
                :outlined="true"
                @filter="(inputValue:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn
                      ) "
                :hide-dropdown-icon="false"
                style="min-width: 150px"
              >
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      ไม่มีข้อมูล
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>

              <!-- use-input -->
              <div>
                <popupAdd
                  :type="useStoreRetire.type"
                  :year="fiscalyear"
                  :rows="rows"
                  :actionOptio="actionOption"
                  :checkjson="checkjson"
                />
              </div>
              <q-space />

              <q-input
                class="col-xs-12 col-sm-3 col-md-2"
                standout
                dense
                v-model="filterKeyword"
                ref="filterRef"
                outlined
                debounce="300"
                placeholder="ค้นหา"
              >
                <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>

              <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="col-xs-12 col-sm-3 col-md-2"
              />
            </div>
            <div class="col-12 q-pt-sm">
              <q-table
                ref="table"
                :columns="columns"
                :rows="rows"
                :filter="filterKeyword"
                row-key="name"
                flat
                bordered
                :paging="true"
                dense
                class="custom-header-table"
                v-bind="attrs"
                :visible-columns="visibleColumns"
                :pagination-label="paginationLabel"
                v-model:pagination="pagination"
              >
                <template v-slot:header="props">
                  <q-tr :props="props">
                    <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="nextPage(props.row)"
                  >
                    <q-td key="no" :props="props">
                      {{ props.rowIndex + 1 }}
                    </q-td>
                    <q-td key="signDate" :props="props">
                      {{ 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>
                <template v-slot:pagination="scope">
                  <q-pagination
                    v-model="pagination.page"
                    active-color="primary"
                    color="primary"
                    :max="scope.pagesNumber"
                    :max-pages="5"
                    size="sm"
                    boundary-links
                    direction-links
                  ></q-pagination>
                </template>
              </q-table>
            </div>
          </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;
}

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