<script setup lang="ts">
import { ref, reactive } from "vue";
import { useQuasar } from "quasar";

import type { QTableProps } from "quasar";
import type { DataOption2 } 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 store = useSalaryDataStore();
const { date2Thai, dialogConfirm, showLoader, hideLoader, messageError } =
  useCounterMixin();
const columns = ref<QTableProps["columns"]>([
  {
    name: "date",
    align: "left",
    label: "วัน เดือน ปี",
    sortable: true,
    field: "date",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "amount",
    align: "left",
    label: "เงินเดือน",
    sortable: true,
    field: "amount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionSalaryAmount",
    align: "left",
    label: "เงินประจำตำแหน่ง",
    sortable: true,
    field: "positionSalaryAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "mouthSalaryAmount",
    align: "left",
    label: "เงินค่าตอบแทนรายเดือน",
    sortable: true,
    field: "mouthSalaryAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },

  {
    name: "posNo",
    align: "left",
    label: "ตำแหน่งเลขที่",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },

  {
    name: "postionTypeName",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: true,
    field: "postionTypeName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionLevelName",
    align: "left",
    label: "ระดับ",
    sortable: true,
    field: "positionLevelName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },

  {
    name: "salaryRef",
    align: "left",
    label: "เอกสารอ้างอิง",
    sortable: true,
    field: "salaryRef",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "refCommandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "refCommandNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumns = ref<string[]>([
  "date",
  "amount",
  "positionSalaryAmount",
  "mouthSalaryAmount",
  "posNo",
  "postionTypeName",
  "positionLevelName",
  "salaryRef",
  "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>([
  {
    id: "1",
  },
  {
    id: "2",
  },
  {
    id: "3",
  },
]);

const formDataSalary = reactive<FormSalaryNew>({
  date: null,
  posNo: "",
  templatePos: "",
  position: "",
  positionLineName: "",
  typePosition: "",
  levelPosition: "",
  positionPathSideName: "",
  positionExecutiveName: "",
  salaryCompensation: null,
  salary: null,
  salaryPos: null,
  refCommandNo: "",
  templateDoc: "",
  doc: "",
});

/** ตัวแปร ref สำหรับแสดง validate */
const dateRef = ref<Object | null>(null);
const posNoRef = ref<Object | null>(null);
const positionRef = ref<Object | null>(null);
const typePositionRef = ref<Object | null>(null);
const levelPositionRef = ref<Object | null>(null);
const salaryRef = ref<Object | null>(null);
const docRef = ref<Object | null>(null);

const ObjectRef: ObjectSalaryRef = {
  date: dateRef,
  posNo: posNoRef,
  position: positionRef,
  typePosition: typePositionRef,
  levelPosition: levelPositionRef,
  salary: salaryRef,
  doc: docRef,
};

const modalDialogSalary = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);

const posNoOptions = ref<DataOption2[]>(store.optionTemplatePos);
const positionLineOptions = ref<DataOption2[]>(store.optionTemplatePos);
const posTypeOptions = ref<DataOption2[]>(store.optionTemplatePos);
const posLevelOption = ref<DataOption2[]>(store.optionTemplatePos);
const docOption = ref<DataOption2[]>(store.optionTemplateDoc);

function onClickOpenDialog(type: string) {
  if (type === "ADD") {
    isStatusEdit.value = false;
  } else {
    isStatusEdit.value = true;
  }
  modalDialogSalary.value = true;
}
function onClickCcloseDialog() {
  modalDialogSalary.value = false;
}

const 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 "positionLineName":
      update(() => {
        positionLineOptions.value = store.optionTemplatePos.filter(
          (v: DataOption2) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "posType":
      update(() => {
        posTypeOptions.value = store.optionTemplatePos.filter(
          (v: DataOption2) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "posLevel":
      update(() => {
        posLevelOption.value = store.optionTemplatePos.filter(
          (v: DataOption2) => 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() {
  const hasError = [];
  for (const key in ObjectRef) {
    if (Object.prototype.hasOwnProperty.call(ObjectRef, key)) {
      const property = ObjectRef[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    dialogConfirm($q, () => {
      onClickCcloseDialog();
    });
  }
}

const modalHistory = ref<boolean>(false);
function ocClikcHistory() {
  modalHistory.value = true;
}
</script>
<template>
  <div class="row items-center q-gutter-sm">
    <div class="toptitle text-dark row items-center q-py-xs">
      ตำแหน่งเงินเดือน
    </div>
  </div>

  <q-toolbar style="padding: 0px" class="text-primary">
    <q-btn flat round dense icon="add" @click="onClickOpenDialog('ADD')">
      <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 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"
      options-cover
      style="min-width: 150px"
    />
  </q-toolbar>
  <d-table
    ref="table"
    row-key="id"
    flat
    bordered
    dense
    :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"
          >
            <!-- <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"
          >
            <!-- <q-tooltip>เลื่อนลำดับลง</q-tooltip> -->
          </q-btn>
        </q-td>
        <q-td
          v-for="col in props.cols"
          :key="col.id"
          @click="onClickOpenDialog('EDIT')"
        >
          <template>
            {{ col.value ? col.value : "-" }}
          </template>
        </q-td>
        <q-td auto-width>
          <q-btn
            color="info"
            flat
            dense
            round
            size="14px"
            icon="mdi-history"
            @click="ocClikcHistory"
          >
            <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>
      <form @submit.prevent.stop="onSubmit">
        <DialogHeader
          :tittle="
            isStatusEdit ? 'แก้ไขตำแหน่งเงินเดือน' : 'เพิ่มตำแหน่งเงินเดือน'
          "
          :close="onClickCcloseDialog"
        />
        <q-separator />
        <q-card-section class="q-pa-sm bg-grey-1">
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-xs-12 col-sm-12">
              <q-card flat bordered class="fit q-pa-sm">
                <div class="row col-12 q-col-gutter-xs">
                  <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
                          ref="dateRef"
                          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-mt-lg">
                    <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-6">
                    <q-select
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formDataSalary.positionLineName"
                      :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, 'positionLineName'
                        )"
                    />
                  </div>

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

                  <div class="col-xs-6 col-sm-6 col-md-3">
                    <q-select
                      ref="levelPositionRef"
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formDataSalary.levelPosition"
                      :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-xs-6 col-sm-6 col-md-3">
                    <q-input
                      outlined
                      dense
                      lazy-rules
                      v-model="formDataSalary.positionPathSideName"
                      hide-bottom-space
                      :label="`${'ด้าน/สาขา'}`"
                    />
                  </div>
                  <div class="col-xs-6 col-sm-6 col-md-6">
                    <q-input
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formDataSalary.positionExecutiveName"
                      hide-bottom-space
                      :label="`${'ตำแหน่งทางการบริหาร'}`"
                    >
                    </q-input>
                  </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"
                      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>
                </div>
              </q-card>
            </div>
          </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>
      </form>
    </q-card>
  </q-dialog>

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

<style scoped></style>
