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

import { checkPermission } from "@/utils/permissions";
import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableProps } from "quasar";
import type { RequestItemsObject } from "@/modules/04_registryPerson/interface/request/DeclarationHonor";
import type { ResponseObject } from "@/modules/04_registryPerson/interface/response/DeclarationHonor";

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

const $q = useQuasar();
const route = useRoute();
const mixin = useCounterMixin();
const {
  date2Thai,
  success,
  messageError,
  showLoader,
  hideLoader,
  dialogConfirm,
  pathRegistryEmp,
} = mixin;

const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);
const empType = ref<string>(pathRegistryEmp(route.name?.toString() ?? ""));

/**
 * props
 */
const isLeave = defineModel<boolean>("isLeave", {
  required: true,
});

const id = ref<string>(""); //id ที่ต้องการแก้ไข
const issueDateYear = ref<number>(0); //ปีที่ได้รับ
const declHonorForm = reactive<RequestItemsObject>({
  isDate: "false", //ปี
  issuer: "", //ผู้มีอำนาจลงนาม
  detail: "", //รายละเอียด
  issueDate: null, //ปีที่ได้รับ
  refCommandNo: "", //เลขที่คำสั่ง
  refCommandDate: null, //'เอกสารอ้างอิง (ลงวันที่)'
});

const isEdit = ref<boolean>(false); //สถานะการแก้ไขข้อมูล
const modal = ref<boolean>(false); //แสดง popup ข้อมูลประกาศเกียรติคุณ
const modeView = ref<string>("table"); //การแสดงผล Table,Card
const modalHistory = ref<boolean>(false); //แสดง popup ประวัติแก้ไข

//Table Main
const rows = ref<ResponseObject[]>([]);
const filterSearch = ref("");
const columns = ref<QTableProps["columns"]>([
  {
    name: "issueDate",
    align: "left",
    label: "วันที่ได้รับ",
    sortable: true,
    field: (v) =>
      v.isDate
        ? date2Thai(v.issueDate)
        : new Date(v.issueDate).getFullYear() + 543,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "issuer",
    align: "left",
    label: "ผู้มีอำนาจลงนาม",
    sortable: true,
    field: "issuer",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "detail",
    align: "left",
    label: "รายละเอียด",
    sortable: true,
    field: "detail",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "refCommandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "refCommandNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "refCommandDate",
    align: "left",
    label: "เอกสารอ้างอิง (ลงวันที่)",
    sortable: true,
    field: "refCommandDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumns = ref<String[]>([
  "issuer",
  "detail",
  "issueDate",
  "refCommandNo",
  "refCommandDate",
]);
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});

