<script setup lang="ts">
import { ref } 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 { QTableColumn } 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";
import DialogProperties from "@/modules/13_salary/components/05_salaryListsEmployee/DialogProperties.vue";
import DialogInfo from "@/modules/13_salary/components/DialogInfoMain.vue";
import DialogMoveLevelMulti from "@/modules/13_salary/components/05_salaryListsEmployee/DialogMoveLevelMulti.vue";

/** use*/
const $q = useQuasar();
const store = useSalaryEmployeeListSDataStore();
const {
  dialogRemove,
  messageError,
  showLoader,
  hideLoader,
  success,
  findOrgName,
  findOrgNameHtml,
} = 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,
  },
  isRetire: {
    type: Boolean,
    required: true,
  },
  onRequest: {
    type: Function,
    required: true,
  },
  checkAndUpdatePage: {
    type: Function,
    required: true,
  },
});

/** ข้อมูล Table*/
const columns = ref<QTableColumn[]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "firstName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "firstName",
    format(val, row) {
      return `${row.prefix}${row.firstName} ${row.lastName}`;
    },
    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",
    format(val, row) {
      return row.orgShortName && row.posMasterNo
        ? `${row.orgShortName} ${row.posMasterNo}`
        : "-";
    },
  },

  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    field: "position",
    sortable: true,
    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: "ระดับชั้นงาน",
    field: "posLevel",
    sortable: true,
    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: "ค่าจ้าง",
    field: "amount",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organization",
    align: "left",
    label: "สังกัด",
    sortable: false,
    field: "organization",
    format(val, row) {
      return findOrgName(row);
    },
    headerStyle: "font-size: 14px;min-width:280px",
    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",
  "firstName",
  "orgShortName",
  "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 modalDialogMoveLevel = ref<boolean>(false); //popup เลื่อนขั้น
const modalDialogProperties = ref<boolean>(false); //popup คุณสมบัติ
const modalDialogInfo = ref<boolean>(false); //popup ข้อมูลส่วนตัว
const modalDialogMoveLevelMulti = 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 updateCurrentPageAndfetchData();
        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;
  modalDialogMoveLevel.value = !modalDialogMoveLevel.value;
  typeLevel.value = typeVal;
  isReserve.value = isReserveVal;
}

/** function ค้นหาข้อมูล Table*/
function searchData() {
  pagination.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;
}

/** function openPopup ย้ายกขั้น*/
function onClickMoveLevelMulti() {
  modalDialogMoveLevelMulti.value = !modalDialogMoveLevel.value;
}

/** ฟังก์ชันอัปเดตหน้าปัจจุบันและดึงข้อมูล */
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 &&
        checkPermission($route)?.attrIsCreate &&
        !isClose
      "
      flat
      round
      dense
      icon="add"
      @click="onClickAddPerson"
    >
      <q-tooltip>เพิ่ม </q-tooltip>
    </q-btn>

    <q-btn
      v-if="!store.isClosedRound && !isClose"
      flat
      round
      dense
      color="green-6"
      icon="mdi-swap-vertical-bold"
      @click="onClickMoveLevelMulti"
    >
      <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="!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="q-ml-sm"
    />
  </q-toolbar>
  <p-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="[1, 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 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 !== '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'">
            {{ props.rowIndex + 1 }}
          </div>
          <div v-else-if="col.name == 'organization'" class="text-html">
            {{ findOrgNameHtml(props.row) }}
          </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 == 'leave'">
            <q-btn
              v-if="checkPermission($route)?.attrIsGet"
              flat
              dense
              icon="info"
              class="q-pa-none q-ml-xs"
              color="info"
              size="12px"
              @click.prevent="onClickViewInfo(col.name, props.row.profileId)"
            >
            </q-btn>
          </div>

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

          <div v-else>
            {{ 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"
    :type-level="typeLevel"
    :is-reserve="isReserve"
    :fetch-data="updateCurrentPageAndfetchData"
    :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'"
  />

  <!-- เลื่อนขั้นเลือกหลายคน -->
  <DialogMoveLevelMulti
    v-model:modal="modalDialogMoveLevelMulti"
    :fetch-data="props.fetchDataTable"
    :columns="
      columns.filter(
        (e) =>
          e.name !== 'leave' &&
          e.name !== 'discipline' &&
          e.name !== 'posSalary'
      )
    "
    :visible-columns="visibleColumns"
    :total="props?.total"
    :is-retire="isRetire"
  />
</template>

<style scoped></style>
