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

import { useCounterMixin } from "@/stores/mixin";
import DialogHeader from "@/components/DialogHeader.vue";
import DialogHisotory from "@/modules/04_registryNew/components/detail/Salary/02_NotReceiveSalaryHistory.vue";

import type { QTableProps } from "quasar";
import type { RowList } from "@/modules/04_registryNew/interface/index/salary";
import type { RequestNoPaidObject } from "@/modules/04_registryNew/interface/request/Salary";

const $q = useQuasar();
const route = useRoute();
const {
  date2Thai,
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  dialogRemove,
} = useCounterMixin();
const id = ref<string>("");
const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);

const modelView = ref<string>("table");
const modalDialog = ref<boolean>(false);
const modalHistory = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);
const rows = ref<RowList[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "date",
    align: "left",
    label: "วัน เดือน ปี",
    sortable: true,
    field: "date",
    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: "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",
    format: (v) => date2Thai(v),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumns = ref<string[]>([
  "date",
  "detail",
  "reference",
  "refCommandNo",
  "refCommandDate",
]);
const formData = reactive<RequestNoPaidObject>({
  date: null,
  reference: "",
  detail: "",
  refCommandNo: "",
  refCommandDate: null,
});
const formFilter = reactive({
  page: 1,
  pageSize: 10,
  keyword: "",
});
const maxPage = ref<number>(1);
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});

function onSubmit() {
  dialogConfirm($q, () => {
    isStatusEdit.value ? editData() : saveData();
    onClickCloseDialog();
  });
}

function onClickOpenDialog(StatusEdit: boolean = false, data: any = []) {
  isStatusEdit.value = StatusEdit;
  id.value = StatusEdit ? data.id : "";
  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;
  modalDialog.value = true;
}

function onClickCloseDialog() {
  modalDialog.value = false;
  isStatusEdit.value = false;
}

async function getData() {
  showLoader();
  await http
    .get(config.API.profileNewNoPaidByProfileId(profileId.value))
    .then((res) => {
      rows.value = res.data.result;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

async function saveData() {
  showLoader();
  await http
    .post(config.API.profileNewNoPaid, {
      ...formData,
      profileId: profileId.value,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      getData();
      onClickCloseDialog();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

async function editData() {
  showLoader();
  await http
    .patch(config.API.profileNewNoPaidById(id.value), {
      ...formData,
      profileId: undefined,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      getData();
      onClickCloseDialog();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

function onClickHistory(rowId: string) {
  id.value = rowId;
  modalHistory.value = true;
}

onMounted(() => {
  getData();
});
</script>
<template>
  <div class="row items-center q-gutter-x-sm q-py-sm">
    <q-btn color="teal-5" icon="add" flat round @click="onClickOpenDialog()"
      ><q-tooltip>เพิ่มข้อมูล</q-tooltip></q-btn
    >

    <q-space />
    <q-input
      standout
      dense
      v-model="formFilter.keyword"
      ref="filterRef"
      outlined
      placeholder="ค้นหา"
      debounce="300"
    >
      <template v-slot:append>
        <q-icon
          v-if="formFilter.keyword == ''"
          name="search"
          @click.stop.prevent="formFilter.keyword = ''"
          class="cursor-pointer"
        />
        <q-icon
          v-if="formFilter.keyword"
          name="cancel"
          @click.stop.prevent="formFilter.keyword = ''"
          class="cursor-pointer"
        />
      </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"
    />
    <q-btn-toggle
      v-model="modelView"
      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: modelView === 'table' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>

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

  <d-table
    ref="table"
    row-key="id"
    flat
    bordered
    dense
    :columns="columns"
    :rows="rows"
    :paging="true"
    :filter="formFilter.keyword"
    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">
          <div>{{ col.value ? col.value : "-" }}</div>
        </q-td>
        <q-td auto-width>
          <q-btn
            flat
            dense
            round
            class="q-mr-xs"
            size="14px"
            color="primary"
            icon="mdi-pencil-outline"
            @click="onClickOpenDialog(true, props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
          <q-btn
            color="info"
            flat
            dense
            round
            size="14px"
            icon="mdi-history"
            @click.stop.prevent="onClickHistory(props.row.id)"
          >
            <q-tooltip>ประวัติบันทึกวันที่ไม่ได้รับเงินเดือนฯ</q-tooltip>
          </q-btn>
          <!-- <q-btn
            flat
            dense
            round
            size="14px"
            color="red"
            icon="mdi-delete"
            @click="
              dialogRemove($q, async () => await deleteData(props.row.id))
            "
          >
            <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-6 col-lg-3 grid-style-transition"
      >
        <q-card bordered>
          <q-card-actions class="bg-grey-3" align="right">
            <q-btn
              flat
              round
              color="primary"
              icon="mdi-pencil-outline"
              @click="onClickOpenDialog(true, props.row)"
            >
              <q-tooltip>แก่ไขข้อมุล</q-tooltip>
            </q-btn>
            <q-btn
              flat
              round
              color="info"
              icon="history"
              @click="onClickHistory(props.row.id)"
            >
              <q-tooltip>ประวัติบันทึกวันที่ไม่ได้รับเงินเดือนฯ</q-tooltip>
            </q-btn>
          </q-card-actions>
          <q-separator />
          <q-list>
            <q-item
              v-for="(col, index) in props.cols.filter(
                (col) => col.name !== 'desc'
              )"
              :key="col.name"
              :class="index % 2 !== 0 ? 'bg-grey-1' : ''"
            >
              <q-item-section class="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>
          </q-list>
        </q-card>
      </div>
    </template>
  </d-table>

  <q-dialog v-model="modalDialog" persistent>
    <q-layout
      view="lHh lpr lFf"
      container
      style="height: 300px; min-width: 80%"
      class="bg-white"
    >
      <q-form @submit.prevent greedy @validation-success="onSubmit">
        <q-header>
          <q-toolbar>
            <DialogHeader
              :tittle="
                isStatusEdit
                  ? 'แก้ไขบันทึกวันที่ไม่ได้รับเงินเดือนฯ'
                  : 'เพิ่มบันทึกวันที่ไม่ได้รับเงินเดือนฯ'
              "
              :close="onClickCloseDialog"
            />
          </q-toolbar>
          <q-separator color="grey-4" />
        </q-header>

        <q-page-container>
          <q-page class="q-pa-md">
            <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
                            class="inputgreen"
                            :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"
                        class="inputgreen"
                        :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"
                        class="inputgreen"
                        :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"
                        class="inputgreen"
                        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
                        menu-class-name="modalfix"
                        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
                            clearable
                            outlined
                            dense
                            borderless
                            class="inputgreen"
                            :model-value="
                        formData.refCommandDate == null ? null : date2Thai(formData.refCommandDate as Date)
                        "
                            hide-bottom-space
                            :label="`${'เอกสารอ้างอิง (ลงวันที่)'}`"
                            @clear="formData.refCommandDate = null"
                          >
                            <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-page>
        </q-page-container>
        <q-separator />

        <q-footer>
          <q-separator color="grey-4" />
          <q-toolbar class="fit row wrap justify-end items-start content-start">
            <q-btn
              dense
              unelevated
              label="บันทึก"
              id="onSubmit"
              type="submit"
              color="public"
              class="q-px-md"
            >
              <q-tooltip>บันทึกข้อมูล</q-tooltip>
            </q-btn>
          </q-toolbar>
        </q-footer>
      </q-form>
    </q-layout>
  </q-dialog>

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

<style scoped></style>
