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

import type { QTableProps } from "quasar";
import type {
  DataOption2,
  DataOption,
} from "@/modules/04_registryNew/interface/index/Main";
import type { ObjectSalaryRef } from "@/modules/04_registryNew/interface/index/salary";
import type { FormSalaryNew } from "@/modules/04_registryNew/interface/request/Salary";

import DialogHeader from "@/components/DialogHeader.vue";
import DialogHistory from "@/modules/04_registryNew/components/detail/Salary/01_PositionSalaryHistory.vue";

import { useCounterMixin } from "@/stores/mixin";
import { useSalaryDataStore } from "@/modules/04_registryNew/stores/salary";

const $q = useQuasar();
const route = useRoute();
const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);
const store = useSalaryDataStore();
const {
  date2Thai,
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
} = useCounterMixin();

const columns = ref<QTableProps["columns"]>([
  {
    name: "date",
    align: "left",
    label: "วัน เดือน ปี",
    sortable: true,
    field: "date",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
  },
  {
    name: "amount",
    align: "left",
    label: "เงินเดือน",
    sortable: true,
    field: "amount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Number(v).toLocaleString(),
  },
  {
    name: "positionSalaryAmount",
    align: "left",
    label: "เงินประจำตำแหน่ง",
    sortable: true,
    field: "positionSalaryAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Number(v).toLocaleString(),
  },
  {
    name: "mouthSalaryAmount",
    align: "left",
    label: "เงินค่าตอบแทนรายเดือน",
    sortable: true,
    field: "mouthSalaryAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Number(v).toLocaleString(),
  },

  {
    name: "posNo",
    align: "left",
    label: "ตำแหน่งเลขที่",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "positionType",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: true,
    field: "positionType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionLevel",
    align: "left",
    label: "ระดับ",
    sortable: true,
    field: "positionLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "templateDoc",
    align: "left",
    label: "เอกสารอ้างอิง",
    sortable: true,
    field: "templateDoc",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "refCommandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "refCommandNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "date",
  "amount",
  "positionSalaryAmount",
  "mouthSalaryAmount",
  "posNo",
  "positionType",
  "positionLevel",
  "templateDoc",
  "refCommandNo",
]);
const formFilter = reactive({
  page: 1,
  pageSize: 10,
  keyword: "",
});
const maxPage = ref<number>(1);

const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});

const rows = ref<any>([]);

const formDataSalary = reactive<FormSalaryNew>({
  date: null,
  posNo: "",
  templatePos: "",
  position: "",
  positionLine: "",
  positionPathSide: "",
  positionType: "",
  positionLevel: "",
  positionExecutive: "",
  salaryCompensation: null,
  salary: null,
  salaryPos: null,
  refCommandNo: "",
  templateDoc: "",
  doc: "",
});

const modalDialogSalary = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);
const salaryId = ref<string>("");
const dataLevel = ref<any[]>([]);

const posNoOptions = ref<DataOption2[]>(store.optionTemplatePos);
const positionLineOptions = ref<DataOption2[]>(store.optionTemplatePos);
const posTypeOptions = ref<DataOption[]>([]);
const posTypeOptionsMain = ref<DataOption[]>([]);
const posLevelOption = ref<DataOption[]>([]);
const posLevelOptionMain = ref<DataOption[]>([]);

const docOption = ref<DataOption2[]>(store.optionTemplateDoc);

