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

import type { QTableProps } from "quasar";
import type { ObjectReceiveRef } from "@/modules/04_registryNew/interface/index/salary";

import DialogHeader from "@/components/DialogHeader.vue";
import DialogHisotory from "@/modules/04_registryNew/components/detail/Salary/02_NotReceiveSalaryHistory.vue";

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

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

const columns = ref<QTableProps["columns"]>([
  {
    name: "date",
    align: "left",
    label: "วัน เดือน ปี",
    sortable: true,
    field: "date",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "reference",
    align: "left",
    label: "เอกสารอ้างอิง",
    sortable: true,
    field: "reference",
    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",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumns = ref<string[]>([
  "date",
  "detail",
  "reference",
  "refCommandNo",
  "refCommandDate",
]);
const rows = ref<any>([
  {
    date: new Date(),
    detail: "รายละเอีียด",
    reference: "อ้างอิง",
    refCommandNo: "เลขที่คำสั่ง",
    refCommandDate: new Date(),
  },
  {
    date: new Date(),
    detail: "รายละเอีียด",
    reference: "อ้างอิง",
    refCommandNo: "เลขที่คำสั่ง",
    refCommandDate: new Date(),
  },
  {
    date: new Date(),
    detail: "รายละเอีียด",
    reference: "อ้างอิง",
    refCommandNo: "เลขที่คำสั่ง",
    refCommandDate: new Date(),
  },
  {
    date: new Date(),
    detail: "รายละเอีียด",
    reference: "อ้างอิง",
    refCommandNo: "เลขที่คำสั่ง",
    refCommandDate: new Date(),
  },
]);

const formFilter = reactive({
  page: 1,
  pageSize: 10,
  keyword: "",
});

const formData = reactive({
  date: null,
  reference: "",
  detail: "",
  refCommandNo: "",
  refCommandDate: null,
});

const dateRef = ref<Object | null>(null);
const referenceRef = ref<Object | null>(null);
const detailRef = ref<Object | null>(null);

const ObjectRef: ObjectReceiveRef = {
  date: dateRef,
  reference: referenceRef,
  detail: detailRef,
};

const modelView = ref<string>("table");
const maxPage = ref<number>(1);

const pagination = ref({
  page: formFilter.page,
  rowsPerPage: formFilter.pageSize,
});

const modalDialog = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);

