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

/** importType*/
import type { QTableProps } from "quasar";
import type { NewPagination } from "@/modules/13_salary/interface/index/Main";
import type { DataFilter } from "@/modules/13_salary/interface/index/SalaryList";

/** importComponents*/
import DialogAddPerson from "@/modules/13_salary/components/SalaryEmployeeLists//DialogAddPerson.vue";
import DialogFormEdit from "@/modules/13_salary/components/SalaryEmployeeLists/DialogFormEdit.vue";
import DialogMoveGroup from "@/modules/13_salary/components/SalaryEmployeeLists/DialogMoveGroup.vue";
import DialogMoveLevel from "@/modules/13_salary/components/SalaryEmployeeLists/DialogMoveLevel.vue";
import DialogProperties from "@/modules/13_salary/components/SalaryEmployeeLists/DialogProperties.vue";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";
import { useSalaryEmployeeListSDataStore } from "@/modules/13_salary/store/SalaryEmployeeListsStore";
import http from "@/plugins/http";
import config from "@/app.config";

/** use*/
const $q = useQuasar();
const store = useSalaryEmployeeListSDataStore();
const { dialogRemove, messageError, showLoader, hideLoader, success } =
  useCounterMixin();

/** Props*/
const formFilter = defineModel<DataFilter>("formFilter", { required: true });
const maxPage = defineModel<Number>("maxPage", { required: true });
const props = defineProps({
  rows: { type: Array },
  fetchDataTable: {
    type: Function,
  },
  maxPage: {
    type: Number,
  },
  total: {
    type: Number,
  },
});

/** ข้อมูล Table*/
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posType",
    align: "left",
    label: "กลุ่มงาน",
    sortable: true,
    field: "posType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    field: "position",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posLevel",
    align: "left",
    label: "ระดับชั้นงาน",
    field: "posLevel",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "group",
    align: "left",
    label: "ผังค่าจ้าง(เดิม)",
    sortable: false,
    field: "group",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return val ? "กลุ่ม" + val : "-";
    },
  },
  {
    name: "salaryLevel",
    align: "left",
    label: "ขั้น(เดิม)",
    sortable: false,
    field: "salaryLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "amount",
    align: "left",
    label: "เงินเดือน",
    field: "amount",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organization",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "organization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "result",
    align: "center",
    label: "ผลการประเมินฯ",
    sortable: false,
    field: "result",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "duration",
    align: "center",
    label: "ระยะเวลาการปฏิบัติราชการในรอบครึ่งปี",
    sortable: false,
    field: "duration",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "isPunish",
    align: "center",
    label: "ไม่ถูกลงโทษทางวินัย",
    sortable: false,
    field: "isPunish",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "isSuspension",
    align: "center",
    label: "ไม่ถูกพักราชการ",
    sortable: false,
    field: "isSuspension",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "isAbsent",
    align: "center",
    label: "ไม่ขาดราชการ",
    sortable: false,
    field: "isAbsent",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "isLeave",
    align: "center",
    label: "วันลาไม่เกิน",
    sortable: false,
    field: "isLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "fullName",
  "posType",
  "position",
  "posLevel",
  "amount",
  "organization",
  "result",
  "duration",
  "isPunish",
  "isSuspension",
  "isAbsent",
  "isLeave",
  "group",
  "salaryLevel",
]);

/** modalDialog*/
const modalDialogAddPerson = ref<boolean>(false);
const modalDialogForm = ref<boolean>(false);
const modalDialogMoveGroup = ref<boolean>(false);
const modalDialogMoveLeve = ref<boolean>(false);
const modalDialogProperties = ref<boolean>(false);

/** ตัวแปร*/
const profileId = ref<string>("");
const amount = ref<number>(0);
const isPunish = ref<boolean>(false);
const isSuspension = ref<boolean>(false);
const isAbsent = ref<boolean>(false);
const isLeave = ref<boolean>(false);
/**
 * function ยืนยันการลบรายชื่อ
 *  @param id profileId
 */
function onClickDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.salaryListPeriodProfileByIdEmp(id))
      .then(() => {
        success($q, "ลบข้อมูลสำเร็จ");
        props.fetchDataTable?.();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** function openPopup เพิ่มคนเลื่อนเงินเดือน*/
function onClickAddPerson() {
  modalDialogAddPerson.value = !modalDialogAddPerson.value;
}

/**
 * function openPopup แก้ไขเงินเดือน
 * @param id profileId
 * @param amountSalary จำนวนเงินเดือน
 *
 */
function onClickEdit(id: string, amountSalary: number) {
  profileId.value = id;
  amount.value = amountSalary;
  modalDialogForm.value = !modalDialogForm.value;
}

/**
 * function openPopup ย้ายกลุ่ม
 * @param id profileId
 *
 */
function onClickMovieGroup(id: string) {
  profileId.value = id;
  modalDialogMoveGroup.value = !modalDialogMoveGroup.value;
}

const typeLevel = ref<string>("");
const isReserve = ref<boolean>(false);
/**
 * function openPopup ย้ายกขั้น
 * @param id profileId
 *
 */
function onClickMoveLevel(id: string, typeVal: string, isReserveVal: boolean) {
  profileId.value = id;
  modalDialogMoveLeve.value = !modalDialogMoveLeve.value;
  typeLevel.value = typeVal;
  isReserve.value = isReserveVal;
}

/** function updatePageTable*/
function updatePagePagination() {
  props.fetchDataTable?.();
}

/** function updatePageSizeTable*/
function updatePageSizePagination(newPagination: NewPagination) {
  formFilter.value.page = 1;
  formFilter.value.pageSize = newPagination.rowsPerPage;
}

/** function ค้นหาข้อมูล Table*/
function searchData() {
  formFilter.value.page = 1;
  props.fetchDataTable?.();
}

function onProperties(data: any) {
  console.log(data);
  modalDialogProperties.value = true;
  profileId.value = data.id;
  isPunish.value = data.isPunish;
  isSuspension.value = data.isSuspension;
  isAbsent.value = data.isAbsent;
  isLeave.value = data.isLeave;
}
/** callblack function เรียกข้อมูลรายชื่อใหม่ เมื่อมีการเปลี่ยน PageSize*/
watch(
  () => formFilter.value.pageSize,
  () => {
    updatePagePagination();
  }
);
</script>

<template>
  <q-toolbar class="text-primary" style="padding: 0px">
    <q-btn
      v-if="!store.isClosedRound"
      flat
      round
      dense
      icon="add"
      @click="onClickAddPerson"
    >
      <q-tooltip>เพิ่ม </q-tooltip>
    </q-btn>
    <q-space />
    <q-input
      borderless
      dense
      debounce="300"
      outlined
      v-model="formFilter.keyword"
      placeholder="ค้นหา"
      @keydown.enter.prevent="searchData"
    >
      <template v-slot:append>
        <q-icon name="search" />
      </template>
    </q-input>
    <q-select
      for="#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"
      class="col-xs-12 col-sm-3 col-md-2 q-ml-sm"
    />
  </q-toolbar>
  <d-table
    ref="table"
    :columns="columns"
    :rows="props.rows"
    row-key="id"
    flat
    bordered
    :paging="true"
    dense
    :rows-per-page-options="[10, 25, 50, 100]"
    :visible-columns="visibleColumns"
    @update:pagination="updatePageSizePagination"
  >
    <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-th auto-width />
      </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.name" :props="props">
          <div v-if="col.name === 'no'">
            {{
              (formFilter.page - 1) * formFilter.pageSize + props.rowIndex + 1
            }}
          </div>
          <div v-else-if="col.name === 'fullName'">
            {{
              `${props.row.prefix}${props.row.firstName}  ${props.row.lastName}`
            }}
          </div>
          <div v-else-if="col.name == 'organization'" class="table_ellipsis">
            <div
              v-if="
                props.row.child4 === null &&
                props.row.child3 === null &&
                props.row.child2 === null &&
                props.row.child1 === null &&
                props.row.root === null
              "
            >
              -
            </div>
            {{
              `${props.row.child4 ? props.row.child4 + "/" : ""}${
                props.row.child3 ? props.row.child3 + "/" : ""
              }${props.row.child2 ? props.row.child2 + "-" : ""}${
                props.row.child1 ? props.row.child1 + "/" : ""
              }${props.row.root ? props.row.root : ""}`
            }}
          </div>
          <!-- <div v-else-if="col.name === 'isResult'">
            <q-checkbox
              disable
              keep-color
              color="primary"
              v-model="props.row.isResult"
            />
          </div>
          <div v-else-if="col.name === 'isDuration'">
            <q-checkbox
              disable
              keep-color
              color="primary"
              v-model="props.row.isDuration"
            />
          </div>
          <div v-else-if="col.name === 'isPunish'">
            <q-checkbox
              disable
              keep-color
              color="primary"
              v-model="props.row.isPunish"
            />
          </div>
          <div v-else-if="col.name === 'isRetired'">
            <q-checkbox
              disable
              keep-color
              color="primary"
              v-model="props.row.isRetired"
            />
          </div>
          <div v-else-if="col.name === 'isRetired2'">
            <q-checkbox
              disable
              keep-color
              color="primary"
              v-model="props.row.isRetired2"
              false
            />
          </div> -->
          <div v-else-if="col.name == 'isPunish'">
            <q-icon
              v-if="props.row.isPunish !== null"
              :name="props.row.isPunish ? 'done' : 'close'"
              :color="props.row.isPunish ? 'primary' : 'red'"
              size="24px"
            />
            <div v-else-if="props.row.isPunish == null">
              {{ props.row.isPunish == null ? "-" : "" }}
            </div>
          </div>
          <div v-else-if="col.name == 'isSuspension'">
            <q-icon
              v-if="props.row.isSuspension !== null"
              :name="props.row.isSuspension ? 'done' : 'close'"
              :color="props.row.isSuspension ? 'primary' : 'red'"
              size="24px"
            />
            <div v-else-if="props.row.isSuspension == null">
              {{ props.row.isSuspension == null ? "-" : "" }}
            </div>
          </div>
          <div v-else-if="col.name == 'isAbsent'">
            <q-icon
              v-if="props.row.isAbsent !== null"
              :name="props.row.isAbsent ? 'done' : 'close'"
              :color="props.row.isAbsent ? 'primary' : 'red'"
              size="24px"
            />
            <div v-else-if="props.row.isAbsent == null">
              {{ props.row.isAbsent == null ? "-" : "" }}
            </div>
          </div>
          <div v-else-if="col.name == 'amount'">
            {{ Number(props.row.amount).toLocaleString() }}
          </div>
          <div v-else-if="col.name == 'isLeave'">
            <q-icon
              v-if="props.row.isLeave !== null"
              :name="props.row.isLeave ? 'done' : 'close'"
              :color="props.row.isLeave ? 'primary' : 'red'"
              size="24px"
            />
            <div v-else-if="props.row.isLeave == null">
              {{ props.row.isLeave == null ? "-" : "" }}
            </div>
          </div>
          <div v-else>
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
        <q-td>
          <q-btn
            v-if="!store.isClosedRound"
            flat
            dense
            icon="mdi-dots-vertical"
            class="q-pa-none q-ml-xs"
            color="grey-13"
            size="12px"
          >
            <q-menu>
              <q-list dense style="min-width: 150px">
                <q-item
                  v-for="(item, index) in store.itemMenu.filter((x:any)=>x.type !== 'moveGroup')"
                  :key="index"
                  clickable
                  v-close-popup
                  @click="
                    item.type === 'edit'
                      ? onClickEdit(props.row.id, props.row.amount)
                      : item.type === 'moveGroup'
                      ? onClickMovieGroup(props.row.id)
                      : item.type === 'moveLevel'
                      ? onClickMoveLevel(
                          props.row.id,
                          props.row.type,
                          props.row.isReserve
                        )
                      : item.type === 'delete'
                      ? onClickDelete(props.row.id)
                      : item.type === 'properties'
                      ? onProperties(props.row)
                      : null
                  "
                >
                  <q-item-section>
                    <div class="row items-center">
                      <q-icon
                        :color="item.color"
                        size="17px"
                        :name="item.icon"
                      />
                      <div class="q-pl-md">{{ item.label }}</div>
                    </div>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-menu>
          </q-btn>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:pagination="scope">
      ทั้งหมด {{ props.total }} รายการ
      <q-pagination
        v-model="formFilter.page"
        active-color="primary"
        color="dark"
        :max="Number(maxPage)"
        :max-pages="5"
        size="sm"
        boundary-links
        direction-links
        @update:model-value="updatePagePagination()"
      ></q-pagination>
    </template>
  </d-table>

  <DialogAddPerson
    v-model:modal="modalDialogAddPerson"
    :fetchData="props.fetchDataTable"
  />

  <DialogFormEdit
    v-model:modal="modalDialogForm"
    v-model:profileId="profileId"
    v-model:amount="amount"
    :fetchData="props.fetchDataTable"
  />
  <DialogMoveGroup
    v-model:modal="modalDialogMoveGroup"
    v-model:profileId="profileId"
    :group="store.tabGroup === 'group1' ? 'กลุ่ม1' : 'กลุ่ม2'"
    :fetchData="props.fetchDataTable"
  />
  <DialogMoveLevel
    :typeLevel="typeLevel"
    :isReserve="isReserve"
    v-model:modal="modalDialogMoveLeve"
    v-model:profileId="profileId"
    :fetchData="props.fetchDataTable"
  />
  <DialogProperties
    v-model:modal="modalDialogProperties"
    v-model:id="profileId"
    :is-punish="isPunish"
    :is-suspension="isSuspension"
    :is-absent="isAbsent"
    :is-leave="isLeave"
    :fetch-data="props.fetchDataTable"
  />
</template>

<style scoped></style>
