<script setup lang="ts">
import { getDateMeta } from "@fullcalendar/core/internal";
import { ref, reactive, onMounted } from "vue";
import { useSalaryDataStore } from "@/modules/13_salary/store/SalaryStore";
import { useCounterMixin } from "@/stores/mixin";
import type { QTableProps } from "quasar";
import type { RowList, Row } from "@/modules/13_salary/interface/response/Main";
import Dialog from "@/modules/13_salary/components/SalaryRound/DialogForm.vue";
import config from "@/app.config";
import http from "@/plugins/http";

import { useQuasar } from "quasar";

const idRound = ref<string>("");
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  dialogRemove,
  showLoader,
  hideLoader,
  messageError,
  date2Thai,
  dateToISO,
  dialogConfirm,
  success,
} = mixin;
const dataStore = useSalaryDataStore();
const year = ref<number>(0);
const filterKeyword = ref<string>("");
const rowsPerPage = ref<number>(10);
const editCheck = ref<boolean>(false);
const dialog = ref<boolean>(false);
const period = ref<string>("");
const isActive = ref<boolean>(false);
const isRead = ref<boolean>(false);
const effectiveDate = ref<Date | null>(null);

const yearData = ref<number | null>(0);
const maxPage = ref<number>(1);
const currentPage = ref<number>(1);
const page = ref<number>(1);

const pagination = ref({
  descending: false,
  page: page.value,
  rowsPerPage: rowsPerPage.value,
});

const visibleColumns = ref<string[]>([
  "no",
  "period",
  "year",
  "effectiveDate",
  "isActive",
  "isClose",
]);

// หัวตาราง
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "center",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "period",
    align: "left",
    label: "รอบการขึ้นเงินเดือน",
    sortable: true,
    field: "period",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "year",
    align: "left",
    label: "ปีงบประมาณ",
    sortable: true,
    field: "year",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "effectiveDate",
    align: "left",
    label: "วันที่มีผลบังคับใช้",
    sortable: true,
    field: "effectiveDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "isActive",
    align: "left",
    label: "สถานะการใช้งาน",
    sortable: true,
    field: "isActive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "isClose",
    align: "left",
    label: "สถานะการปิดรอบ",
    sortable: true,
    field: "isClose",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