function onSubmit() {
  const hasError = [];
  for (const key in ObjectRef) {
    if (Object.prototype.hasOwnProperty.call(ObjectRef, key)) {
      const property = ObjectRef[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    dialogConfirm($q, () => {
      onClickCloseDialog();
    });
  }
}

function onClickOpenDialog(StatusEdit: boolean = false, data: any = []) {
  isStatusEdit.value = StatusEdit;
  modalDialog.value = true;

  formData.date = StatusEdit ? data.date : null;
  formData.reference = StatusEdit ? data.reference : "";
  formData.detail = StatusEdit ? data.detail : "";
  formData.refCommandNo = StatusEdit ? data.refCommandNo : "";
  formData.refCommandDate = StatusEdit ? data.refCommandDate : null;
}
function onClickCloseDialog() {
  modalDialog.value = false;
}

const modalHistory = ref<boolean>(false);
function ocClikcHistory() {
  modalHistory.value = true;
}
</script>
<template>
  <!-- <div class="row items-center q-gutter-sm">
    <div class="toptitle text-dark row items-center q-py-xs">
      บันทึกวันที่ไม่ได้รับเงินเดือนฯ
    </div>
  </div> -->
  <q-toolbar style="padding: 0px" class="text-primary">
    <q-btn flat round dense icon="add" @click="onClickOpenDialog()">
      <q-tooltip>เพิ่ม</q-tooltip>
    </q-btn>
    <q-space />
    <q-input
      dense
      outlined
      v-model="formFilter.keyword"
      label="ค้นหา"
      class="q-mr-sm"
    >
      <template v-slot:append>
        <q-icon name="search" />
      </template>
    </q-input>

    <q-select
      v-if="modelView === 'table'"
      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="q-mr-sm"
    />

    <q-btn-toggle
      v-model="modelView"
      toggle-color="grey-4"
      class="no-shadow toggle-borderd"
      :options="[
        { value: 'table', slot: 'table' },
        { value: 'card', slot: 'card' },
      ]"
    >
      <template v-slot:table>
        <q-icon
          name="format_list_bulleted"
          size="sm"
          :style="{
            color: modelView === 'table' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>
      <template v-slot:card>
        <q-icon
          name="mdi-view-grid-outline"
          size="sm"
          :style="{
            color: modelView === 'card' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>
    </q-btn-toggle>
  </q-toolbar>

  <d-table
    ref="table"
    row-key="id"
    flat
    bordered
    dense
    :columns="columns"
    :rows="rows"
    :paging="true"
    v-model:pagination="pagination"
    :rows-per-page-options="[20, 50, 100]"
    :visible-columns="visibleColumns"
    :grid="modelView === 'card'"
  >
    <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" v-if="modelView === 'table'">
      <q-tr :props="props" class="cursor-pointer">
        <q-td
          v-for="col in props.cols"
          :key="col.id"
          @click.stop.prevent="onClickOpenDialog(true, props.row)"
        >
          <div v-if="col.name === 'date'">
            {{ col.value ? date2Thai(col.value) : "-" }}
          </div>
          <div v-else-if="col.name === 'refCommandDate'">
            {{ col.value ? date2Thai(col.value) : "-" }}
          </div>
          <div v-else>{{ col.value ? col.value : "-" }}</div>
        </q-td>
        <q-td auto-width>
          <q-btn
            color="info"
            flat
            dense
            round
            size="14px"
            icon="mdi-history"
            @click.stop.prevent="ocClikcHistory"
          >
            <q-tooltip>ประวัติบันทึกวันที่ไม่ได้รับเงินเดือนฯ</q-tooltip>
          </q-btn>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:item="props" v-else>
      <div
        class="q-pa-xs col-xs-12 col-sm-6 col-md-4 col-lg-3 grid-style-transition"
      >
        <q-card bordered>
          <q-card-actions align="right">
            <q-btn
              flat
              round
              color="edit"
              icon="edit"
              @click.stop.prevent="onClickOpenDialog(true, props.row)"
            >
              <q-tooltip>แก่ไขข้อมุล</q-tooltip>
            </q-btn>
            <q-btn
              flat
              round
              color="primary"
              icon="history"
              @click.stop.prevent="ocClikcHistory"
            >
              <q-tooltip>ประวัติบันทึกวันที่ไม่ได้รับเงินเดือนฯ</q-tooltip>
            </q-btn>
          </q-card-actions>
          <q-separator />
          <q-list>
            <q-item
              v-for="col in props.cols.filter((col) => col.name !== 'desc')"
              :key="col.name"
            >
              <q-item-section>
                <q-item-label>{{ col.label }}</q-item-label>
              </q-item-section>
              <q-item-section side>
                <q-item-label caption v-if="col.name === 'date'">
                  {{ col.value ? date2Thai(col.value) : "-" }}
                </q-item-label>
                <q-item-label caption v-else-if="col.name === 'refCommandDate'">
                  {{ col.value ? date2Thai(col.value) : "-" }}</q-item-label
                >
                <q-item-label caption v-else>{{ col.value }}</q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-card>
      </div>
    </template>
    <template v-slot:pagination="scope">
      <q-pagination
        v-model="formFilter.page"
        active-color="primary"
        color="dark"
        :max="Number(maxPage)"
        :max-pages="5"
        size="sm"
        boundary-links
        direction-links
      ></q-pagination>
    </template>
  </d-table>

  <q-dialog v-model="modalDialog" persistent>
    <q-card style="width: 600px">
      <form @submit.prevent.stop="onSubmit">
        <DialogHeader
          tittle="บันทึกวันที่ไม่ได้รับเงินเดือนฯ"
          :close="onClickCloseDialog"
        />
        <!-- วันที่ไม่ได้รับเงินเดือนหรือได้รับเงินเดือนไม่เต็ม หรือวันที่มิได้ประจำปฏิบัติหน้าที่อยู่ในเขตที่ได้มีประกาศใช้กฎอัยการศึก -->
        <q-separator />
        <q-card-section class="q-pa-sm bg-grey-1">
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-xs-12 col-sm-12">
              <q-card flat bordered class="fit q-pa-sm">
                <div class="row col-12 q-col-gutter-xs">
                  <div class="col-xs-6 col-sm-6 col-md-6">
                    <datepicker
                      menu-class-name="modalfix"
                      v-model="formData.date"
                      :locale="'th'"
                      autoApply
                      :enableTimePicker="false"
                      week-start="0"
                    >
                      <template #year="{ year }">{{ year + 543 }}</template>
                      <template #year-overlay-value="{ value }">{{
                        parseInt(value + 543)
                      }}</template>
                      <template #trigger>
                        <q-input
                          ref="dateRef"
                          outlined
                          dense
                          borderless
                          :model-value="date2Thai(formData.date)"
                          :rules="[
                            (val) => !!val || `${'กรุณาเลือก วัน/เดือน/ปี'}`,
                          ]"
                          hide-bottom-space
                          :label="`${'วัน/เดือน/ปี'}`"
                        >
                          <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-6">
                    <q-input
                      ref="referenceRef"
                      outlined
                      dense
                      autogrow
                      lazy-rules
                      borderless
                      v-model="formData.reference"
                      :rules="[(val) => !!val || `${'กรุณากรอกเอกสารอ้างอิง'}`]"
                      hide-bottom-space
                      :label="`${'เอกสารอ้างอิง'}`"
                    />
                  </div>
                  <div class="col-12">
                    <q-input
                      ref="detailRef"
                      outlined
                      dense
                      autogrow
                      lazy-rules
                      borderless
                      v-model="formData.detail"
                      :rules="[(val) => !!val || `${'กรุณากรอกรายละเอียด'}`]"
                      hide-bottom-space
                      :label="`${'รายละเอียด'}`"
                    />
                  </div>
                  <div class="col-xs-6 col-sm-6 col-md-6">
                    <q-input
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.refCommandNo"
                      hide-bottom-space
                      :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
                      v-model="formData.refCommandDate"
                      :locale="'th'"
                      autoApply
                      :enableTimePicker="false"
                      week-start="0"
                    >
                      <template #year="{ year }">{{ year + 543 }}</template>
                      <template #year-overlay-value="{ value }">{{
                        parseInt(value + 543)
                      }}</template>
                      <template #trigger>
                        <q-input
                          outlined
                          dense
                          borderless
                          :model-value="
                        formData.refCommandDate == null ? null : date2Thai(formData.refCommandDate as Date)
                        "
                          hide-bottom-space
                          :label="`${'เอกสารอ้างอิง (ลงวันที่)'}`"
                        >
                          <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>
            </div>
          </div>
        </q-card-section>
        <q-separator />

        <q-card-section align="right">
          <q-btn label="บันทึก" type="submit" color="secondary">
            <q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-section>
      </form>
    </q-card>
  </q-dialog>

  <DialogHisotory v-model:modal="modalHistory" />
</template>

<style scoped></style>
