<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";

/** importType*/
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";

/** importComponents*/
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",
  },
  {
    name: "isActive",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "isActive",
    format: (val) => (val ? "เปิด" : "ปิดแล้ว"),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "durationKPI",
  "startDate",
  "endDate",
  "isActive",
]);

/** itemMenu*/
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",
  },
]);

/** Option  รอบการประเมิน*/
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: "",
  year: null,
  startDate: null,
  endDate: null,
});
const modalDialog = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);

/** function fetch ข้อมูลรายการรอบการประเมินผลการปฏิบัติหน้าที่ราชการ*/
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();
    });
}

/**
 *  function opent Dialog เพิ่มรอบการประเมินผลการปฏิบัติหน้าที่ราชการ
 * @param status เพิ่ม,แก้ไข
 * @param id
 */
function onClickAddOrView(status: boolean = false, id: string = "") {
  isStatusEdit.value = status;
  modalDialog.value = true;
}

/** function close Dialog*/
function closeDialog() {
  modalDialog.value = false;
  clearFormData();
}

/** function Clear วันสิ้นสุด*/
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 ClearForm เพิ่มรอบการประเมิน*/
function clearFormData() {
  formData.durationKPI = "";
  formData.startDate = null;
  formData.endDate = null;
  formData.year = null;
}

/** function บันทึกข้อมูลเพิ่มรอบการประเมิน*/
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(id);
      break;
    case "close":
      onCloseRounde(id);
      break;
    case "delete":
      onDeleteRound(id);
      break;
    default:
      break;
  }
}

/**
 *  function เปิดรอบ
 * @param id รอบการประเมิน
 */
function onOpenRounde(id: string) {
  dialogConfirm(
    $q,
    () => {
      http
        .get(config.API.kpiPeriod + `/open/${id}`)
        .then(() => {
          fetchList();
          success($q, "เปิดรอบสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการเปิดรอบ",
    "ต้องการยืนยันการเปิดรอบนี้หรือไม่ ?"
  );
}

/**
 *  function ปิดรอบ
 * @param id รอบการประเมิน
 */
function onCloseRounde(id: string) {
  dialogConfirm(
    $q,
    () => {
      showLoader();
      http
        .get(config.API.kpiPeriod + `/close/${id}`)
        .then(() => {
          success($q, "ปิดรอบสำเร็จ");
          fetchList();
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการปิดรอบ",
    "ต้องการยืนยันการปิดรอบนี้หรือไม่ ?"
  );
}

/**
 *  function ลบรอบ
 * @param id รอบการประเมิน
 */
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 Convertname รอบการประเมิน */
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();
  }
);

watch(
  [() => formData.durationKPI, () => formData.year],
  ([newDurationKPI, newYear], [oldDurationKPI, oldYear]) => {
    if (newDurationKPI && newYear) {
      if (newDurationKPI === "APR") {
        formData.startDate = new Date(`${Number(newYear) - 1}-10-01`);
        formData.endDate = new Date(`${newYear}-03-31`);
      } else if (newDurationKPI === "OCT") {
        formData.startDate = new Date(`${newYear}-04-01`);
        formData.endDate = new Date(`${newYear}-09-30`);
      }
    }
  }
);

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="
                formQuery.year === 0 ? 'ทั้งหมด' : Number(formQuery.year) + 543
              "
              :label="`${'ปีงบประมาณ'}`"
            >
              <template v-slot:prepend>
                <q-icon
                  name="event"
                  class="cursor-pointer"
                  style="color: var(--q-primary)"
                >
                </q-icon>
              </template>
              <template v-if="formQuery.year" v-slot:append>
                <q-icon
                  name="cancel"
                  @click.stop.prevent="
                    (formQuery.year = 0), (formQuery.page = 1), fetchList()
                  "
                  class="cursor-pointer"
                />
              </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 props.row.isActive
                        ? itemMenu
                        : itemMenu.slice(1, 2)"
                      @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.year"
                :locale="'th'"
                autoApply
                year-picker
                :enableTimePicker="false"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    hide-bottom-space
                    class="inputgreen"
                    :model-value="
                      formData.year === null
                        ? null
                        : Number(formData.year) + 543
                    "
                    :label="`${'ปีงบประมาณ'}`"
                    :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.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>
