<script setup lang="ts">
import { useQuasar, type QTableProps } from "quasar";
import { ref, onMounted, reactive } from "vue";
import type {
  RowList,
  FormFilter,
  MyObjectRef,
} from "@/modules/04_registryNew/interface/index/other";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import DialogHeader from "@/components/DialogHeader.vue";
import { useRoute } from "vue-router";
import DialogHistory from "@/modules/04_registryNew/components/detail/Other/01_OtherInformationHistory.vue";
const route = useRoute();
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  date2Thai,
  showLoader,
  hideLoader,
  success,
  messageError,
  dialogRemove,
  dialogConfirm,
} = mixin;

const id = ref<string>("");

const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});
const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);
const mode = ref<string>("table");
const filterKeyword = ref<string>("");
const rows = ref<RowList[]>([]);

const currentPage = ref<number>(1);
const maxPage = ref<number>(1);
const formFilter = reactive<FormFilter>({
  page: 1,
  pageSize: 12,
  keyword: "",
  type: "",
  posType: "",
  posLevel: "",
  retireYear: "",
  rangeYear: { min: 0, max: 60 },
  isShowRetire: false,
  isProbation: false,
});

/** modal */
const modal = ref<boolean>(false);
const edit = ref<boolean>(false);
const modalHistory = ref<boolean>(false);

const date = ref<Date | null>(null);
const detail = ref<string>();

const dateRef = ref<object | null>(null);
const detailRef = ref<object | null>(null);
const objectRef: MyObjectRef = {
  date: dateRef,
  detail: detailRef,
};

const visibleColumns = ref<String[]>(["date", "detail"]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "date",
    align: "left",
    label: "วันที่",
    sortable: true,
    field: "date",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width: 50px;",
    format: (v) => date2Thai(v),
  },
  {
    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" }),
  },
]);

/** เปิด dialog */
function openDialogAdd() {
  modal.value = true;
}

/** dialog แก้ไข
 * @param props ข้อมูล row ของรายการ
 */
function openDialogEdit(props: RowList) {
  modal.value = true;
  edit.value = true;

  id.value = props.id;
  date.value = props.date;
  detail.value = props.detail;
}
/** dialog ประติ
 * @param id id รายการ
 */
function openDialogHistory(idOrder: string) {
  id.value = idOrder;
  modalHistory.value = true;
}

/** ปิด dialog */
function closeDialog() {
  modal.value = false;
  edit.value = false;
  date.value = null;
  detail.value = "";
}

/** validate check*/
function validateForm() {
  dialogConfirm(
    $q,
    async () => {
      if (edit.value) {
        editData();
      } else {
        saveData();
      }
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}

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

/**
 * บันทึกแก้ไขข้อมูล
 */
async function editData() {
  showLoader();
  await http
    .patch(config.API.profileNewOtherById(id.value), {
      date: date.value,
      detail: detail.value,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      getData();
      closeDialog();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

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

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

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

  <d-table
    :rows="rows"
    :columns="columns"
    dense
    bordered
    v-model:pagination="pagination"
    flat
    :card-container-class="mode === 'card' ? 'q-col-gutter-md' : ''"
    :grid="mode === 'card'"
    :paging="true"
    :visible-columns="visibleColumns"
    :filter="filterKeyword"
    :rows-per-page-options="[10, 25, 50, 100]"
  >
    <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-th>
      </q-tr>
    </template>
    <template v-slot:body="props" v-if="mode === '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="openDialogEdit(props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
          <q-btn
            color="info"
            flat
            dense
            round
            size="14px"
            icon="mdi-history"
            @click="openDialogHistory(props.row.id)"
          >
            <q-tooltip>ประวัติแก้ไขอื่นๆ</q-tooltip>
          </q-btn>
        </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 flat bordered>
          <div class="row bg-grey-3">
            <q-space />
            <div class="q-gutter-x-sm">
              <q-btn
                color="primary"
                icon="mdi-pencil-outline"
                flat
                round
                @click="openDialogEdit(props.row)"
                ><q-tooltip>แก้ไข</q-tooltip></q-btn
              >
              <q-btn
                color="info"
                icon="mdi-history"
                flat
                round
                @click="openDialogHistory(props.row.id)"
                ><q-tooltip>ประวิติแก้ไขอื่นๆ</q-tooltip></q-btn
              >
            </div>
          </div>
          <q-separator />
          <q-card-section class="q-pa-none">
            <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-card-section>
        </q-card>
      </div>
    </template>
  </d-table>

  <!-- dialog add edit -->
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 70%">
      <q-form greedy @submit.prevent @validation-success="validateForm">
        <DialogHeader
          :tittle="edit ? 'แก้ไขข้อมูลอื่นๆ' : 'เพิ่มข้อมูลอื่นๆ'"
          :close="closeDialog"
        />
        <q-separator />

        <q-card-section style="max-height: 60vh" class="scroll">
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-xs-6 col-sm-3 col-md-3">
              <datepicker
                menu-class-name="modalfix"
                v-model="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"
                    class="full-width inputgreen cursor-pointer"
                    outlined
                    dense
                    :model-value="date2Thai(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-xs-6 col-sm-9 col-md-9">
              <q-input
                ref="detailRef"
                class="full-width inputgreen cursor-pointer"
                outlined
                dense
                lazy-rules
                v-model="detail"
                :rules="[(val) => !!val || `${'กรุณากรอกรายละเอียด'}`]"
                hide-bottom-space
                :label="`${'รายละเอียด'}`"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn
            dense
            unelevated
            label="บันทึก"
            id="onSubmit"
            type="submit"
            color="public"
            class="q-px-md"
          >
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

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

<style scoped></style>
