<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,
  dialogMessageNotify,
} = useCounterMixin();

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

/** ข้อมูลลูกจ้างชั่วคราว*/
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(() => {
        success($q, "บันทึกข้อมูลสำเร็จ");
        fetchData();
        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",
    format: (v) => (v ? Number(v).toLocaleString() : ""),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "employeeMoneyIncrease",
    align: "left",
    label: "เงินเพิ่มการครองชึพชั่วคราว",
    sortable: true,
    field: "employeeMoneyIncrease",
    format: (v) => (v ? Number(v).toLocaleString() : ""),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "employeeMoneyAllowance",
    align: "left",
    label: "เงินช่วยเหลือการครองชึพชั่วคราว",
    sortable: true,
    field: "employeeMoneyAllowance",
    format: (v) => (v ? Number(v).toLocaleString() : ""),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "employeeMoneyEmployee",
    align: "left",
    label: "เงินสมทบประกันสังคม(ลูกจ้าง)",
    sortable: true,
    field: "employeeMoneyEmployee",
    format: (v) => (v ? Number(v).toLocaleString() : ""),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "employeeMoneyEmployer",
    align: "left",
    label: "เงินสมทบประกันสังคม(นายจ้าง)",
    sortable: true,
    field: "employeeMoneyEmployer",
    format: (v) => (v ? Number(v).toLocaleString() : ""),
    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),
  },
]);
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;
    })
    .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="checkPermission($route)?.attrIsUpdate"
        flat
        round
        dense
        icon="mdi-pencil-outline"
        color="primary"
        @click="onClickEdit"
      >
        <q-tooltip>แก้ไขข้อมูล</q-tooltip>
      </q-btn>
      <q-btn
        flat
        round
        dense
        icon="mdi-history"
        color="info"
        @click="onClickHistory"
      >
        <q-tooltip>ประวัติแก้ไขข้อมูลลูกจ้างชั่วคราว</q-tooltip>
      </q-btn>
    </div>
  </div>

  <q-card bordered class="my-card bg-grey-1 q-pa-md">
    <div :class="$q.screen.gt.xs ? 'row' : 'column'">
      <!-- column 1 -->
      <div class="col-md-7 col-12 row">
        <div class="col-5 text-grey-6 text-weight-medium">
          <div class="q-py-xs">กลุ่มงาน</div>
          <div class="q-py-xs">สายงาน</div>
          <div class="q-py-xs">ตำแหน่งทางสายงาน</div>
          <div class="q-py-xs">สังกัด</div>
          <div class="q-py-xs">ประเภทบุคคล</div>
        </div>

        <!-- data -->
        <div class="col-7">
          <div class="q-py-xs">
            {{ dataEmployee.positionEmployeeGroupId }}
          </div>
          <div class="q-py-xs">
            {{ dataEmployee.positionEmployeeLineId }}
          </div>
          <div class="q-py-xs">
            {{ dataEmployee.positionEmployeePositionId }}
          </div>
          <div class="q-py-xs">
            {{ dataEmployee.employeeOc }}
          </div>
          <div class="q-py-xs">
            {{ dataEmployee.employeeTypeIndividual }}
          </div>
        </div>
      </div>

      <!-- column 2 -->
      <div class="col-md-5 col-12 row">
        <div class="col-5 col text-grey-6 text-weight-medium">
          <div class="q-py-xs">ค่าจ้าง</div>
          <div class="q-py-xs">เงินเพิ่มการครองชึพชั่วคราว</div>
          <div class="q-py-xs">เงินช่วยเหลือการครองชึพชั่วคราว</div>
          <div class="q-py-xs">เงินสมทบประกันสังคม(ลูกจ้าง)</div>
          <div class="q-py-xs">เงินสมทบประกันสังคม(นายจ้าง)</div>
        </div>

        <div class="col-7">
          <div class="q-py-xs">
            {{ dataEmployee.employeeWage }}
          </div>
          <div class="q-py-xs">
            {{ dataEmployee.employeeMoneyIncrease }}
          </div>
          <div class="q-py-xs">
            {{ dataEmployee.employeeMoneyAllowance }}
          </div>
          <div class="q-py-xs">
            {{ dataEmployee.employeeMoneyEmployee }}
          </div>
          <div class="q-py-xs">
            {{ dataEmployee.employeeMoneyEmployer }}
          </div>
        </div>
      </div>
    </div>
  </q-card>

  <!-- Dialog แก้ไขข้อมูลลูกจ้างชั่วคราว -->
  <q-dialog v-model="modalEdit" persistent full-width>
    <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-6 col-sm-3 col-md-3">
              <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-6 col-sm-3 col-md-3">
              <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-6 col-sm-3 col-md-3">
              <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-6 col-sm-3 col-md-3">
              <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-6 col-sm-3 col-md-3">
              <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-6 col-sm-3 col-md-3">
              <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-6 col-sm-3 col-md-3">
              <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-6 col-sm-3 col-md-3">
              <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-6 col-sm-3 col-md-3">
              <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-6 col-sm-3 col-md-3">
              <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)"
      />
      <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
                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"
            option-value="name"
            options-cover
            style="min-width: 150px"
          />
        </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"
        >
          >
          <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>
