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

import type { QTableColumn } from "quasar";
import type {
  Employment,
  EmploymentHistory,
} from "@/modules/04_registryPerson/interface/response/Employee";
import type { FormEmployment } from "@/modules/04_registryPerson/interface/request/Employee";

import DialogHeader from "@/components/DialogHeader.vue";
import DialogHistory from "@/modules/04_registryPerson/components/detail/DialogHistory.vue";

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

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

const profileId = ref<string>(route.params.id.toString());

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

/** ข้อมูลการจ้าง*/
const rows = ref<Employment[]>([]);
const rowsMain = ref<Employment[]>([]);
const filter = ref<string>("");

const columns = ref<QTableColumn[]>([
  {
    name: "date",
    align: "left",
    label: "วันที่จ้าง",
    sortable: true,
    field: "date",
    format: (v) => date2Thai(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "command",
    align: "left",
    label: "คำสั่งจ้าง",
    sortable: true,
    field: "command",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .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
        .toString()
        .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
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumns = ref<string[]>([
  "date",
  "command",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
const pagination = ref({
  sortBy: "",
});

const modalEmployment = ref<boolean>(false);
const isEdit = ref<boolean>(false);
const employmentId = ref<string>("");
const formData = reactive<FormEmployment>({
  date: null,
  command: "",
});

/** function fetch ข้อมูลรายการการจ้าง*/
async function fetchListEmployment() {
  showLoader();
  await http
    .get(config.API.employmentEmployee(profileId.value))
    .then((res) => {
      const data = res.data.result;
      rows.value = data;
      rowsMain.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function fetch ข้อมูลการจ้าง
 * @param id รายการการจ้าง
 */
function fetchDataEmployment(id: string) {
  showLoader();
  http
    .get(config.API.employmentEmployeeId(id))
    .then((res) => {
      const data = res.data.result;
      formData.date = data.date;
      formData.command = data.command;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function เปิด dialog Form ข้อมูลการจ้าง
 * @param statusEdit สถานะการ สร้าง หรือ แก้ไข
 * @param id รายการการจ้าง
 */
function onOpenDialog(statusEdit: boolean = false, id: string = "") {
  modalEmployment.value = true;
  if (statusEdit) {
    isEdit.value = statusEdit;
    employmentId.value = id;
    fetchDataEmployment(id);
  }
}

/** function ปิด dialog Form ข้อมูลการจ้าง*/
function onCloseDialog() {
  modalEmployment.value = false;
  isEdit.value = false;
  employmentId.value = "";
  formData.date = null;
  formData.command = "";
}

/** function บันทึกข้อมูลการจ้าง*/
function onSubmit() {
  dialogConfirm($q, () => {
    showLoader();
    const methods = isEdit.value ? "put" : "post";
    const id = isEdit.value ? employmentId.value : profileId.value;
    http[methods](config.API.employmentEmployee(id), {
      ...formData,
      date: convertDateToAPI(formData.date),
    })
      .then(async () => {
        await fetchListEmployment();
        await success($q, "บันทึกข้อมูลสำเร็จ");
        onCloseDialog();
      })
      .catch((err) => {
        messageError($q, err);
        hideLoader();
      })
      .finally(() => {});
  });
}

/**
 * function ลบข้อมูลรายการจ้าง
 * @param id รายการจ้าง
 */
function onDeleteEmployment(id: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.employmentEmployee(id))
      .then(() => {
        success($q, "ลบข้อมูลสำเร็จ");
        fetchListEmployment();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** ประวัติข้อมูลการจ้าง*/
const modalHistory = ref<boolean>(false);
const historyId = ref<string>("");

/**
 * function เปิด dialog ประวัติการแก้ไขข้อมูลการจ้าง
 * @param id รายการการจ้าง
 */
function onClickHistory(id: string) {
  historyId.value = id;
  modalHistory.value = true;
}

async function fetchDataHistory() {
  showLoader();
  try {
    const res = await http.get(
      config.API.employmentHistoryEmployee(historyId.value)
    );
    return res.data.result;
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
  }
}

function serchDataTable() {
  rows.value = onSearchDataTable(
    filter.value,
    rowsMain.value,
    columns.value ? columns.value.slice(0, 2) : []
  );
}

onMounted(() => {
  profileId.value && fetchListEmployment();
});
</script>

<template>
  <div class="flex items-center">
    <div class="q-gutter-sm">
      <q-btn
        v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
        size="12px"
        flat
        round
        color="primary"
        icon="mdi-plus"
        @click="onOpenDialog()"
      >
        <q-tooltip>เพิ่มข้อมูลการจ้าง</q-tooltip>
      </q-btn>
    </div>

    <q-space />
    <div class="q-gutter-sm" style="display: flex">
      <q-input
        outlined
        dense
        v-model="filter"
        label="ค้นหา"
        @keydown.enter.prevent="serchDataTable"
      >
        <template v-slot:append> <q-icon name="search" /> </template
      ></q-input>

      <q-select
        v-model="visibleColumns"
        multiple
        outlined
        dense
        options-dense
        :display-value="$q.lang.table.columns"
        emit-value
        map-options
        :options="columns?.slice(0, 2)"
        option-value="name"
        style="min-width: 140px"
      />
    </div>
  </div>

  <div class="q-mt-sm">
    <d-table
      flat
      bordered
      id="table"
      ref="table"
      :columns="columns?.slice(0, 2)"
      :rows="rows"
      row-key="dateEmployment"
      dense
      :visible-columns="visibleColumns"
      v-model:pagination="pagination"
    >
      <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">
        <q-tr :props="props">
          <q-td auto-width>
            <q-btn
              dense
              flat
              round
              color="deep-purple"
              icon="mdi-history"
              @click="onClickHistory(props.row.id)"
            >
              <q-tooltip>ประวัติข้อมูลการจ้าง </q-tooltip>
            </q-btn>
            <q-btn
              v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
              dense
              flat
              round
              color="edit"
              icon="edit"
              @click="onOpenDialog(true, props.row.id)"
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>
            <q-btn
              v-if="isLeave == false && checkPermission($route)?.attrIsDelete"
              dense
              flat
              round
              color="red"
              icon="mdi-delete"
              @click="onDeleteEmployment(props.row.id)"
            >
              <q-tooltip>ลบข้อมูล</q-tooltip></q-btn
            >
          </q-td>

          <q-td v-for="col in props.cols" :key="col.name" :props="props">
            <div>
              {{ col.value ? col.value : "-" }}
            </div>
          </q-td>
        </q-tr>
      </template>
    </d-table>
  </div>

  <!-- Dialog เพิ่มข้อมูลการจ้าง -->
  <q-dialog v-model="modalEmployment" persistent>
    <q-card style="width: 700px; max-width: 80vw">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          :tittle="isEdit ? 'แก้ข้อมูลการจ้าง' : 'เพิ่มข้อมูลการจ้าง'"
          :close="onCloseDialog"
        />

        <q-separator />
        <q-card-section>
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-xs-12 col-sm-6 col-md-6">
              <datepicker
                menu-class-name="modalfix"
                v-model="formData.date"
                :locale="'th'"
                autoApply
                borderless
                :enableTimePicker="false"
                week-start="0"
                class="inputgreen"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    outlined
                    dense
                    class="full-width datepicker"
                    :model-value="
                      formData.date != null ? date2Thai(formData.date) : null
                    "
                    label="วันที่จ้าง"
                    hide-bottom-space
                    :rules="[(val:string) => !!val || `${'กรุณาเลือกวันที่จ้าง'}`]"
                  >
                    <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-12 col-sm-6 col-md-6">
              <q-input
                dense
                class="inputgreen"
                outlined
                v-model="formData.command"
                label="คำสั่งจ้าง"
                hide-bottom-space
                :rules="[(val:string) => !!val || `${'กรุณากรอกคำสั่งจ้าง'}`]"
                lazy-rules
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <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>

  <!-- Dialog ประวัติการแก้ไขข้อมูลลูกจ้างชั่วคราว -->
  <DialogHistory
    v-model:modal="modalHistory"
    :visible-columns="visibleColumns"
    :title="`ประวัติแก้ไขข้อมูลการจ้าง`"
    :columns="columns"
    :fetch-data="fetchDataHistory"
  />
</template>

<style scoped></style>
