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

import type { FormEmployee } from "@/modules/04_registryPerson/interface/request/Employee";
import type {
  EmployeeHistory,
  ResEmployee,
} from "@/modules/04_registryPerson/interface/response/Employee";

import DialogHeader from "@/components/DialogHeader.vue";

import type { QTableColumn } from "quasar";

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

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

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

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

/** ข้อมูลลูกจ้างชั่วคราว*/
const modalEdit = ref<boolean>(false);
const dataEmployee = reactive<ResEmployee>({
  id: "",
  positionEmployeeGroupId: "",
  positionEmployeeLineId: "",
  positionEmployeePositionId: "",
  employeeOc: "",
  employeeTypeIndividual: "",
  employeeWage: "",
  employeeMoneyIncrease: "",
  employeeMoneyAllowance: "",
  employeeMoneyEmployee: "",
  employeeMoneyEmployer: "",
});
const formData = reactive<FormEmployee>({
  positionEmployeeGroupId: "",
  positionEmployeeLineId: "",
  positionEmployeePositionId: "",
  employeeOc: "",
  employeeTypeIndividual: "",
  employeeWage: "",
  employeeMoneyIncrease: "",
  employeeMoneyAllowance: "",
  employeeMoneyEmployee: "",
  employeeMoneyEmployer: "",
});