function clickAdd() {
  dialog.value = true;
  editCheck.value = false;
}
/** ดึงข้อมูลเริ่มต้น */
function getData() {
  showLoader();
  http
    .get(
      config.API.salaryPeriod() +
        `?page=${page.value}&pageSise=${rowsPerPage.value}&keyword=${filterKeyword.value}&year=${year.value}`
    )
    .then((res) => {
      dataStore.fetchDataMap(res.data.result.data);
      maxPage.value = Math.ceil(res.data.result.total / rowsPerPage.value);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}
function dataUpdate() {
  getData();
}
/** set ปี ทั้งหมด */
function yearAll() {
  year.value = 0;
  getData();
}

/** ฟังชั่น เคลียฟิลเตอร์ */
function resetFilter() {
  filterKeyword.value = "";
  getData();
}

// /** ดึงข้อมูลเมื่อ กด enter */
// function filterFn() {
//   getData();
// }

function deleteData(id: string) {
  showLoader();
  http
    .delete(config.API.salaryPeriod() + `/${id}`)
    .then((res) => {
      getData();
      success($q, "ลบข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function editPopup(data: RowList, status: string) {
  if (status == "read") {
    isRead.value = true;
  }
  editCheck.value = true;
  dialog.value = true;
  idRound.value = data.id;
  period.value = data.period ? data.period : "";
  yearData.value = data.year ? data.year : 0;
  effectiveDate.value = data.effectiveDate as Date;
  isActive.value = data.isActive ? data.isActive : false;
}
/** ปิดรอบ */
function dialogClose(id: string) {
  dialogConfirm(
    $q,
    () => {
      http
        .get(config.API.salaryPeriod() + `/close/${id}`)
        .then((res) => {
          getData();
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {});
    },
    "ยืนยันการปิดรอบ",
    "หากปิดรอบแล้วจะไม่สามารถแก้ไขรายการเงินเดือนของรอบนี้ได้ ต้องการยืนยันการปิดรอบนี้ใช่หรือไม่?"
  );
}

onMounted(async () => {
  year.value = new Date().getFullYear();
  getData();

  dataStore.visibleColumns = visibleColumns.value;
  dataStore.columns = columns.value;
});
</script>

<template>
  <div class="row items-center">
    <div class="toptitle text-dark row items-center q-py-xs">
      รอบการขึ้นเงินเดือน
    </div>
  </div>
  <q-card flat bordered class="col-12 q-mt-sm q-pa-md">
    <div class="row q-mb-sm q-col-gutter-sm">
      <div class="col-2">
        <datepicker
          menu-class-name="modalfix"
          v-model="year"
          class="col-2"
          :locale="'th'"
          autoApply
          year-picker
          :enableTimePicker="false"
          @update:model-value="dataUpdate"
        >
          <template #year="{ year }">{{ year + 543 }}</template>
          <template #year-overlay-value="{ value }">{{
            parseInt(value + 543)
          }}</template>
          <template #trigger>
            <q-input
              dense
              lazy-rules
              outlined
              :model-value="year === 0 ? null : Number(year) + 543"
              :label="`${'ปีงบประมาณ'}`"
            >
              <template v-if="year" v-slot:append>
                <q-icon
                  name="cancel"
                  @click.stop.prevent="yearAll"
                  class="cursor-pointer"
                />
              </template>
              <template v-slot:prepend>
                <q-icon
                  name="event"
                  class="cursor-pointer"
                  style="color: var(--q-primary)"
                >
                </q-icon>
              </template>
            </q-input>
          </template>
        </datepicker>
      </div>
      <div>
        <q-btn
          id="addComplaints"
          for="addComplaints"
          size="12px"
          flat
          round
          color="primary"
          icon="mdi-plus"
          @click="clickAdd()"
          ><q-tooltip>สร้างรอบเงินเดือน</q-tooltip></q-btn
        >
      </div>
      <q-space />
      <!-- <q-input
        for="#search"
        class="col-xs-12 col-sm-3 col-md-2"
        standout
        dense
        v-model="filterKeyword"
        ref="filterRef"
        outlined
        placeholder="ค้นหา"
        @keydown.enter.prevent="filterFn"
      >
        <template v-slot:append>
          <q-icon
            v-if="filterKeyword !== ''"
            name="clear"
            class="cursor-pointer"
            @click="resetFilter"
          />
        </template>
      </q-input> -->

      <q-select
        id="visibleColumns"
        for="visibleColumns"
        v-model="dataStore.visibleColumns"
        multiple
        outlined
        dense
        options-dense
        :display-value="$q.lang.table.columns"
        emit-value
        map-options
        :options="dataStore.columns"
        option-value="name"
        options-cover
        class="col-xs-12 col-sm-3 col-md-2"
      />
    </div>

    <div class="col-12">
      <d-table
        ref="table"
        :columns="dataStore.columns"
        :rows="dataStore.rows"
        row-key="id"
        flat
        bordered
        :paging="true"
        dense
        class="custom-header-table"
        :visible-columns="dataStore.visibleColumns"
        v-model:pagination="pagination"
        :rows-per-page-options="[10, 25, 50, 100]"
      >
        <template v-slot:pagination="scope">
          <q-pagination
            v-model="currentPage"
            active-color="primary"
            color="dark"
            :max="Number(maxPage)"
            size="sm"
            boundary-links
            direction-links
          ></q-pagination>
        </template>
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              style="color: #000000; font-weight: 500"
            >
              <span class="text-weight-medium">{{ col.label }}</span>
            </q-th>
            <q-th auto-width />
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props" class="cursor-pointer">
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              <div v-if="col.name == 'no'">
                {{
                  (currentPage - 1) * Number(pagination.rowsPerPage) +
                  props.rowIndex +
                  1
                }}
              </div>
              <div v-if="col.name == 'effectiveDate'">
                {{ date2Thai(props.row.effectiveDate) }}
              </div>
              <div v-else-if="col.name == 'year'">
                {{ props.row.year ? props.row.year + 543 : "-" }}
              </div>
              <div v-else-if="col.name == 'period'">
                {{ dataStore.statusTothai(props.row.period) }}
              </div>
              <div v-else-if="col.name === 'isActive'">
                <q-icon
                  v-if="col.value == false"
                  name="mdi-close"
                  color="grey"
                  class="text-h5"
                />
                <q-icon
                  v-else
                  name="mdi-check"
                  color="positive"
                  class="text-h5"
                />
              </div>
              <div v-else-if="col.name == 'isClose'">
                {{ props.row.isClose == false ? "" : "ปิดรอบแล้ว" }}
              </div>
              <div v-else>
                {{ col.value }}
              </div>
            </q-td>
            <q-td>
              <q-btn
                flat
                dense
                icon="mdi-dots-vertical"
                class="q-pa-none q-ml-xs"
                color="grey-13"
                size="12px"
              >
                <q-menu>
                  <q-list dense style="min-width: 200px">
                    <q-item
                      clickable
                      v-close-popup
                      @click.stop="
                        props.row.revisionId !== null
                          ? editPopup(props.row, 'read')
                          : editPopup(props.row, 'edit')
                      "
                    >
                      <q-item-section>
                        <div class="row items-center">
                          <q-icon
                            color="edit"
                            size="17px"
                            :name="
                              props.row.revisionId !== null
                                ? 'mdi-eye-outline'
                                : 'edit'
                            "
                          />
                          <div class="q-pl-md">
                            {{
                              props.row.revisionId !== null
                                ? "ดูข้อมูล"
                                : "แก้ไขข้อมูล"
                            }}
                          </div>
                        </div>
                      </q-item-section>
                    </q-item>

                    <q-item
                      v-if="
                        props.row.isClose === false &&
                        props.row.isActive === true
                      "
                      clickable
                      v-close-popup
                      @click.stop="dialogClose(props.row.id)"
                    >
                      <q-item-section>
                        <div class="row items-center">
                          <q-icon
                            color="red"
                            size="17px"
                            name="mdi-close-box"
                          />
                          <div class="q-pl-md">ปิดรอบ</div>
                        </div>
                      </q-item-section>
                    </q-item>
                    <q-item
                      v-if="props.row.revisionId == null"
                      clickable
                      v-close-popup
                      @click.stop="
                        dialogRemove(
                          $q,
                          async () => await deleteData(props.row.id)
                        )
                      "
                    >
                      <q-item-section>
                        <div class="row items-center">
                          <q-icon color="red" size="17px" name="mdi-delete" />
                          <div class="q-pl-md">ลบข้อมูล</div>
                        </div>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-menu>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>

  <Dialog
    v-model:modal="dialog"
    :edit="editCheck"
    :get-data="getData"
    :idRound="idRound"
    :period="period"
    v-model:effective="effectiveDate"
    :isActive="isActive"
    v-model:is-read="isRead"
    v-model:year="yearData"
  />
</template>

<style scoped></style>