function fetchListSalary() {
  showLoader();
  http
    .get(config.API.profileListSalaryNew(profileId.value))
    .then((res) => {
      rows.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function fetchType() {
  http
    .get(config.API.orgPosType)
    .then((res) => {
      dataLevel.value = res.data.result;
      posTypeOptionsMain.value = res.data.result.map((e: any) => ({
        id: e.id,
        name: e.posTypeName,
      }));
      posTypeOptions.value = posTypeOptionsMain.value;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

async function updateSelectType(val: string, status: boolean = false) {
  const listLevel = await dataLevel.value.find(
    (e: any) => e.posTypeName === val
  );
  if (listLevel) {
    posLevelOptionMain.value = listLevel.posLevels.map((e: any) => ({
      id: e.id,
      name: e.posLevelName,
    }));
    posLevelOption.value = posLevelOptionMain.value;
    formDataSalary.positionLevel = !status ? "" : formDataSalary.positionLevel;
  }
}

async function onClickOpenDialog(statusEdit: boolean = false, data: any = []) {
  dataLevel.value.length === 0 && (await fetchType());
  setTimeout(async () => {
    statusEdit && (await updateSelectType(data.positionType, true));
    isStatusEdit.value = statusEdit;
  }, 500);
  posLevelOptionMain.value = !statusEdit ? [] : posLevelOptionMain.value;
  modalDialogSalary.value = true;
  salaryId.value = data.id;
  formDataSalary.date = statusEdit ? data.date : null;
  formDataSalary.posNo = statusEdit ? data.posNo : "";
  formDataSalary.templatePos = "";
  formDataSalary.position = statusEdit ? data.position : "";
  formDataSalary.positionLine = statusEdit ? data.positionLine : "";
  formDataSalary.positionType = statusEdit ? data.positionType : "";
  formDataSalary.positionLevel = statusEdit ? data.positionLevel : "";
  formDataSalary.positionPathSide = statusEdit ? data.positionPathSide : "";
  formDataSalary.positionExecutive = statusEdit ? data.positionExecutive : "";
  formDataSalary.salaryCompensation = statusEdit ? data.mouthSalaryAmount : "";
  formDataSalary.salary = statusEdit ? data.amount : "";
  formDataSalary.salaryPos = statusEdit ? data.positionSalaryAmount : "";
  formDataSalary.refCommandNo = statusEdit ? data.refCommandNo : "";
  formDataSalary.templateDoc = "";
  formDataSalary.doc = statusEdit ? data.templateDoc : "";
}

function onClickCloseDialog() {
  modalDialogSalary.value = false;
}

function filterSelector(val: any, update: Function, filtername: string) {
  switch (filtername) {
    case "pos":
      update(() => {
        posNoOptions.value = store.optionTemplatePos.filter(
          (v: DataOption2) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "positionLine":
      update(() => {
        positionLineOptions.value = store.optionTemplatePos.filter(
          (v: DataOption2) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "posType":
      update(() => {
        posTypeOptions.value = posTypeOptionsMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "posLevel":
      update(() => {
        posLevelOption.value = posLevelOptionMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "doc":
      update(() => {
        docOption.value = store.optionTemplateDoc.filter(
          (v: DataOption2) => v.name.indexOf(val) > -1
        );
      });
      break;

    default:
      break;
  }
}

function updatePos(val: string) {
  formDataSalary.position = val;
}

function updateDoc(val: string) {
  formDataSalary.doc = val;
}

function onSubmit() {
  dialogConfirm($q, () => {
    submit();
  });
}

async function submit() {
  const formData = {
    profileId: isStatusEdit.value ? undefined : profileId.value,
    date: formDataSalary.date, // วันที่
    posNo: formDataSalary.posNo, //เลขที่ตำแหน่ง
    position: formDataSalary.position, //ตำแหน่ง
    positionLine: formDataSalary.positionLine, //สายงาน
    positionPathSide: formDataSalary.positionPathSide, // ด้าน/สาขา
    positionExecutive: formDataSalary.positionExecutive, //ตำแหน่งทางการบริหาร
    positionType: formDataSalary.positionType, // ประเภทตำแหน่ง
    positionLevel: formDataSalary.positionLevel, // ระดับตำแหน่ง
    amount:
      typeof formDataSalary.salary === "number"
        ? formDataSalary.salary
        : Number(formDataSalary?.salary?.replace(/,/g, "")), //เงินเดือนฐาน
    positionSalaryAmount:
      typeof formDataSalary.salaryPos === "number"
        ? formDataSalary.salaryPos
        : Number(formDataSalary?.salaryPos?.replace(/,/g, "")), // เงินประจำตำแหน่ง
    mouthSalaryAmount:
      typeof formDataSalary.salaryCompensation === "number"
        ? formDataSalary.salaryCompensation
        : Number(formDataSalary?.salaryCompensation?.replace(/,/g, "")), //เงินค่าตอบแทนรายเดือน
    refCommandNo: formDataSalary.refCommandNo, // เลขที่คำสั่ง
    templateDoc: formDataSalary.doc, // เอกสารอ้างอิง
  };

  try {
    const url = isStatusEdit.value
      ? config.API.profileListSalaryNew(salaryId.value)
      : config.API.profileSalaryNew;
    const method = isStatusEdit.value ? "patch" : "post";
    await http[method](url, formData);
    fetchListSalary();
    onClickCloseDialog();
    success($q, "บันทึกข้อมูลสำเร็จ");
  } catch (e) {
    messageError($q, e);
  } finally {
    hideLoader();
  }
}

function onSwapUp(id: string) {
  showLoader();
  http
    .get(config.API.profileSalarySwapNew("up", id))
    .then(() => {
      fetchListSalary();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}
function onSwapDown(id: string) {
  showLoader();
  http
    .get(config.API.profileSalarySwapNew("down", id))
    .then(() => {
      fetchListSalary();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

const modalHistory = ref<boolean>(false);
function onClikcHistory(id: string) {
  salaryId.value = id;
  modalHistory.value = true;
}

onMounted(() => {
  fetchListSalary();
});
</script>
<template>
  <q-toolbar style="padding: 0px" class="text-primary q-mb-xs">
    <q-btn flat round dense icon="add" @click="onClickOpenDialog()">
      <q-tooltip>เพิ่มข้อมูล</q-tooltip>
    </q-btn>
    <q-space />
    <q-input
      dense
      outlined
      v-model="formFilter.keyword"
      label="ค้นหา"
      class="q-mr-sm"
    >
      <template v-slot:append>
        <q-icon v-if="formFilter.keyword == ''" name="search" />
        <q-icon
          v-else
          name="clear"
          class="cursor-pointer"
          @click="formFilter.keyword = ''"
        />
      </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"
    />
  </q-toolbar>
  <d-table
    ref="table"
    row-key="id"
    flat
    bordered
    dense
    :filter="formFilter.keyword"
    :columns="columns"
    :rows="rows"
    :paging="true"
    v-model:pagination="pagination"
    :rows-per-page-options="[20, 50, 100]"
    :visible-columns="visibleColumns"
  >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th auto-width />
        <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-th auto-width />
      </q-tr>
    </template>
    <template v-slot:body="props">
      <q-tr :props="props" class="cursor-pointer">
        <q-td auto-width>
          <q-btn
            dense
            size="12px"
            flat
            round
            :color="props.rowIndex + 1 == 1 ? 'grey' : 'green'"
            :disable="props.rowIndex + 1 == 1"
            icon="mdi-arrow-up-bold"
            @click="onSwapUp(props.row.id)"
          >
            <!-- <q-tooltip>เลื่อนลำดับขึ้น</q-tooltip> -->
          </q-btn>
        </q-td>
        <q-td auto-width>
          <q-btn
            dense
            size="12px"
            flat
            round
            :color="rows.length == props.rowIndex + 1 ? 'grey' : 'red'"
            :disable="rows.length == props.rowIndex + 1"
            icon="mdi-arrow-down-bold"
            @click="onSwapDown(props.row.id)"
          >
            <!-- <q-tooltip>เลื่อนลำดับลง</q-tooltip> -->
          </q-btn>
        </q-td>
        <q-td v-for="col in props.cols" :key="col.id">
          <div class="table_ellipsis">
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
        <q-td auto-width>
          <q-btn
            color="primary"
            flat
            dense
            round
            class="q-mr-xs"
            size="14px"
            icon="mdi-pencil-outline"
            clickable
            @click="onClickOpenDialog(true, props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
          <q-btn
            color="info"
            flat
            dense
            round
            size="14px"
            icon="mdi-history"
            @click="onClikcHistory(props.row.id)"
          >
            <q-tooltip>ประวัติแก้ไขตำแหน่ง/เงินเดือน</q-tooltip>
          </q-btn>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:pagination="scope">
      <q-pagination
        v-model="formFilter.page"
        active-color="primary"
        color="dark"
        :max="Number(maxPage)"
        :max-pages="5"
        size="sm"
        boundary-links
        direction-links
      ></q-pagination>
    </template>
  </d-table>

  <q-dialog v-model="modalDialogSalary" persistent full-width>
    <q-card>
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          :tittle="
            isStatusEdit ? 'แก้ไขตำแหน่งเงินเดือน' : 'เพิ่มตำแหน่งเงินเดือน'
          "
          :close="onClickCloseDialog"
        />
        <q-separator />
        <q-card-section class="q-pa-md bg-grey-1">
          <div class="row col-12 q-col-gutter-sm">
            <q-card flat bordered class="row fit q-pa-sm q-col-gutter-sm">
              <div class="col-xs-6 col-sm-6 col-md-6">
                <datepicker
                  v-model="formDataSalary.date"
                  :locale="'th'"
                  autoApply
                  :enableTimePicker="false"
                  week-start="0"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      outlined
                      dense
                      borderless
                      :model-value="date2Thai(formDataSalary.date)"
                      :rules="[
                            (val: string) =>
                              !!val ||
                              `${'กรุณาเลือก วัน/เดือน/ปี'}`,
                          ]"
                      :label="`${'วัน/เดือน/ปี'}`"
                      hide-bottom-space
                    >
                      <template v-slot:prepend>
                        <q-icon name="event" class="cursor-pointer"> </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>

              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-input
                  ref="posNoRef"
                  outlined
                  dense
                  lazy-rules
                  borderless
                  v-model="formDataSalary.posNo"
                  hide-bottom-space
                  :label="`${'เลขที่ตำแหน่ง'}`"
                  :rules="[(val: string) => !!val || `${'กรุณากรอกเลขที่ตำแหน่ง'}`]"
                >
                </q-input>
              </div>

              <div class="col-xs-12 col-sm-12 col-md-12">
                <q-select
                  ref="templatePosRef"
                  outlined
                  dense
                  lazy-rules
                  borderless
                  v-model="formDataSalary.templatePos"
                  :label="`${'ต้นแบบ (template) ตำแหน่ง'}`"
                  option-label="name"
                  :options="posNoOptions"
                  option-value="name"
                  hide-bottom-space
                  emit-value
                  use-input
                  input-debounce="0"
                  @update:modelValue="updatePos"
                  @filter="(inputValue: any,
                        doneFn: Function) => filterSelector(inputValue, doneFn, 'pos'
                        )"
                />
              </div>

              <div class="col-xs-12 col-sm-12 col-md-12">
                <q-input
                  ref="positionRef"
                  outlined
                  dense
                  lazy-rules
                  borderless
                  v-model="formDataSalary.position"
                  :label="`${'ตำแหน่ง'}`"
                  type="textarea"
                  hide-bottom-space
                  :rules="[(val: string) => !!val || `${'กรุณากรอกตำแหน่ง'}`]"
                />
              </div>

              <div class="col-xs-6 col-sm-6 col-md-4">
                <q-input
                  outlined
                  dense
                  lazy-rules
                  v-model="formDataSalary.positionLine"
                  hide-bottom-space
                  :label="`${'สายงาน'}`"
                />
                <!-- <q-select
                  outlined
                  dense
                  lazy-rules
                  borderless
                  v-model="formDataSalary.positionLine"
                  :label="`${'สายงาน'}`"
                  emit-value
                  map-options
                  option-label="name"
                  :options="positionLineOptions"
                  option-value="id"
                  hide-bottom-space
                  use-input
                  input-debounce="0"
                  @filter="(inputValue: any,
                        doneFn: Function) => filterSelector(inputValue, doneFn, 'positionLine'
                        )"
                /> -->
              </div>

              <div class="col-xs-6 col-sm-6 col-md-4">
                <q-input
                  outlined
                  dense
                  lazy-rules
                  v-model="formDataSalary.positionPathSide"
                  hide-bottom-space
                  :label="`${'ด้าน/สาขา'}`"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-4">
                <q-input
                  outlined
                  dense
                  lazy-rules
                  borderless
                  v-model="formDataSalary.positionExecutive"
                  hide-bottom-space
                  :label="`${'ตำแหน่งทางการบริหาร'}`"
                >
                </q-input>
              </div>

              <div class="col-xs-6 col-sm-6 col-md-4">
                <q-select
                  ref="positionType Ref"
                  outlined
                  dense
                  lazy-rules
                  borderless
                  v-model="formDataSalary.positionType"
                  :label="`${'ตำแหน่งประเภท'}`"
                  emit-value
                  map-options
                  option-label="name"
                  :options="posTypeOptions"
                  option-value="name"
                  hide-bottom-space
                  use-input
                  input-debounce="0"
                  @update:model-value="updateSelectType"
                  :rules="[(val: string) => !!val || `${'กรุณาเลือกตำแหน่งประเภท'}`]"
                  @filter="(inputValue: any,
                        doneFn: Function) => filterSelector(inputValue, doneFn, 'posType'
                        )"
                />
              </div>

              <div class="col-xs-6 col-sm-6 col-md-4">
                <q-select
                  ref="positionLevel Ref"
                  outlined
                  dense
                  lazy-rules
                  borderless
                  v-model="formDataSalary.positionLevel"
                  :rules="[(val: string) => !!val || `${'กรุณาเลือกระดับตำแหน่ง'}`]"
                  :label="`${'ระดับตำแหน่ง'}`"
                  emit-value
                  map-options
                  option-label="name"
                  :options="posLevelOption"
                  option-value="name"
                  hide-bottom-space
                  use-input
                  input-debounce="0"
                  @filter="(inputValue: any,
                          doneFn: Function) => filterSelector(inputValue, doneFn, 'posLevel'
                          )"
                />
              </div>
              <div class="col-md-4"></div>
              <div class="col-xs-6 col-sm-6 col-md-4">
                <q-input
                  ref="salaryRef"
                  dense
                  outlined
                  v-model="formDataSalary.salary"
                  label="เงินเดือน"
                  mask="###,###,###,###"
                  reverse-fill-mask
                  :rules="[(val) => !!val || `${'กรุณากรอกเงินเดือน'}`]"
                  lazy-rules
                  hide-bottom-space
                />
              </div>

              <div class="col-xs-6 col-sm-6 col-md-4">
                <q-input
                  ref="amountRef"
                  dense
                  outlined
                  v-model="formDataSalary.salaryPos"
                  :rules="[(val) => !!val || `${'กรุณากรอกเงินประจำตำแหน่ง'}`]"
                  label="เงินประจำตำแหน่ง"
                  mask="###,###,###,###"
                  reverse-fill-mask
                  lazy-rules
                  hide-bottom-space
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-4">
                <q-input
                  ref="amountRef"
                  dense
                  outlined
                  v-model="formDataSalary.salaryCompensation"
                  label="เงินค่าตอบแทนรายเดือน"
                  mask="###,###,###,###"
                  reverse-fill-mask
                  lazy-rules
                  hide-bottom-space
                />
              </div>

              <div class="col-xs-6 col-sm-6 col-md-12">
                <q-input
                  outlined
                  dense
                  lazy-rules
                  borderless
                  v-model="formDataSalary.refCommandNo"
                  hide-bottom-space
                  :label="`${'เลขที่คำสั่ง'}`"
                  mask="#####################"
                >
                  <!-- :rules="[(val: string) => !!val || `${'กรุณากรอกเลขที่คำสั่ง'}`]" -->
                </q-input>
              </div>

              <div class="col-xs-12 col-sm-12 col-md-12">
                <q-select
                  ref="templateDocRef"
                  outlined
                  dense
                  lazy-rules
                  borderless
                  v-model="formDataSalary.templateDoc"
                  :label="`${'ต้นแบบ (template) เอกสารอ้างอิง'}`"
                  option-label="name"
                  :options="docOption"
                  option-value="name"
                  emit-value
                  hide-bottom-space
                  use-input
                  input-debounce="0"
                  @update:modelValue="updateDoc"
                  @filter="(inputValue: any,
                          doneFn: Function) => filterSelector(inputValue, doneFn, 'doc'
                          )"
                />
              </div>

              <div class="col-xs-12 col-sm-12 col-md-12">
                <q-input
                  ref="docRef"
                  outlined
                  dense
                  lazy-rules
                  borderless
                  v-model="formDataSalary.doc"
                  :label="`${'เอกสารอ้างอิง'}`"
                  type="textarea"
                  hide-bottom-space
                  :rules="[(val: number) => !!val  || `${'กรุณากรอกเอกสารอ้างอิง'}`]"
                />
              </div>
            </q-card>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-section align="right">
          <q-btn label="บันทึก" type="submit" color="secondary">
            <q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-section>
      </q-form>
    </q-card>
  </q-dialog>

  <DialogHistory v-model:modal="modalHistory" v-model:salaryId="salaryId" />
</template>

<style scoped></style>
