<template>
  <q-card flat bordered class="col-12 q-px-lg q-py-md q-mt-md">
    <HeaderTop
      v-model:edit="edit"
      header="ข้อมูลลูกจ้างชั่วคราว"
      icon="mdi-account"
      :save="saveData"
      :changeBtn="changeBtn"
      :disable="statusEdit"
      :cancel="refreshData"
      :addEmployee="statusAdd()"
      :history="!statusAdd()"
    />
    <q-form ref="myform">
      <div class="row col-12 items-center q-col-gutter-x-sm q-col-gutter-y-sm">
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            :class="getClass(edit)"
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaTempData.positionEmployeeGroupId"
            :label="`${'กลุ่มงาน'}`"
            @update:modelValue="!edit"
            emit-value
            map-options
            option-label="name"
            :options="employeeGroupOptions"
            :rules="[(val:string) => !!val || `${'กรุณาเลือกกลุ่มงาน'}`]"
            option-value="id"
            hide-bottom-space
            use-input
            input-debounce="0"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            :class="getClass(edit)"
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaTempData.positionEmployeeLineId"
            :label="`${'สายงาน'}`"
            @update:modelValue="!edit"
            emit-value
            map-options
            option-label="name"
            :options="positionEmployeeLineOptions"
            :rules="[(val:string) => !!val || `${'กรุณาเลือกสายงาน'}`]"
            option-value="id"
            hide-bottom-space
            use-input
            input-debounce="0"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            :class="getClass(edit)"
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaTempData.positionEmployeePositionId"
            :label="`${'ชื่อตำแหน่งทางสายงาน'}`"
            @update:modelValue="!edit"
            emit-value
            map-options
            option-label="name"
            :options="positionEmployeePositionOptions"
            :rules="[(val:string) => !!val || `${'กรุณาเลือกชื่อตำแหน่งทางสายงาน'}`]"
            option-value="id"
            hide-bottom-space
            use-input
            input-debounce="0"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaTempData.employeeOc"
            :label="`${'สังกัด'}`"
          />
        </div>

        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            :readonly="!edit"
            :borderless="!edit"
            v-model="informaTempData.employeeTypeIndividual"
            :label="`${'ประเภทบุคคล'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <CurrencyInput
            v-model="informaTempData.employeeWage"
            :edit="edit"
            :options="{
              currency: 'THB',
            }"
            :label="`${'ค่าจ้าง'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <CurrencyInput
            v-model="informaTempData.employeeMoneyIncrease"
            :edit="edit"
            :options="{
              currency: 'THB',
            }"
            :label="`${'เงินเพิ่มการครองชีพชั่วคราว'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <CurrencyInput
            v-model="informaTempData.employeeMoneyAllowance"
            :edit="edit"
            :options="{
              currency: 'THB',
            }"
            :label="`${'เงินช่วยเหลือการครองชีพชั่วคราว'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <CurrencyInput
            v-model="informaTempData.employeeMoneyEmployee"
            :edit="edit"
            :options="{
              currency: 'THB',
            }"
            :label="`${'เงินสมทบประกันสังคม(ลูกจ้าง)'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <CurrencyInput
            v-model="informaTempData.employeeMoneyEmployer"
            :edit="edit"
            :options="{
              currency: 'THB',
            }"
            :label="`${'เงินสมทบประกันสังคม(นายจ้าง)'}`"
          />
        </div>
      </div>
    </q-form>
  </q-card>
  <HistoryTable
    :rows="rowsHistory"
    :columns="columnsHistory"
    :filter="filterHistory"
    :visible-columns="visibleColumnsHistory"
    v-model:modal="modalHistory"
    v-model:inputfilter="filterHistory"
    v-model:inputvisible="visibleColumnsHistory"
    v-model:tittle="tittleHistory"
  >
    <template #columns="props">
      <q-tr :props="props">
        <q-td v-for="col in props.cols" :key="col.name" :props="props">
          <div v-if="col.name == 'createdAt'" class="table_ellipsis">
            {{ date2Thai(col.value) }}
          </div>
          <div
            v-else-if="col.name == 'registrationSame'"
            class="table_ellipsis"
          >
            {{ col.value ? "ใช่" : "ไม่" }}
          </div>
          <div v-else class="table_ellipsis">
            {{ col.value }}
          </div>
        </q-td>
      </q-tr>
    </template>
  </HistoryTable>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useCounterMixin } from "@/stores/mixin";

import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";
import type { DataOption } from "@/modules/04_registry/components/profileType";
import { defaultTempInformation } from "@/modules/04_registry/components/profileType";
import HeaderTop from "@/modules/08_registryEmployee/views/topEmployeeTemp.vue";
import HistoryTable from "@/components/TableHistory.vue";
import { useRoute } from "vue-router";
import type { QTableProps } from "quasar";
import CurrencyInput from "@/components/CurruncyInput.vue";

