<script setup lang="ts">
import { onMounted, 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 { QTableColumn } from "quasar";
import type { FormEmployee } from "@/modules/04_registryPerson/interface/request/Employee";
import type { ResEmployee } from "@/modules/04_registryPerson/interface/response/Employee";

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

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: undefined,
  employeeMoneyIncrease: undefined,
  employeeMoneyAllowance: undefined,
  employeeMoneyEmployee: undefined,
  employeeMoneyEmployer: undefined,
});

/** function fetch ข้อมูลลูกจ้างชั่วคราว*/
async 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 = Number(dataEmployee.employeeWage) || undefined;
  formData.employeeMoneyIncrease =
    Number(dataEmployee.employeeMoneyIncrease) || undefined;
  formData.employeeMoneyAllowance =
    Number(dataEmployee.employeeMoneyAllowance) || undefined;
  formData.employeeMoneyEmployee =
    Number(dataEmployee.employeeMoneyEmployee) || undefined;
  formData.employeeMoneyEmployer =
    Number(dataEmployee.employeeMoneyEmployer) || undefined;
}

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

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

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

function onClickHistory() {
  modalHistory.value = true;
}

async function fetchDataHistory() {
  showLoader();
  try {
    const res = await http.get(
      config.API.informationHistoryEmployee(profileId.value)
    );
    return res.data.result;
  } 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 text-html">
            {{ 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">
              <CurruncyInput
                :edit="true"
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.employeeWage"
                class="inputgreen"
                label="ค่าจ้าง"
                :rules="[(val:number) => {
                              if (!val) return true;
                              const numVal = typeof val === 'number' ? val : Number(String(val).replace(/,/g, ''));
                              return numVal <= 10000000 || 'ค่าจ้างต้องไม่เกิน 10,000,000 บาท';
                            }]"
              />
              <!-- :rules="[(val: string) => !!val || `${'กรุณากรอกค่าจ้าง'}`]" -->
            </div>

            <div class="col-xs-12 col-sm-6 col-md-6">
              <CurruncyInput
                :edit="true"
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.employeeMoneyIncrease"
                class="inputgreen"
                label="เงินเพิ่มการครองชีพชั่วคราว"
                :rules="[(val:number) => {
                              if (!val) return true;
                              const numVal = typeof val === 'number' ? val : Number(String(val).replace(/,/g, ''));
                              return numVal <= 10000000 || 'เงินเพิ่มการครองชีพชั่วคราวต้องไม่เกิน 10,000,000 บาท';
                            }]"
              />
              <!-- :rules="[(val: string) => !!val || `${'กรุณากรอกเงินเพิ่มการครองชีพชั่วคราว'}`]" -->
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <CurruncyInput
                :edit="true"
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.employeeMoneyAllowance"
                class="inputgreen"
                label="เงินช่วยเหลือการครองชีพชั่วคราว"
                :rules="[(val:number) => {
                              if (!val) return true;
                              const numVal = typeof val === 'number' ? val : Number(String(val).replace(/,/g, ''));
                              return numVal <= 10000000 || 'เงินช่วยเหลือการครองชีพชั่วคราวต้องไม่เกิน 10,000,000 บาท';
                            }]"
              />
              <!-- :rules="[(val: string) => !!val || `${'กรุณากรอกเงินช่วยเหลือการครองชีพชั่วคราว'}`]" -->
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <CurruncyInput
                :edit="true"
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.employeeMoneyEmployee"
                class="inputgreen"
                label="เงินสมทบประกันสังคม(ลูกจ้าง)"
                :rules="[(val:number) => {
                              if (!val) return true;
                              const numVal = typeof val === 'number' ? val : Number(String(val).replace(/,/g, ''));
                              return numVal <= 10000000 || 'เงินสมทบประกันสังคม(ลูกจ้าง)ต้องไม่เกิน 10,000,000 บาท';
                            }]"
              />
              <!-- :rules="[(val: string) => !!val || `${'กรุณากรอกเงินสมทบประกันสังคม(ลูกจ้าง)'}`]" -->
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <CurruncyInput
                :edit="true"
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="formData.employeeMoneyEmployer"
                class="inputgreen"
                label="เงินสมทบประกันสังคม(นายจ้าง)"
                :rules="[(val:number) => {
                              if (!val) return true;
                              const numVal = typeof val === 'number' ? val : Number(String(val).replace(/,/g, ''));
                              return numVal <= 10000000 || 'เงินสมทบประกันสังคม(นายจ้าง)ต้องไม่เกิน 10,000,000 บาท';
                            }]"
              />
              <!--  :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 ประวัติการแก้ไขข้อมูลลูกจ้างชั่วคราว -->
  <DialogHistory
    v-model:modal="modalHistory"
    :visible-columns="visibleColumns"
    :title="`ประวัติแก้ไขข้อมูลส่วนตัว`"
    :columns="columns"
    :fetch-data="fetchDataHistory"
  />
</template>

<style scoped></style>
