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

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

/** 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/05_salaryListsEmployee//DialogAddPerson.vue";
import DialogFormEdit from "@/modules/13_salary/components/05_salaryListsEmployee/DialogFormEditSalary.vue";
import DialogMoveGroup from "@/modules/13_salary/components/05_salaryListsEmployee/DialogMoveGroup.vue";
import DialogMoveLevel from "@/modules/13_salary/components/05_salaryListsEmployee/DialogMoveLevel.vue";
import DialogProperties from "@/modules/13_salary/components/05_salaryListsEmployee/DialogProperties.vue";
import DialogInfo from "@/modules/13_salary/components/DialogInfoMain.vue";

/** 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: "isSuspension",
    align: "center",
    label: "ไม่ถูกพักราชการ",
    sortable: false,
    field: "isSuspension",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posSalary",
    align: "center",
    label: "ประวัติตำแหน่ง/ค่าจ้าง",
    sortable: false,
    field: "posSalary",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "discipline",
    align: "center",
    label: "วินัย",
    sortable: false,
    field: "discipline",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "leave",
    align: "center",
    label: "การลา",
    sortable: false,
    field: "leave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "fullName",
  "posType",
  "position",
  "posLevel",
  "amount",
  "organization",
  "result",
  "isSuspension",
  "group",
  "salaryLevel",
  "posSalary",
  "discipline",
  "leave",
]);

/** modalDialog*/
const modalDialogAddPerson = ref<boolean>(false); //popup คนเลื่อนเงินเดือน
const modalDialogForm = ref<boolean>(false); //popup แก้ไขเงินเดือน
const modalDialogMoveGroup = ref<boolean>(false); //popup ย้ายกลุ่ม
const modalDialogMoveLeve = ref<boolean>(false); //popup เลื่อนขั้น
const modalDialogProperties = ref<boolean>(false); //popup คุณสมบัติ
const modalDialogInfo = ref<boolean>(false); //popup ข้อมูลส่วนตัว

/** ตัวแปร*/
const profileId = ref<string>(""); //id คน
const amount = ref<number>(0); //เงินเดือน
const typeLevel = ref<string>(""); //เลื่อนขั้น
const isReserve = ref<boolean>(false); //สำรอง
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(async () => {
        await props.fetchDataTable?.();
        await success($q, "ลบข้อมูลสำเร็จ");
      })
      .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;
}

/**
 * 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 เปิด popup คุณสมบัติ
 * @param data ข่อมูลคุณสมบัติ
 */
function onProperties(data: any) {
  modalDialogProperties.value = true;
  profileId.value = data.id;
  isPunish.value = data.isPunish;
  isSuspension.value = data.isSuspension;
  isAbsent.value = data.isAbsent;
  isLeave.value = data.isLeave;
}

const infoType = ref<string>(""); //ประเภทข้อมูล
/**
 * function ดูข้อมูลส่วนตัว
 * @param type ประเภทข้อมูล
 * @param id id ที่ต้องการดู
 */
function onClickViewInfo(type: string, id: string) {
  infoType.value = type;
  profileId.value = id;
  modalDialogInfo.value = true;
}

/**
 * callblack function เรียกข้อมูลรายชื่อใหม่ เมื่อมีการเปลี่ยน PageSize
 */
watch(
  () => formFilter.value.pageSize,
  () => {
    updatePagePagination();
  }
);
</script>

<template>
  <q-toolbar class="text-primary" style="padding: 0px">
    <q-btn
      v-if="!store.isClosedRound && checkPermission($route)?.attrIsCreate"
      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="!checkPermission($route)?.attrIsGet 
      ? columns?.filter((col:any) =>  col.name !== 'posSalary' && col.name !== 'discipline' && col.name !== 'leave' ) 
      : columns"
      option-value="name"
      
      style="min-width: 140px"
      class="col-xs-12 col-sm-3 col-md-2 q-ml-sm"
    />
  </q-toolbar>
  <d-table
    ref="table"
    :columns="!checkPermission($route)?.attrIsGet 
    ? columns?.filter((col:any) =>  col.name !== 'posSalary' && col.name !== 'discipline' && col.name !== 'leave' ) 
    : 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 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-tr>
    </template>
    <template v-slot:body="props">
      <q-tr :props="props">
        <q-td>
          <q-btn
            v-if="
              !store.isClosedRound &&
              (checkPermission($route)?.attrIsUpdate ||
                checkPermission($route)?.attrIsDelete)
            "
            flat
            dense
            color="secondary"
            icon="mdi-dots-horizontal-circle-outline"
            round
          >
            <q-menu>
              <q-list dense style="min-width: 150px">
                <q-item
                  v-for="(item, index) in  checkPermission($route)?.attrIsUpdate &&!checkPermission($route)?.attrIsDelete
                  ? store.itemMenu.filter((x:any)=>x.type !== 'moveGroup' && x.type !== 'delete')
                  : !checkPermission($route)?.attrIsUpdate && checkPermission($route)?.attrIsDelete
                  ? store.itemMenu.filter((x:any)=> x.type === 'delete') 
                  : 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-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 == '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 == 'amount'">
            {{ Number(props.row.amount).toLocaleString() }}
          </div>

          <div
            v-else-if="
              col.name == 'posSalary' ||
              col.name == 'discipline' ||
              col.name == 'leave'
            "
          >
            <q-btn
              v-if="checkPermission($route)?.attrIsGet"
              flat
              dense
              icon="info"
              class="q-pa-none q-ml-xs"
              color="info"
              size="12px"
              @click.pervent="onClickViewInfo(col.name, props.row.profileId)"
            >
            </q-btn>
          </div>

          <div v-else>
            {{ col.value ? col.value : "-" }}
          </div>
        </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"
    :fetch-data="props.fetchDataTable"
  />

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

  <DialogInfo
    v-model:modal="modalDialogInfo"
    v-model:profile-id="profileId"
    :type="infoType"
    :employee-class="'-employee'"
  />
</template>

<style scoped></style>