const props = defineProps({
  statusEdit: {
    type: Boolean,
    required: true,
  },
  fetchDataProfile: {
    type: Function,
    default: () => console.log("not function"),
  },
  statusAdd: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["update:statusEdit"]);

const route = useRoute();
const $q = useQuasar();

const mixin = useCounterMixin();
const {
  date2Thai,
  success,
  messageError,
  showLoader,
  hideLoader,
  dialogConfirm,
} = mixin;
const edit = ref<boolean>(false);
const myform = ref<any>();
const employeeOc = ref<string>("");
const codec = ref<string>("");
const rows = ref<any[]>([]);
const positionEmployeeGroupId = ref<string>("");
const employeeGroupOptions = ref<DataOption[]>([]);
const positionEmployeeLineId = ref<string>("");
const positionEmployeeLineOptions = ref<DataOption[]>([]);
const positionEmployeePositionId = ref<string>("");
const positionEmployeePositionOptions = ref<DataOption[]>([]);
const employeeWage = ref<number>(0);
const employeeTypeIndividual = ref<string>("");
const employeeMoneyIncrease = ref<number>(0);
const employeeMoneyAllowance = ref<number>(0);
const employeeMoneyEmployee = ref<number>(0);
const employeeMoneyEmployer = ref<number>(0);

const informaTempData = ref<any>(defaultTempInformation);
const rowsHistory = ref<any[]>([]); //select data history
const tittleHistory = ref<string>("ประวัติแก้ไขข้อมูลที่อยู่"); //
const filterHistory = ref<string>(""); //search data table history
const modalHistory = ref<boolean>(false); //modal ประวัติการแก้ไขข้อมูล
const columnsHistory = ref<QTableProps["columns"]>([
  {
    name: "positionEmployeeGroupId",
    align: "left",
    label: "กลุ่มงาน",
    sortable: true,
    field: "positionEmployeeGroupId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.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.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.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "employeeOc",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "employeeOc",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.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.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.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.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.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.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.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "createdFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "createdFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumnsHistory = ref<String[]>([
  "employeeMoneyIncrease",
  "employeeMoneyAllowance",
  "employeeMoneyEmployee",
  "employeeMoneyEmployer",
  "positionEmployeeGroupId",
  "positionEmployeePositionId",
  "positionEmployeeLineId",
  "employeeTypeIndividual",
  "employeeOc",
  "employeeWage",
]);

onMounted(async () => {
  await fetchData();
  await fetchDataSelector();
});

const statusAdd = () => props.statusAdd;

const fetchDataSelector = async () => {
  showLoader();
  await fetchEmployeeGroup();
  await fetchpositionEmployeeLine();
  await fetchPositionEmployeePosition();
  hideLoader();
};

/**
 * ฟังชั้นดูข้อมูลประวัติแก้ไขข้อมูลที่เลือก
 */
// const clickHistory = async () => {
//   modalHistory.value = true;
//   showLoader();
//   await http
//     .get(config.API.profileEmployeeTempId(route.params.id.toString()))
//     .then((res) => {
//       let data = res.data.result;
//       rowsHistory.value = [];
//       data.map((e: any) => {
//         rowsHistory.value.push({
//           employeeMoneyIncrease: e.employeeMoneyIncrease,
//           employeeMoneyAllowance: e.employeeMoneyAllowance,
//           employeeMoneyEmployee: e.employeeMoneyEmployee,
//           employeeMoneyEmployer: e.employeeMoneyEmployer,
//           positionEmployeeGroupId: e.positionEmployeeGroupId,
//           positionEmployeePositionId: e.positionEmployeePositionId,
//           positionEmployeeLineId: e.positionEmployeeLineId,
//           employeeTypeIndividual: e.employeeTypeIndividual,
//           employeeOc: e.employeeOc,
//           employeeWage: e.employeeWage,
//           createdFullName: e.createdFullName,
//           createdAt: new Date(e.createdAt),
//         });
//       });
//     })
//     .catch((e) => {
//       messageError($q, e);
//     })
//     .finally(() => {
//       hideLoader();
//     });
// };

const refreshData = async () => {
  myform.value.reset();
  await getNewData();
};

const getNewData = async () => {
  await fetchData();
};

const fetchData = async () => {
  if (route.params.id) {
    showLoader();
    await http
      .get(config.API.profileEmployeeTempId(route.params.id.toString()))
      .then((res) => {
        // const data: any = res.data.result;
        // rows.value = [];
        // data.map((e: any) => {
        //   rows.value.push({
        //     employeeMoneyIncrease: e.employeeMoneyIncrease,
        //     employeeMoneyAllowance: e.employeeMoneyAllowance,
        //     employeeMoneyEmployee: e.employeeMoneyEmployee,
        //     employeeMoneyEmployer: e.employeeMoneyEmployer,
        //     positionEmployeeGroupId: e.positionEmployeeGroupId,
        //     positionEmployeePositionId: e.positionEmployeePositionId,
        //     positionEmployeeLineId: e.positionEmployeeLineId,
        //     employeeTypeIndividual: e.employeeTypeIndividual,
        //     employeeOc: e.employeeOc,
        //     employeeWage: e.employeeWage,
        //   });
        //   console.log(res);
        // });
        const data: any = res.data.result;
        informaTempData.value.employeeMoneyIncrease =
          data.employeeMoneyIncrease;
        informaTempData.value.employeeMoneyAllowance =
          data.employeeMoneyAllowance;
        informaTempData.value.employeeMoneyEmployee =
          data.employeeMoneyEmployee;
        informaTempData.value.employeeMoneyEmployer =
          data.employeeMoneyEmployer;
        informaTempData.value.positionEmployeeGroupId =
          data.positionEmployeeGroupId;
        informaTempData.value.positionEmployeePositionId =
          data.positionEmployeePositionId;
        informaTempData.value.positionEmployeeLineId =
          data.positionEmployeeLineId;
        informaTempData.value.employeeTypeIndividual =
          data.employeeTypeIndividual;
        informaTempData.value.employeeOc = data.employeeOc;
        informaTempData.value.employeeWage = data.employeeWage;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        hideLoader();
        await props.fetchDataProfile();
      });
  }
};

// กลุ่มงาน
const fetchEmployeeGroup = async () => {
  await http
    .get(config.API.positionEmployeeGroup)
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: DataOption) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });

      employeeGroupOptions.value = option;
    })
    .catch((e) => {
      messageError($q, e);
    });
};

