<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { useQuasar, type QTableProps } from "quasar";
import { useRouter } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";

import type {
  DataOption,
  ItemsMenu,
  NewPagination,
} from "@/modules/14_KPI/interface/index/Main";
import type {
  FormQueryRound,
  FormRound,
} from "@/modules/14_KPI/interface/request/Main";
import type { ResRound } from "@/modules/14_KPI/interface/response/Main";

import DialogHeader from "@/components/DialogHeader.vue";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";

/** use*/

const $q = useQuasar();
const router = useRouter();
const {
  showLoader,
  hideLoader,
  success,
  messageError,
  date2Thai,
  dialogConfirm,
  dialogRemove,
} = useCounterMixin();

/** หัวตาราง */
const rows = ref<ResRound[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "durationKPI",
    align: "left",
    label: "รอบการประเมิน ",
    sortable: true,
    field: "durationKPI",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => connvertName(val),
  },
  {
    name: "startDate",
    align: "left",
    label: "วันเริ่มต้น",
    sortable: true,
    field: "startDate",
    format: (val) => date2Thai(val),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "endDate",
    align: "left",
    label: "วันสิ้นสุด",
    sortable: true,
    field: "endDate",
    format: (val) => date2Thai(val),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>(["durationKPI", "startDate", "endDate"]);

const itemMenu = ref<ItemsMenu[]>([
  {
    label: "เปิดรอบ",
    value: "open",
    icon: "mdi-check",
    color: "primary",
  },
  {
    label: "ปิดรอบ",
    value: "close",
    icon: "mdi-close",
    color: "orange",
  },
  {
    label: "ลบรอบ",
    value: "delete",
    icon: "delete",
    color: "red",
  },
]);

const roundOp = ref<DataOption[]>([
  { id: "APR", name: "รอบเมษายน" },
  {
    id: "OCT",
    name: "รอบตุลาคม",
  },
]);

const formQuery = reactive<FormQueryRound>({
  page: 1,
  pageSize: 10,
  year: new Date().getFullYear(),
  keyword: "",
});
const totalList = ref<number>(1);

const formData = reactive<FormRound>({
  durationKPI: "",
  startDate: null,
  endDate: null,
});

function fetchList() {
  showLoader();
  http
    .get(
      config.API.kpiPeriod +
        `?page=${formQuery.page}&pageSize=${formQuery.pageSize}&keyword=${formQuery.keyword}&year=${formQuery.year}`
    )
    .then((res) => {
      const data: ResRound[] = res.data.result.data;
      totalList.value = Math.ceil(res.data.result.total / formQuery.pageSize);
      rows.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

const modalDialog = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);
function onClickAddOrView(status: boolean = false, id: string = "") {
  isStatusEdit.value = status;
  modalDialog.value = true;
}

function closeDialog() {
  modalDialog.value = false;
  clearFormData();
}

function changeDateStart() {
  if (formData?.startDate !== null && formData?.endDate !== null) {
    const startDate = new Date(formData.startDate);
    const endDate = new Date(formData?.endDate);
    if (startDate > endDate) {
      formData.endDate = null;
    }
  }
}

function clearFormData() {
  formData.durationKPI = "";
  formData.startDate = null;
  formData.endDate = null;
}

function onSubmit() {
  dialogConfirm($q, async () => {
    try {
      const url = isStatusEdit.value
        ? config.API.kpiPeriodById("12")
        : config.API.kpiPeriod;
      const method = isStatusEdit.value ? "put" : "post";
      await http[method](url, formData);
      fetchList();
      success($q, "บันทึกข้อมูลสำเร็จ");
    } catch (e) {
      messageError($q, e);
    } finally {
      hideLoader();
      closeDialog();
    }
  });
}

function onClickAction(action: string, id: string) {
  switch (action) {
    case "open":
      onOpenRounde();
      break;
    case "close":
      onCloseRounde();
      break;
    case "delete":
      onDeleteRound(id);
      break;
    default:
      break;
  }
}

function onOpenRounde() {
  dialogConfirm(
    $q,
    () => {},
    "ยืนยันการเปิดรอบ",
    "ต้องการยืนยันการเปิดรอบนี้หรือไม่ ?"
  );
}
function onCloseRounde() {
  dialogConfirm(
    $q,
    () => {},
    "ยืนยันการปิดรอบ",
    "ต้องการยืนยันการปิดรอบนี้หรือไม่ ?"
  );
}

function onDeleteRound(id: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.kpiPeriodById(id))
      .then(() => {
        success($q, "ลบข้อมูลสำเร็จ");
        fetchList();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function connvertName(val: string) {
  const findData = roundOp.value.find((e: DataOption) => e.id === val);
  return findData?.name;
}

/**
 * function updatePagination
 * @param newPagination ข้อมูล Pagination ใหม่
 */
function updatePagination(newPagination: NewPagination) {
  formQuery.page = 1;
  formQuery.pageSize = newPagination.rowsPerPage;
}

watch(
  () => formQuery.pageSize,
  () => {
    fetchList();
  }
);

onMounted(() => {
  fetchList();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการรอบการประเมินผลการปฏิบัติหน้าที่ราชการ
  </div>
  <q-card flat bordered class="q-pa-md">
    <q-toolbar style="padding: 0px">
      <div class="row q-gutter-sm">
        <datepicker
          menu-class-name="modalfix"
          v-model="formQuery.year"
          :locale="'th'"
          autoApply
          year-picker
          :enableTimePicker="false"
          @update:model-value="(formQuery.page = 1), fetchList()"
        >
          <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="Number(formQuery.year) + 543"
              :label="`${'ปีงบประมาณ'}`"
            >
              <template v-slot:prepend>
                <q-icon
                  name="event"
                  class="cursor-pointer"
                  style="color: var(--q-primary)"
                >
                </q-icon>
              </template>
            </q-input>
          </template>
        </datepicker>
        <q-btn
          flat
          round
          dense
          icon="add"
          color="primary"
          @click="onClickAddOrView()"
        >
          <q-tooltip>เพิ่ม</q-tooltip>
        </q-btn>
      </div>

      <q-space />
      <div class="row q-gutter-sm">
        <!-- <q-btn
          flat
          round
          color="blue"
          icon="mdi-arrow-down-bold-circle-outline"
        >
          <q-menu>
            <q-list style="min-width: 100px" dense>
              <q-item clickable v-close-popup v-for="items in itemDownload">
                <q-item-section avatar>
                  <q-icon :color="items.color" :name="items.icon" />
                </q-item-section>
                <q-item-section :class="`text-${items.color}`">{{
                  items.label
                }}</q-item-section>
              </q-item>
            </q-list>
          </q-menu>
          <q-tooltip>ดาวน์โหลด</q-tooltip>
        </q-btn> -->

        <!-- <q-input
          standout
          dense
          v-model="formQuery.keyword"
          ref="filterRef"
          outlined
          debounce="300"
          placeholder="ค้นหา"
          @keyup.enter="(formQuery.page = 1), fetchList()"
        >
          <template v-slot:append>
            <q-icon v-if="formQuery.keyword == ''" name="search" />
            <q-icon
              v-if="formQuery.keyword !== ''"
              name="clear"
              class="cursor-pointer"
              @click="
                (formQuery.keyword = ''), (formQuery.page = 1), fetchList()
              "
            />
          </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"
        />
      </div>
    </q-toolbar>

    <div class="col-12">
      <d-table
        for="table"
        ref="table"
        :columns="columns"
        :rows="rows"
        row-key="subject"
        flat
        bordered
        dense
        class="custom-header-table"
        :visible-columns="visibleColumns"
        :rows-per-page-options="[10, 25, 50, 100]"
        @update:pagination="updatePagination"
      >
        <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-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 class="table_ellipsis">
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
            <q-td>
              <q-btn flat round color="grey" icon="mdi-dots-vertical">
                <q-menu>
                  <q-list style="min-width: 150px" dense>
                    <q-item
                      clickable
                      v-close-popup
                      v-for="items in itemMenu"
                      @click="onClickAction(items.value, props.row.id)"
                    >
                      <q-item-section avatar>
                        <q-icon :color="items.color" :name="items.icon" />
                      </q-item-section>
                      <q-item-section>{{ items.label }}</q-item-section>
                    </q-item>
                  </q-list>
                </q-menu>
                <q-tooltip>ดาวน์โหลด</q-tooltip>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
        <template v-slot:pagination="scope">
          <q-pagination
            v-model="formQuery.page"
            active-color="primary"
            color="dark"
            :max="Number(totalList)"
            size="sm"
            boundary-links
            direction-links
            :max-pages="5"
            @update:model-value="fetchList"
          ></q-pagination>
        </template>
      </d-table>
    </div>
  </q-card>

  <q-dialog v-model="modalDialog" persistent>
    <q-card style="width: 350px">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          :tittle="'เพิ่มรอบการประเมินผลการปฏิบัติหน้าที่ราชการ'"
          :close="closeDialog"
        />
        <q-separator />

        <q-card-section class="q-pt-none">
          <div class="row col-12 q-pa-md q-col-gutter-md">
            <div class="col-12">
              <q-select
                dense
                outlined
                hide-bottom-space
                lazy-rules
                v-model="formData.durationKPI"
                :options="roundOp"
                option-label="name"
                option-value="id"
                emit-value
                map-options
                input-class="text-red"
                label="รอบการประเมิน"
                class="inputgreen"
                :rules="[
          (val:string) =>
            !!val || `${'กรุณาเลือกรอบการประเมิน'}`,
        ]"
              />
            </div>
            <div class="col-12">
              <datepicker
                menu-class-name="modalfix"
                v-model="formData.startDate"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
                @update:model-value="changeDateStart()"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    :model-value="
                      formData.startDate ? date2Thai(formData.startDate) : null
                    "
                    :label="`${'วันเริ่มต้น'}`"
                    hide-bottom-space
                    class="inputgreen"
                    :rules="[
      (val:string) =>
        !!val || `${'กรุณาเลือกวันที่เริ่มต้น'}`,
    ]"
                  >
                    <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 class="col-12">
              <datepicker
                menu-class-name="modalfix"
                v-model="formData.endDate"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
                :min-date="formData.startDate"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    :model-value="
                      formData.endDate ? date2Thai(formData.endDate) : null
                    "
                    :label="`${'วันสิ้นสุด'}`"
                    class="inputgreen"
                    hide-bottom-space
                    :rules="[
      (val:string) =>
        !!val || `${'กรุณาเลือกวันที่วันสิ้นสุด'}`,
    ]"
                  >
                    <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-card-section>

        <q-separator />

        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn dense unelevated label="บันทึก" type="submit" color="public">
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