/** function fetch ข้อมูลลูกจ้างชั่วคราว*/
function fetchData() {
  showLoader();
  http
    .get(config.API.informationEmployee(profileId.value))
    .then((res) => {
      const data = res.data.result;
      dataEmployee.positionEmployeeGroupId = data.positionEmployeeGroupId;
      dataEmployee.positionEmployeeLineId = data.positionEmployeeLineId;
      dataEmployee.positionEmployeePositionId = data.positionEmployeePositionId;
      dataEmployee.employeeOc = data.employeeOc;
      dataEmployee.employeeTypeIndividual = data.employeeTypeIndividual;
      dataEmployee.employeeWage = data.employeeWage;
      dataEmployee.employeeMoneyIncrease = data.employeeMoneyIncrease;
      dataEmployee.employeeMoneyAllowance = data.employeeMoneyAllowance;
      dataEmployee.employeeMoneyEmployee = data.employeeMoneyEmployee;
      dataEmployee.employeeMoneyEmployer = data.employeeMoneyEmployer;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function เปิด Dialog แก้ไขมูลลูกจ้างชั่วคราว*/
function onClickEdit() {
  modalEdit.value = true;
  formData.positionEmployeeGroupId = dataEmployee.positionEmployeeGroupId;
  formData.positionEmployeeLineId = dataEmployee.positionEmployeeLineId;
  formData.positionEmployeePositionId = dataEmployee.positionEmployeePositionId;
  formData.employeeOc = dataEmployee.employeeOc;
  formData.employeeTypeIndividual = dataEmployee.employeeTypeIndividual;
  formData.employeeWage = dataEmployee.employeeWage;
  formData.employeeMoneyIncrease = dataEmployee.employeeMoneyIncrease;
  formData.employeeMoneyAllowance = dataEmployee.employeeMoneyAllowance;
  formData.employeeMoneyEmployee = dataEmployee.employeeMoneyEmployee;
  formData.employeeMoneyEmployer = dataEmployee.employeeMoneyEmployer;
}

/** function ปิด Dialog แก้ไขมูลลูกจ้างชั่วคราว*/
function onCloseDialog() {
  modalEdit.value = false;
  formData.positionEmployeeGroupId = "";
  formData.positionEmployeeLineId = "";
  formData.positionEmployeePositionId = "";
  formData.employeeOc = "";
  formData.employeeTypeIndividual = "";
  formData.employeeWage = "";
  formData.employeeMoneyIncrease = "";
  formData.employeeMoneyAllowance = "";
  formData.employeeMoneyEmployee = "";
  formData.employeeMoneyEmployer = "";
}

/** function บันทึกแก้ไขมูลลูกจ้างชั่วคราว*/
function onSubmit() {
  dialogConfirm($q, () => {
    showLoader();
    http
      .put(config.API.informationEmployee(profileId.value), formData)
      .then(async () => {
        await fetchData();
        await success($q, "บันทึกข้อมูลสำเร็จ");
        onCloseDialog();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** ประวัติข้อมูลลูกจ้างชั่วคราว */
const modalHistory = ref<boolean>(false);
const filter = ref<string>("");
const rows = ref<EmployeeHistory[]>([]);
const columns = ref<QTableColumn[]>([
  {
    name: "positionEmployeeGroupId",
    align: "left",
    label: "กลุ่มงาน",
    sortable: true,
    field: "positionEmployeeGroupId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionEmployeeLineId",
    align: "left",
    label: "สายงาน",
    sortable: true,
    field: "positionEmployeeLineId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionEmployeePositionId",
    align: "left",
    label: "ตำแหน่งทางสายงาน",
    sortable: true,
    field: "positionEmployeePositionId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "employeeOc",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "employeeOc",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "employeeTypeIndividual",
    align: "left",
    label: "ประเภทบุคคล",
    sortable: true,
    field: "employeeTypeIndividual",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "employeeWage",
    align: "left",
    label: "ค่าจ้าง",
    sortable: true,
    field: "employeeWage",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "employeeMoneyIncrease",
    align: "left",
    label: "เงินเพิ่มการครองชีพชั่วคราว",
    sortable: true,
    field: "employeeMoneyIncrease",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "employeeMoneyAllowance",
    align: "left",
    label: "เงินช่วยเหลือการครองชีพชั่วคราว",
    sortable: true,
    field: "employeeMoneyAllowance",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "employeeMoneyEmployee",
    align: "left",
    label: "เงินสมทบประกันสังคม(ลูกจ้าง)",
    sortable: true,
    field: "employeeMoneyEmployee",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "employeeMoneyEmployer",
    align: "left",
    label: "เงินสมทบประกันสังคม(นายจ้าง)",
    sortable: true,
    field: "employeeMoneyEmployer",
    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[]>([
  "positionEmployeeGroupId",
  "positionEmployeeLineId",
  "positionEmployeePositionId",
  "employeeOc",
  "employeeTypeIndividual",
  "employeeWage",
  "employeeMoneyIncrease",
  "employeeMoneyAllowance",
  "employeeMoneyEmployee",
  "employeeMoneyEmployer",
  "createdFullName",
  "createdAt",
]);

function onClickHistory() {
  showLoader();
  modalHistory.value = true;
  http
    .get(config.API.informationHistoryEmployee(profileId.value))
    .then((res) => {
      const data = res.data.result;
      rows.value = data.sort(
        (a: any, b: any) =>
          new Date(b.lastUpdatedAt).getTime() -
          new Date(a.lastUpdatedAt).getTime()
      );
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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

<template>
  <div class="row q-gutter-sm items-center">
    <div class="toptitle col text-right q-gutter-x-sm">
      <q-btn
        v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
        flat
        round
        dense
        icon="edit"
        color="edit"
        @click="onClickEdit"
      >
        <q-tooltip>แก้ไขข้อมูล</q-tooltip>
      </q-btn>
      <q-btn
        flat
        round
        dense
        icon="mdi-history"
        color="deep-purple"
        @click="onClickHistory"
      >
        <q-tooltip>ประวัติแก้ไขข้อมูลลูกจ้างชั่วคราว</q-tooltip>
      </q-btn>
    </div>
  </div>

  <q-card bordered class="my-card bg-grey-1 q-pa-md">
    <div class="row q-col-gutter-md">
      <!-- column 1 -->
      <div class="col-12 col-sm-6 col-md-6 q-gutter-y-sm">
        <div class="row items-center">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>กลุ่มงาน</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ dataEmployee.positionEmployeeGroupId ?? "-" }}
          </div>
        </div>
        <div class="row items-center">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>สายงาน</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ dataEmployee.positionEmployeeLineId ?? "-" }}
          </div>
        </div>
        <div class="row items-center">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>ตำแหน่งทางสายงาน</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ dataEmployee.positionEmployeePositionId ?? "-" }}
          </div>
        </div>
        <div class="row items-center">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>สังกัด</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ dataEmployee.employeeOc ?? "-" }}
          </div>
        </div>
        <div class="row items-center">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>ประเภทบุคคล</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ dataEmployee.employeeTypeIndividual ?? "-" }}
          </div>
        </div>
      </div>
      <div class="col-12 col-sm-6 col-md-6 q-gutter-y-sm">
        <div class="row items-center">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>ค่าจ้าง</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ dataEmployee.employeeWage ?? "-" }}
          </div>
        </div>
        <div class="row items-start">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>เงินเพิ่มการครองชีพชั่วคราว</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ dataEmployee.employeeMoneyIncrease ?? "-" }}
          </div>
        </div>
        <div class="row items-start">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>เงินช่วยเหลือการครองชีพชั่วคราว</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ dataEmployee.employeeMoneyAllowance ?? "-" }}
          </div>
        </div>
        <div class="row items-start">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>เงินสมทบประกันสังคม (ลูกจ้าง)</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ dataEmployee.employeeMoneyEmployee ?? "-" }}
          </div>
        </div>
        <div class="row items-start">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>เงินสมทบประกันสังคม (นายจ้าง)</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ dataEmployee.employeeMoneyEmployer ?? "-" }}
          </div>
        </div>
      </div>
    </div>
  </q-card>

  <!-- Dialog แก้ไขข้อมูลลูกจ้างชั่วคราว -->
  <q-dialog v-model="modalEdit" persistent>
    <q-card>
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          tittle="แก้ไขข้อมูลลูกจ้างชั่วคราว"
          :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">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.positionEmployeeGroupId"
                class="inputgreen"
                label="กลุ่มงาน"
                :rules="[(val: string) => !!val || `${'กรุณากรอกกลุ่มงาน'}`]"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.positionEmployeeLineId"
                class="inputgreen"
                label="สายงาน"
                :rules="[(val: string) => !!val || `${'กรุณากรอกสายงาน'}`]"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.positionEmployeePositionId"
                class="inputgreen"
                label="ตำแหน่งทางสายงาน"
                :rules="[(val: string) => !!val || `${'กรุณากรอกตำแหน่งทางสายงาน'}`]"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.employeeOc"
                class="inputgreen"
                label="สังกัด"
              />
              <!-- :rules="[(val: string) => !!val || `${'กรุณากรอกสังกัด'}`]" -->
            </div>

            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.employeeTypeIndividual"
                class="inputgreen"
                label="ประเภทบุคคล"
              />
              <!-- :rules="[(val: string) => !!val || `${'กรุณากรอกประเภทบุคคล'}`]" -->
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.employeeWage"
                class="inputgreen"
                label="ค่าจ้าง"
                mask="###,###,###,###"
                reverse-fill-mask
              />
              <!-- :rules="[(val: string) => !!val || `${'กรุณากรอกค่าจ้าง'}`]" -->
            </div>

            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.employeeMoneyIncrease"
                class="inputgreen"
                label="เงินเพิ่มการครองชีพชั่วคราว"
                mask="###,###,###,###"
                reverse-fill-mask
              />
              <!-- :rules="[(val: string) => !!val || `${'กรุณากรอกเงินเพิ่มการครองชีพชั่วคราว'}`]" -->
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.employeeMoneyAllowance"
                class="inputgreen"
                label="เงินช่วยเหลือการครองชีพชั่วคราว"
                mask="###,###,###,###"
                reverse-fill-mask
              />
              <!-- :rules="[(val: string) => !!val || `${'กรุณากรอกเงินช่วยเหลือการครองชีพชั่วคราว'}`]" -->
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.employeeMoneyEmployee"
                class="inputgreen"
                label="เงินสมทบประกันสังคม(ลูกจ้าง)"
                mask="###,###,###,###"
                reverse-fill-mask
              />
              <!-- :rules="[(val: string) => !!val || `${'กรุณากรอกเงินสมทบประกันสังคม(ลูกจ้าง)'}`]" -->
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.employeeMoneyEmployer"
                class="inputgreen"
                label="เงินสมทบประกันสังคม(นายจ้าง)"
                mask="###,###,###,###"
                reverse-fill-mask
              />
              <!--  :rules="[(val: string) => !!val || `${'กรุณากรอกเงินสมทบประกันสังคม(นายจ้าง))'}`]" -->
            </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), (filter = ''), (rows = []))"
      />
      <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="filter"
            ref="filterRef"
            outlined
            placeholder="ค้นหา"
            debounce="300"
          >
            <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"
            option-value="name"
            style="min-width: 140px"
          />
        </div>

        <d-table
          ref="table"
          flat
          bordered
          dense
          :columns="columns"
          :rows="rows"
          :rows-per-page-options="[10, 25, 50, 100]"
          :visible-columns="visibleColumns"
          :filter="filter.trim()"
        >
          >
          <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">
              <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>