const fetchpositionEmployeeLine = async () => {
  await http
    .get(config.API.positionEmployeeLine)
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: DataOption) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });

      positionEmployeeLineOptions.value = option;
    })
    .catch((e) => {
      messageError($q, e);
    });
};

//ชื่อตำแหน่ง

const fetchPositionEmployeePosition = async () => {
  await http
    .get(config.API.positionEmployeePosition)
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: DataOption) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });

      positionEmployeePositionOptions.value = option;
    })
    .catch((e) => {
      messageError($q, e);
    });
};

const editData = async () => {
  const body: any = {
    employeeMoneyIncrease: informaTempData.value.employeeMoneyIncrease,
    employeeMoneyAllowance: informaTempData.value.employeeMoneyAllowance,
    employeeMoneyEmployee: informaTempData.value.employeeMoneyEmployee,
    employeeMoneyEmployer: informaTempData.value.employeeMoneyEmployer,
    positionEmployeeGroupId: informaTempData.value.positionEmployeeGroupId,
    positionEmployeePositionId:
      informaTempData.value.positionEmployeePositionId,
    positionEmployeeLineId: informaTempData.value.positionEmployeeLineId,
    employeeTypeIndividual: informaTempData.value.employeeTypeIndividual,
    employeeOc: informaTempData.value.employeeOc,
    employeeWage: informaTempData.value.employeeWage,
  };
  showLoader();
  await http
    .put(config.API.profileEmployeeTempId(route.params.id.toString()), body)
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      edit.value = false;
      emit("update:statusEdit", false);
      await getNewData();
    });
};

const addData = async () => {
  const body: any = {
    employeeMoneyIncrease: employeeMoneyIncrease.value,
    employeeMoneyAllowance: employeeMoneyAllowance.value,
    employeeMoneyEmployee: employeeMoneyEmployee.value,
    employeeMoneyEmployer: employeeMoneyEmployer.value,
    positionEmployeeGroupId: positionEmployeeGroupId.value,
    positionEmployeePositionId: positionEmployeePositionId.value,
    positionEmployeeLineId: positionEmployeeLineId.value,
    employeeTypeIndividual: employeeTypeIndividual.value,
    employeeOc: employeeOc.value,
    employeeWage: employeeWage.value,
  };
  showLoader();
  await http
    .put(config.API.profileInforId(route.params.id.toString()), body)
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      edit.value = false;
      emit("update:statusEdit", false);
      await fetchData();
    });
};
const saveData = async () => {
  dialogConfirm($q, () => Datasave());
};
const Datasave = async () => {
  await myform.value.validate().then(async (success: boolean) => {
    if (success) {
      if (props.statusAdd) {
        await addData();
      } else {
        await editData();
      }
    } else {
    }
  });
};

const changeBtn = async () => {
  if (edit.value == true) {
    if (props.statusEdit === true) {
      edit.value = false;
    } else {
      emit("update:statusEdit", true);
    }
  } else {
    emit("update:statusEdit", false);
  }
};

const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};
</script>
