<script setup lang="ts">
import { ref, computed } 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 config from "@/app.config";
import http from "@/plugins/http";

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

/** 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";

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

/** props*/
const isClose = defineModel<boolean>("isClose", { required: true });
const pagination = defineModel<NewPagination>("pagination", {
  required: true,
});
const keyword = defineModel<string>("keyword", { required: true });

const props = defineProps({
  rows: { type: Array, required: true },
  fetchDataTable: {
    type: Function,
    required: true,
  },
  total: {
    type: Number,
    required: true,
  },
  type: {
    type: String,
    required: true,
  },
  onRequest: {
    type: Function,
    required: true,
  },
  checkAndUpdatePage: {
    type: Function,
    required: true,
  },
});

/** ข้อมูล Table*/
const baseColumns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "firstName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    field: "firstName",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "orgShortName",
    align: "left",
    label: "ตำแหน่งเลขที่",
    sortable: true,
    field: "orgShortName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    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: "posLevel",
    align: "left",
    label: "ระดับชั้นงาน",
    sortable: true,
    field: "posLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "group",
    align: "left",
    label: "ผังค่าจ้าง(เดิม)",
    sortable: true,
    field: "group",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return val ? "กลุ่ม" + val : "-";
    },
  },
  {
    name: "salaryLevel",
    align: "left",
    label: "ขั้น(เดิม)",
    sortable: true,
    field: "salaryLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "amount",
    align: "left",
    label: "ค่าจ้างฐาน",
    sortable: true,
    field: "amount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "amountUse",
    align: "left",
    label: "จำนวนเงินที่ใช้เลื่อน",
    sortable: true,
    field: "amountUse",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "positionSalaryAmount",
    align: "left",
    label: "ค่าจ้างหลังเลื่อน",
    sortable: true,
    field: "positionSalaryAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "isRetired",
    align: "center",
    label: "เกษียณอายุ",
    sortable: false,
    field: "isRetired",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "remark",
    align: "left",
    label: "หมายเหตุ",
    sortable: true,
    field: "remark",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "firstName",
  "orgShortName",
  "position",
  "posType",
  "posLevel",
  "group",
  "salaryLevel",
  "amount",
  "amountUse",
  "positionSalaryAmount",
  "isRetired",
  "remark",
]);
const columns = computed(() => {
  if (props.type !== "NONE") {
    if (baseColumns.value) {
      return baseColumns.value.filter((column) => column.name !== "remark");
    }
  }
  return baseColumns.value;
});

/** modalDialog*/
const modalDialogAddPerson = ref<boolean>(false); //popup คนเลื่อนเงินเดือน
const modalDialogForm = ref<boolean>(false); //popup แก้ไขเงินเดือน
const modalDialogMoveGroup = ref<boolean>(false); //popup ย้ายกลุ่ม
const modalDialogMoveLevel = ref<boolean>(false); //popup เลื่อนขั้น

const profileId = ref<string>(""); //id คน
const amount = ref<number>(0); //เงินเดือน
const typeLevel = ref<string>(""); //เลื่อนขั้น
const isReserve = ref<boolean>(false); //สำรอง
const remark = ref<string>(""); //หมายเหตุ

/** 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,
  remarkVal: string = ""
) {
  profileId.value = id;
  modalDialogMoveLevel.value = !modalDialogMoveLevel.value;
  typeLevel.value = typeVal;
  isReserve.value = isReserveVal;
  remark.value = typeVal === "NONE" ? remarkVal : "";
}

/**
 * function ยืนยันการลบรายชื่อ
 *  @param id profileId
 */
function onClickDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.salaryListPeriodProfileByIdEmp(id))
      .then(async () => {
        await updateCurrentPageAndfetchData();
        await success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

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

/** ฟังก์ชันอัปเดตหน้าปัจจุบันและดึงข้อมูล */
async function updateCurrentPageAndfetchData() {
  await props.checkAndUpdatePage(props.rows.length);
  await props.fetchDataTable?.();
}
</script>
<template>
  <q-toolbar class="text-primary" style="padding: 0px">
    <!-- &&
    snapShot === 'SNAP1' -->
    <q-btn
      v-if="
        !store.isClosedRound &&
        !isClose &&
        checkPermission($route)?.attrIsCreate
      "
      flat
      round
      dense
      icon="add"
      @click="onClickAddPerson"
    >
      <q-tooltip>เพิ่ม</q-tooltip>
    </q-btn>
    <q-space />
    <q-input
      borderless
      dense
      outlined
      v-model="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="
        store.roundMainCode === 'OCT'
          ? columns
          : columns
          ? columns.filter((e) => e.name !== 'isRetired')
          : []
      "
      option-value="name"
      style="min-width: 140px"
      class="col-xs-12 col-sm-3 col-md-2 q-ml-sm"
    />
  </q-toolbar>

  <p-table
    ref="table"
    :columns="
      store.roundMainCode === 'OCT'
        ? columns
        : columns
        ? columns.filter((e) => e.name !== 'isRetired')
        : []
    "
    :rows="props.rows"
    row-key="id"
    flat
    bordered
    :paging="true"
    dense
    :rows-per-page-options="[10, 25, 50, 100]"
    :visible-columns="visibleColumns"
    v-model:pagination="pagination"
    @request="props.onRequest"
  >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th auto-width></q-th>
        <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>
          <!-- snapShot === 'SNAP1' && -->
          <q-btn
            v-if="
              !store.isClosedRound &&
              !isClose &&
              (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 !== 'properties' && 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' && x.type !== 'properties' )"
                  :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,
                          props.row.remark
                        )
                      : item.type === 'delete'
                      ? onClickDelete(props.row.id)
                      : 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"
          :class="
            store.tabType !== 'RETIRE'
              ? props.row.isNext == true
                ? 'text-red'
                : ''
              : ''
          "
        >
          <div v-if="col.name === 'no'">
            {{
              props.rowIndex +
              1 +
              (store.tabType == "FULL" && props.row.isReserve == true
                ? " (สำรอง)"
                : "")
            }}
          </div>
          <div v-else-if="col.name === 'orgShortName'">
            {{ `${props.row.orgShortName} ${props.row.posMasterNo}` }}
          </div>
          <div v-else-if="col.name === 'firstName'">
            {{
              `${props.row.prefix}${props.row.firstName}  ${props.row.lastName}`
            }}
          </div>
          <div v-else-if="col.name === 'amount'">
            {{
              props.row.amount !== null ? props.row.amount.toLocaleString() : ""
            }}
          </div>
          <div v-else-if="col.name === 'amountUse'">
            {{
              props.row.amountUse !== null
                ? props.row.amountUse > 0
                  ? props.row.amountUse.toLocaleString()
                  : 0
                : ""
            }}
            {{
              props.row.amountSpecial > 0
                ? `(${props.row.amountSpecial.toLocaleString()})`
                : ""
            }}
          </div>
          <div v-else-if="col.name === 'positionSalaryAmount'">
            {{
              props.row.positionSalaryAmount !== null
                ? props.row.positionSalaryAmount.toLocaleString()
                : ""
            }}
            {{
              props.row.amountSpecial > 0
                ? `(${props.row.amountSpecial.toLocaleString()})`
                : ""
            }}
          </div>

          <div v-else-if="col.name === 'isRetired'">
            <q-icon
              name="check"
              color="primary"
              size="24px"
              v-if="props.row.isRetired && store.roundMainCode === 'OCT'"
            />
          </div>

          <div v-else class="table_ellipsis2">
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
      </q-tr>
    </template>
  </p-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="updateCurrentPageAndfetchData"
    :group="store.tabGroup === 'group1' ? 'กลุ่ม1' : 'กลุ่ม2'"
  />
  <DialogMoveLevel
    v-model:modal="modalDialogMoveLevel"
    v-model:profile-id="profileId"
    :fetch-data="updateCurrentPageAndfetchData"
    :type-level="typeLevel"
    :is-reserve="isReserve"
    :type="store.tabType"
    :remark="remark"
  />
</template>

<style scoped></style>
