<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 { QTableProps } 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 { useCounterMixin } from "@/stores/mixin";

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

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

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

/** ข้อมูลการจ้าง*/
const rows = ref<Employment[]>([]);
const filter = ref<string>("");
const columns = ref<QTableProps["columns"]>([
  {
    name: "date",
    align: "left",
    label: "วันที่จ้าง",
    sortable: false,
    field: "date",
    format: (v) => date2Thai(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "command",
    align: "left",
    label: "คำสั่งจ้าง",
    sortable: false,
    field: "command",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "createdFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "createdFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v, false, true),
  },
]);
const visibleColumns = ref<string[]>([
  "date",
  "command",
  "createdFullName",
  "createdAt",
]);
const modalEmployment = ref<boolean>(false);
const isEdit = ref<boolean>(false);
const employmentId = ref<string>("");
const formData = reactive<FormEmployment>({
  date: null,
  command: "",
});

/** function fetch ข้อมูลรายการการจ้าง*/
function fetchListEmployment() {
  showLoader();
  http
    .get(config.API.employmentEmployee(profileId.value))
    .then((res) => {
      const data = res.data.result;
      rows.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)
      .then(async () => {
        await fetchListEmployment();
        await success($q, "บันทึกข้อมูลสำเร็จ");
        onCloseDialog();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * 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 rowsHistory = ref<EmploymentHistory[]>([]);
const filterHistory = ref<string>("");

/**
 * function เปิด dialog ประวัติการแก้ไขข้อมูลการจ้าง
 * @param id รายการการจ้าง
 */
function onClickHistory(id: string) {
  modalHistory.value = true;
  showLoader();
  http
    .get(config.API.employmentHistoryEmployee(id))
    .then((res) => {
      const data = res.data.result;
      rowsHistory.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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="ค้นหา">
        <template v-slot:append>
          <q-icon
            v-if="filter == ''"
            name="search"
            @click.stop.prevent="filter = ''"
            class="cursor-pointer"
          />
          <q-icon
            v-if="filter"
            name="cancel"
            @click.stop.prevent="filter = ''"
            class="cursor-pointer"
          /> </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"
      :filter="filter"
      row-key="dateEmployment"
      :paging="true"
      dense
      :visible-columns="visibleColumns"
    >
      <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 ประวัติการแก้ไขข้อมูลลูกจ้างชั่วคราว -->
  <q-dialog v-model="modalHistory" persistent>
    <q-card style="min-width: 80%">
      <DialogHeader
        tittle="ประวัติแก้ไขข้อมูลส่วนตัว"
        :close="() => (modalHistory = false)"
      />
      <q-separator />

      <q-card-section style="max-height: 50vh" class="scroll">
        <div class="row q-gutter-sm q-mb-sm">
          <q-space />
          <q-input
            standout
            dense
            v-model="filterHistory"
            outlined
            placeholder="ค้นหา"
            debounce="300"
          >
            <template v-slot:append>
              <q-icon
                v-if="filterHistory == ''"
                name="search"
                @click.stop.prevent="filterHistory = ''"
                class="cursor-pointer"
              />
              <q-icon
                v-if="filterHistory"
                name="cancel"
                @click.stop.prevent="filterHistory = ''"
                class="cursor-pointer"
              />
            </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"
            option-value="name"
            
            style="min-width: 140px"
          />
        </div>

        <d-table
          ref="table"
          flat
          bordered
          dense
          :columns="columns"
          :rows="rowsHistory"
          :rows-per-page-options="[10, 25, 50, 100]"
          :visible-columns="visibleColumns"
          :filter="filterHistory"
        >
          >
          <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-tr>
          </template>
          <template v-slot:body="props">
            <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-tr>
          </template>
        </d-table>
      </q-card-section>

      <q-separator />

      <q-card-actions align="right"> </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