//Table ประวัติแก้ไข
const rowsHistory = ref<ResponseObject[]>([]);
const filterHistory = ref<string>("");
const columnsHistory = ref<QTableProps["columns"]>([
  {
    name: "issueDate",
    align: "left",
    label: "วันที่ได้รับ",
    sortable: true,
    field: (v) =>
      v.isDate
        ? date2Thai(v.issueDate)
        : new Date(v.issueDate).getFullYear() + 543,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "issuer",
    align: "left",
    label: "ผู้มีอำนาจลงนาม",
    sortable: true,
    field: "issuer",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "detail",
    align: "left",
    label: "รายละเอียด",
    sortable: true,
    field: "detail",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "refCommandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "refCommandNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "refCommandDate",
    align: "left",
    label: "เอกสารอ้างอิง (ลงวันที่)",
    sortable: true,
    field: "refCommandDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdateFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "lastUpdateFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v, false, true),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumnsHistory = ref<String[]>([
  "issuer",
  "detail",
  "issueDate",
  "refCommandNo",
  "refCommandDate",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
const historyPagination = ref({
  page: 1,
  rowsPerPage: 10,
});

/**
 * fetch รายการข้อมูลประกาศเกียรติคุณ
 */
async function fetchData() {
  if (!profileId.value) return;

  showLoader();
  try {
    const res = await http.get(
      config.API.profileNewHonorByProfileId(profileId.value, empType.value)
    );
    rows.value = res.data.result;
  } catch (error) {
    messageError($q, error);
  } finally {
    hideLoader();
  }
}

/**
 * บันทึกข้อมูลประกาศเกียรติคุณ
 * @param editStatus แก่ไข,เพิ่ม
 */
async function addEditData(editStatus: boolean = false) {
  if (!profileId.value) return;

  showLoader();
  const url = editStatus
    ? config.API.profileNewHonorById(id.value, empType.value)
    : config.API.profileNewHonor(empType.value);
  const method = editStatus ? "patch" : "post";
  const reqBody: RequestItemsObject = {
    ...declHonorForm,
    profileEmployeeId:
      !editStatus && empType.value !== "" ? profileId.value : undefined,
    profileId:
      !editStatus && empType.value === "" ? profileId.value : undefined,
    isDate: declHonorForm.isDate === "true" ? true : false,
    issueDate:
      declHonorForm.isDate === "true"
        ? declHonorForm.issueDate
        : new Date(`${issueDateYear.value}-01-01`),
  };

  try {
    await http[method](url, reqBody);
    await fetchData();
    await success($q, "บันทึกข้อมูลสำเร็จ");
    modal.value = false;
  } catch (e) {
    messageError($q, e);
  } finally {
    hideLoader();
  }
}

/**
 * เปิด form ข้อมูลประกาศเกียรติคุณ
 */
function onClickOpenDialog(editStatus: boolean = false, row?: ResponseObject) {
  modal.value = true;
  isEdit.value = editStatus;

  if (editStatus && row) {
    id.value = row.id;

    issueDateYear.value = new Date(row.issueDate).getFullYear();
    declHonorForm.issuer = row.issuer;
    declHonorForm.detail = row.detail;
    declHonorForm.issueDate = row.issueDate;
    declHonorForm.refCommandNo = row.refCommandNo;
    declHonorForm.refCommandDate = row.refCommandDate;
    declHonorForm.isDate = row.isDate ? "true" : "false";
  } else {
    clearData();
  }
}

/**
 * ปิด form ข้อมูลประกาศเกียรติคุณ
 */
async function clickClose() {
  clearData();
  modal.value = false;
}

/**
 * fetch ช้อมูลประวัติการแก้ไขรายการข้อมูลประกาศเกียรติคุณ
 */
async function clickHistory(row: ResponseObject) {
  modalHistory.value = true;
  filterSearch.value = "";

  showLoader();
  try {
    const res = await http.get(
      config.API.profileNewHonorHisById(row.id, empType.value)
    );
    rowsHistory.value = res.data.result;
  } catch (e) {
    messageError($q, e);
  } finally {
    hideLoader();
  }
}

/**
 * ยืนยีนการบันทึกข้อมูล
 */
function onSubmit() {
  dialogConfirm(
    $q,
    async () => {
      addEditData(isEdit.value);
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}

/**
 * เคลียร์ formDฟta
 */
function clearData() {
  id.value = "";
  issueDateYear.value = new Date().getFullYear();
  declHonorForm.issuer = "";
  declHonorForm.detail = "";
  declHonorForm.issueDate = new Date();
  declHonorForm.refCommandNo = "";
  declHonorForm.refCommandDate = null;
  declHonorForm.isDate = "false";
}

/**
 * ทำงานเมื่อ Components ถูกเรียกใช้งาน
 */
onMounted(() => {
  fetchData();
});
</script>
<template>
  <div class="row items-center q-gutter-x-sm q-pb-sm">
    <q-btn
      v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
      dense
      color="primary"
      icon="add"
      flat
      round
      @click="onClickOpenDialog()"
      ><q-tooltip>เพิ่มข้อมูล</q-tooltip></q-btn
    >

    <q-space />
    <q-input
      standout
      dense
      v-model="filterSearch"
      ref="filterRef"
      outlined
      placeholder="ค้นหา"
      debounce="300"
    >
      <template v-slot:append>
        <q-icon name="search" />
      </template>
    </q-input>
    <q-select
      v-if="modeView == 'table'"
      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"
    />
    <q-btn-toggle
      v-model="modeView"
      dense
      class="no-shadow toggle-borderd"
      toggle-color="grey-4"
      :options="[
        { value: 'table', slot: 'table' },
        { value: 'card', slot: 'card' },
      ]"
    >
      <template v-slot:table>
        <q-icon
          name="format_list_bulleted"
          size="24px"
          :style="{
            color: modeView === 'table' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>

      <template v-slot:card>
        <q-icon
          name="mdi-view-grid-outline"
          size="24px"
          :style="{
            color: modeView === 'card' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>
    </q-btn-toggle>
  </div>

  <d-table
    flat
    dense
    bordered
    :rows="rows"
    :paging="true"
    :columns="columns"
    :filter="filterSearch.trim()"
    :grid="modeView === 'card'"
    v-model:pagination="pagination"
    :visible-columns="visibleColumns"
    :rows-per-page-options="[20, 50, 100]"
    :card-container-class="modeView === 'card' ? 'q-col-gutter-md' : ''"
  >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th auto-width />
        <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" v-if="modeView === 'table'">
      <q-tr :props="props">
        <q-td auto-width>
          <q-btn
            flat
            dense
            round
            color="deep-purple"
            icon="mdi-history"
            @click="clickHistory(props.row)"
          >
            <q-tooltip>ประวัติแก้ไขประกาศเกียรติคุณ</q-tooltip>
          </q-btn>
          <q-btn
            v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
            flat
            dense
            round
            color="edit"
            icon="edit"
            @click="onClickOpenDialog(true, props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
        </q-td>
        <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-tr>
    </template>

    <template v-slot:item="props" v-else>
      <div class="col-xs-12 col-sm-6 col-md-6">
        <q-card bordered>
          <q-card-actions class="bg-grey-3" align="right">
            <q-btn
              flat
              round
              color="deep-purple"
              icon="mdi-history"
              @click.stop.prevent="clickHistory(props.row)"
            >
              <q-tooltip>ประวัติแก้ไขประกาศเกียรติคุณ</q-tooltip>
            </q-btn>
            <q-btn
              v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
              flat
              round
              color="edit"
              icon="edit"
              @click="onClickOpenDialog(true, props.row)"
            >
              <q-tooltip>แก่ไขข้อมุล</q-tooltip>
            </q-btn>
          </q-card-actions>
          <q-separator />
          <div>
            <q-item
              v-for="(col, index) in props.cols.filter(
                (col:any) => col.name !== 'desc'
              )"
              :key="col.name"
              :class="index % 2 !== 0 ? 'bg-grey-1' : ''"
            >
              <q-item-section class="col-7 text-grey-6">
                <q-item-label>{{ col.label }}</q-item-label>
              </q-item-section>

              <q-item-section class="text-dark">
                <q-item-label>
                  {{ col.value ? col.value : "-" }}
                </q-item-label>
              </q-item-section>
            </q-item>
          </div>
        </q-card>
      </div>
    </template>
  </d-table>

  <q-dialog v-model="modal" persistent>
    <q-card>
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          :tittle="
            isEdit
              ? 'แก้ไขข้อมูลประกาศเกียรติคุณ'
              : 'เพิ่มข้อมูลประกาศเกียรติคุณ'
          "
          :close="clickClose"
        />
        <q-separator />
        <q-card-section>
          <div class="row col-12 q-col-gutter-sm">
            <div class="row col-12 q-gutter-md q-py-sm text-grey-7">
              <q-radio
                v-model="(declHonorForm.isDate as string)"
                dense
                checked-icon="task_alt"
                unchecked-icon="panorama_fish_eye"
                val="false"
                label="ปี"
              />
              <q-radio
                v-model="(declHonorForm.isDate as string)"
                checked-icon="task_alt"
                unchecked-icon="panorama_fish_eye"
                val="true"
                label="วัน/เดือน/ปี"
                dense
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <datepicker
                autoApply
                year-picker
                v-model="issueDateYear"
                week-start="0"
                menu-class-name="modalfix"
                :locale="'th'"
                :enableTimePicker="false"
                @update:modelValue="
                  (v:number) =>
                    (declHonorForm.issueDate = new Date(
                      `${v}-01-01T00:00:02.010+07:00`
                    ))
                "
                v-if="declHonorForm.isDate === '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="issueDateYear + 543"
                    :rules="[
                    (val:string) =>
                      !!val ||
                      `${'กรุณาเลือกปีที่ได้รับ'}`,
                  ]"
                    :label="`${'ปีที่ได้รับ'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      />
                    </template>
                  </q-input>
                </template>
              </datepicker>
              <datepicker
                autoApply
                borderless
                v-else
                week-start="0"
                menu-class-name="modalfix"
                v-model="declHonorForm.issueDate"
                :locale="'th'"
                :enableTimePicker="false"
                @update:modelValue="
                  (v: Date) =>
                    (issueDateYear = parseInt(
                      v.toString().slice(11, 15)
                    ))
                "
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    hide-bottom-space
                    for="inputDatereceive"
                    ref="dateReceivedRef"
                    class="inputgreen"
                    :model-value="date2Thai(declHonorForm.issueDate)"
                    :label="`${'วันที่ได้รับ'}`"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือกวันที่ได้รับ'}`]"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      />
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                class="inputgreen"
                v-model="declHonorForm.issuer"
                :label="`${'ผู้มีอำนาจลงนาม'}`"
              />
            </div>
            <div class="col-12">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                class="inputgreen"
                v-model="declHonorForm.detail"
                :label="`${'รายละเอียด'}`"
                :rules="[(val:string) => !!val || `${'กรุณากรอกรายละเอียด'}`]"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                class="inputgreen"
                v-model="declHonorForm.refCommandNo"
                :label="`${'เลขที่คำสั่ง'}`"
              >
                <template v-slot:append>
                  <q-icon name="mdi-file" class="cursor-pointer" />
                </template>
              </q-input>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <datepicker
                autoApply
                borderless
                week-start="0"
                menu-class-name="modalfix"
                v-model="declHonorForm.refCommandDate"
                :locale="'th'"
                :enableTimePicker="false"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    clearable
                    hide-bottom-space
                    class="inputgreen"
                    :model-value="
                      declHonorForm.refCommandDate == null
                        ? null
                        : date2Thai(declHonorForm.refCommandDate)
                    "
                    :label="`${'เอกสารอ้างอิง (ลงวันที่)'}`"
                    @clear="declHonorForm.refCommandDate = null"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      />
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
          </div>
        </q-card-section>
        <q-separator color="grey-4" />
        <q-card-actions align="right">
          <q-btn label="บันทึก" id="onSubmit" type="submit" color="public">
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="modalHistory" persistent>
    <q-card style="min-width: 80%">
      <q-card-section class="flex justify-between" style="padding: 0">
        <DialogHeader
          tittle="ประวัติแก้ไขประกาศเกียรติคุณ"
          :close="
            () => (
              (modalHistory = false), (rowsHistory = []), (filterHistory = '')
            )
          "
        />
      </q-card-section>

      <q-separator />
      <q-card-section class="q-p-sm">
        <div class="row q-gutter-sm q-mb-sm">
          <q-space />
          <q-input
            standout
            dense
            v-model="filterHistory"
            ref="filterRef"
            outlined
            placeholder="ค้นหา"
            debounce="300"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
          <q-select
            v-model="visibleColumnsHistory"
            multiple
            outlined
            dense
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="columnsHistory"
            option-value="name"
            style="min-width: 140px"
          />
        </div>
        <d-table
          ref="table"
          flat
          bordered
          dense
          :columns="columnsHistory"
          :rows="rowsHistory"
          :paging="true"
          v-model:pagination="historyPagination"
          :rows-per-page-options="[10, 25, 50, 100]"
          :visible-columns="visibleColumnsHistory"
          :filter="filterHistory.trim()"
        >
          >
          <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">
              <q-td v-for="col in props.cols" :key="col.id">
                <div>
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
