div
<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute } from "vue-router";
import { useQuasar, type QTableProps } from "quasar";

import { useCounterMixin } from "@/stores/mixin";
import DialogHeader from "@/components/DialogHeader.vue";
import type {
  DetailData,
  FormFilter,
  DataOptionLeave,
  DataOption,
  ResponseTotalObject,
  MyObjectRef,
} from "@/modules/04_registryNew/interface/index/leave";

import DialogHistory from "@/modules/04_registryNew/components/detail/GovernmentInformation/03_LeaveHistory.vue";
import http from "@/plugins/http";
import config from "@/app.config";

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

const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});
const mode = ref<string>("table");
const filterKeyword = ref<string>("");
const currentPage = ref<number>(1);
const maxPage = ref<number>(1);
const rows = ref<DetailData[]>([]);
const formFilter = reactive<FormFilter>({
  page: 1,
  pageSize: 12,
  keyword: "",
  type: "",
  posType: "",
  posLevel: "",
  retireYear: "",
  rangeYear: { min: 0, max: 60 },
  isShowRetire: false,
  isProbation: false,
});

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

const reason = ref<string>(""); //เหตุผล
const numLeave = ref<number>(1);
const dateRange = ref<[Date, Date]>([new Date(), new Date()]);
const numUsedLeave = ref<number>(0);
const typeLeave = ref<any>();
const typeLeaveOption = ref<DataOptionLeave[]>([]);
const typeLeaveOptionFilter = ref<DataOptionLeave[]>([]);

const statLeave = ref<string>("");
const statLeaveOption = ref<DataOption[]>([
  { id: "approve", name: "ผ่านการอนุมัติ" },
  { id: "reject", name: "ไม่ผ่านการอนุมัติ" },
  { id: "cancel", name: "ยกเลิก" },
  { id: "waitting", name: "รออนุมัติ" },
]);
const statLeaveOptionFilter = ref<DataOption[]>([
  { id: "approve", name: "ผ่านการอนุมัติ" },
  { id: "reject", name: "ไม่ผ่านการอนุมัติ" },
  { id: "cancel", name: "ยกเลิก" },
  { id: "waitting", name: "รออนุมัติ" },
]);

const statusLeave = (val: string) => {
  switch (val) {
    case "waitting":
      return "รออนุมัติ";
    case "reject":
      return "ไม่ผ่านการอนุมัติ";
    case "approve":
      return "ผ่านการอนุมัติ";
    case "cancel":
      return "ยกเลิก";
    default:
      return "-";
  }
};

const clickEditRowType = () => {
  const filter = typeLeaveOptionFilter.value.filter(
    (v: DataOptionLeave) => v.id == typeLeave.value
  );
  if (filter.length > 0) {
    numUsedLeave.value = filter[0].totalLeave;
  }
};

const typeLeaveRef = ref<object | null>(null);
const dateRangeRef = ref<object | null>(null);
const numLeaveRef = ref<object | null>(null);
const statLeaveRef = ref<object | null>(null);
const reasonRef = ref<object | null>(null);
const objectRef: MyObjectRef = {
  typeLeave: typeLeaveRef,
  dateRange: dateRangeRef,
  numLeave: numLeaveRef,
  statLeave: statLeaveRef,
  reason: reasonRef,
};

const visibleColumns = ref<String[]>([
  "no",
  "typeLeave",
  "dateLeave",
  "numLeave",
  "status",
  "reason",
]);

const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "typeLeave",
    align: "left",
    label: "ประเภทการลา",
    sortable: true,
    field: "typeLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateLeave",
    align: "left",
    label: "วัน เดือน ปี ที่ลา",
    sortable: true,
    field: "dateLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "numLeave",
    align: "left",
    label: "จำนวนวันลา",
    sortable: true,
    field: "numLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "status",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "reason",
    align: "left",
    label: "เหตุผล",
    sortable: true,
    field: "reason",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

function openDialogAdd() {
  modal.value = true;
  edit.value = false;
  showLoader();
  http
    .get(config.API.profileNewLeaveType())
    .then((res) => {
      const dataOp = res.data.result.map((item: any) => ({
        id: item.id,
        name: item.name,
        code: item.code,
      }));

      typeLeaveOption.value = dataOp;
      typeLeaveOptionFilter.value = dataOp;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังชั้นดูข้อมูลประวัติแก้ไขข้อมูลที่เลือก
 * @param row ข้อมูล row ที่ดูประวัติการแก้ไข
 */
function clickTotal() {
  rowsTotal.value = [];
  showLoader();
  http
    .get(config.API.profileNewLeaveType())
    .then((res) => {
      const dataOp = res.data.result.map((item: DataOption) => ({
        id: item.id,
        name: item.name,
      }));

      typeLeaveOption.value = dataOp;
      typeLeaveOptionFilter.value = dataOp;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function openDialogEdit(props: DetailData) {
  edit.value = true;
  modal.value = true;
  id.value = props.id;
  typeLeave.value = {
    id: props.typeLeaveId,
    name: props.typeLeave,
    code: props.code,
  };
  statLeave.value = props.status;
  reason.value = props.reason;
  dateRange.value = [
    new Date(props.dateStartLeave as Date),
    new Date(props.dateEndLeave as Date),
  ];
  numLeave.value = props.numLeave;
  clickTotal();
  if (rowsTotal.value.length > 0) {
    let data: DataOptionLeave[] = [];
    rowsTotal.value.map((e: ResponseTotalObject) => {
      data.push({
        id: e.typeLeaveId,
        name: e.typeLeave,
        totalLeave: e.totalLeave,
      });
    });
    typeLeaveOption.value = data;
    typeLeaveOptionFilter.value = data;
  }
}

/** ปิด dialog */
function closeDialog() {
  modal.value = false;
  edit.value = false;

  id.value = "";
  typeLeave.value = "";
  statLeave.value = "";
  reason.value = "";
  dateRange.value = [new Date(), new Date()];
  numLeave.value = 1;
  numUsedLeave.value = 0;
}

function filterSelector(val: any, update: Function, filtername: string) {
  switch (filtername) {
    case "typeLeaveOption":
      update(() => {
        typeLeaveOption.value = typeLeaveOptionFilter.value.filter(
          (v: DataOptionLeave) =>
            v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
        );
      });
      break;
    case "statLeaveOption":
      update(() => {
        statLeaveOption.value = statLeaveOptionFilter.value.filter(
          (v: DataOption) =>
            v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
        );
      });
      break;
    default:
      break;
  }
}

/**
 * แปลงช่วงวันที่ถ้า2ค่าเป็นวันเดียวกันจะโชววันเดียวแต่ถ้าไม่เท่ากันจะแสดงเป็นช่วง
 * @param val ช่วงวันที่
 */
function dateThaiRange(val: [Date, Date]) {
  if (val === null) {
  } else if (date2Thai(val[0]) === date2Thai(val[1])) {
    return `${date2Thai(val[0])}`;
  } else {
    return `${date2Thai(val[0])} - ${date2Thai(val[1])} `;
  }
}

/**
 * ฟังชั้นดูข้อมูลประวัติแก้ไขข้อมูลที่เลือก
 * @param row ข้อมูล row ที่ดูประวัติการแก้ไข
 */
function openDialogHistory(idOrder: string) {
  modalHistory.value = true;
  id.value = idOrder;
}

/** validate check*/
function validateForm() {
  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, async () => {
      if (edit.value == false) {
        saveData();
      } else {
        editData();
      }
    });
  }
}

/**
 * บันทึกเพิ่มข้อมูล
 */
function saveData() {
  showLoader();
  http
    .post(config.API.profileNewLeave(), {
      profileId: profileId.value,
      leaveTypeId: typeLeave.value.id,
      dateLeaveStart: dateToISO(dateRange.value[0]),
      dateLeaveEnd: dateToISO(dateRange.value[1]),
      leaveDays: numLeave.value,
      leaveCount: 0,
      totalLeave: 0,
      status: statLeave.value,
      reason: reason.value,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      closeDialog();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      getData();
    });
}

/**
 * บันทึกแก้ไขข้อมูล
 */
const editData = async () => {
  showLoader();
  http
    .patch(config.API.profileNewLeaveById(id.value), {
      leaveTypeId: typeLeave.value.id,
      dateLeaveStart: dateToISO(dateRange.value[0]),
      dateLeaveEnd: dateToISO(dateRange.value[1]),
      leaveDays: numLeave.value,
      leaveCount: 0,
      totalLeave: 0,
      status: statLeave.value,
      reason: reason.value,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      closeDialog();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      getData();
    });
};

function getData() {
  showLoader();
  http
    .get(config.API.profileNewLeaveById(profileId.value))
    .then((res) => {
      console.log(res.data.result);
      const data = res.data.result;
      rows.value = data.map((item: any) => ({
        id: item.id,
        typeLeave: item.leaveType.name,
        code: item.leaveType.refCommandDate,
        dateStartLeave: item.dateLeaveStart,
        dateEndLeave: item.dateLeaveEnd,
        numLeave: item.leaveDays,
        status: item.status,
        reason: item.reason,
        typeLeaveId: item.leaveTypeId,
      }));
    })
    .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
    ref="table"
    flat
    bordered
    dense
    :card-container-class="mode === 'card' ? 'q-col-gutter-md' : ''"
    :columns="columns"
    :rows="rows"
    :grid="mode === 'card'"
    :paging="true"
    v-model:pagination="pagination"
    :rows-per-page-options="[10, 25, 50, 100]"
    :visible-columns="visibleColumns"
    :filter="filterKeyword"
  >
    >
    <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 v-if="col.name === 'no'">
            {{
              (formFilter.page - 1) * formFilter.pageSize + props.rowIndex + 1
            }}
          </div>
          <div v-else-if="col.name == 'dateLeave'">
            {{
              dateThaiRange([props.row.dateStartLeave, props.row.dateEndLeave])
            }}
          </div>
          <div v-else-if="col.name == 'status'">
            {{ statusLeave(col.value) }}
          </div>
          <div v-else>
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
        <q-td auto-width>
          <q-btn
            color="primary"
            flat
            dense
            round
            class="q-mr-xs"
            size="14px"
            icon="mdi-pencil-outline"
            clickable
            @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-12 col-md-12 col-lg-6">
        <q-card flat bordered class="q-pa-none">
          <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">
            <div class="row q-pa-sm">
              <div class="col-3 text-grey-6 text-weight-medium">
                ประเภทการลา
              </div>
              <div class="col-9">
                {{ props.row.typeLeave !== "" ? props.row.typeLeave : "-" }}
              </div>
            </div>
            <q-separator />
            <div class="row q-pa-sm bg-grey-2">
              <div class="col-3 text-grey-6 text-weight-medium">
                วัน/เดือน/ปี ที่ลา
              </div>
              <div class="col-3">
                {{
                  props.row.dateStartLeave
                    ? date2Thai(props.row.dateStartLeave)
                    : "-"
                }}
              </div>
              <div class="col-3 text-grey-6 text-weight-medium">จำนวนวันลา</div>
              <div class="col-3">
                {{ props.row.numLeave ? props.row.numLeave : "-" }}
              </div>
            </div>
            <q-separator />
            <div class="row q-pa-sm bg-grey-2">
              <div class="col-3 text-grey-6 text-weight-medium">สถานะ</div>
              <div class="col-3">
                {{ props.row.status ? statusLeave(props.row.status) : "-" }}
              </div>
              <div class="col-3 text-grey-6 text-weight-medium">เหตุผล</div>
              <div class="col-3">
                {{ props.row.reason !== "" ? props.row.reason : "-" }}
              </div>
            </div>
          </q-card-section>
        </q-card>
      </div>
    </template>
  </d-table>

  <!-- dialog add edit -->
  <q-dialog v-model="modal" persistent>
    <q-card>
      <form @submit.prevent="validateForm">
        <DialogHeader
          :tittle="edit ? 'แก้ไขข้อมูลการลา' : 'เพิ่มข้อมูลการลา'"
          :close="closeDialog"
        />
        <q-separator color="grey-4" />

        <q-card-section style="max-height: 50vh" class="scroll">
            <div class="row col-12 q-col-gutter-x-xs q-col-gutter-y-xs">
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-select
                  ref="typeLeaveRef"
                  class="full-width inputgreen cursor-pointer"
                  outlined
                  dense
                  lazy-rules
                  v-model="typeLeave"
                  :rules="[(val:string) => !!val || `${'กรุณาเลือกประเภทการลา'}`]"
                  hide-bottom-space
                  :label="`${'ประเภทการลา'}`"
                  @update:modelValue="clickEditRowType"
                  map-options
                  option-label="name"
                  :options="typeLeaveOption"
                  option-value="id"
                  use-input
                  input-debounce="0"
                  @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'typeLeaveOption'
                      ) "
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <datepicker
                  :readonly="!typeLeave"
                  menu-class-name="modalfix"
                  v-model="dateRange"
                  :locale="'th'"
                  autoApply
                  :enableTimePicker="false"
                  week-start="0"
                  range
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      :readonly="!typeLeave"
                      class="full-width inputgreen cursor-pointer"
                      outlined
                      dense
                      ref="dateRangeRef"
                      :model-value="dateThaiRange(dateRange)"
                      :rules="[(val:string) => !!val || `${'กรุณาเลือกวัน เดือน ปีที่ลา'}`]"
                      hide-bottom-space
                      :label="`${'วัน เดือน ปีที่ลา'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          color="primary"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-input
                  ref="numLeaveRef"
                  class="full-width inputgreen cursor-pointer"
                  outlined
                  dense
                  lazy-rules
                  v-model="numLeave"
                  type="number"
                  :rules="[(val:string) => !!val || `${'กรุณากรอกจำนวนวันที่ลา'}`]"
                  hide-bottom-space
                  :label="`${'จำนวนวันที่ลา'}`"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-select
                  ref="statLeaveRef"
                  class="full-width inputgreen cursor-pointer"
                  outlined
                  dense
                  lazy-rules
                  v-model="statLeave"
                  :rules="[(val:string) => !!val || `${'กรุณาเลือกสถานะการลา'}`]"
                  hide-bottom-space
                  :label="`${'สถานะการลา'}`"
                  emit-value
                  map-options
                  option-label="name"
                  :options="statLeaveOption"
                  option-value="id"
                  use-input
                  input-debounce="0"
                  @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'statLeaveOption'
                      ) "
                />
              </div>
              <div class="col-xs-12 col-sm-12 col-md-12">
                <q-input
                  ref="reasonRef"
                  class="full-width inputgreen cursor-pointer"
                  outlined
                  dense
                  lazy-rules
                  v-model="reason"
                  type="textarea"
                  :rules="[(val:string) => !!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>
      </form>
    </q-card>
  </q-dialog>

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

<style scoped></style>
