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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { usePositionEmp } from "@/modules/16_positionEmployee/store/organizational";

/**
 * importType
 */
import type { QTableProps } from "quasar";
import type { DataSortPos } from "@/modules/02_organization/interface/index/organizational";

/**
 * importComponents
 */
import DialogHeader from "@/components/DialogHeader.vue";

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

/**
 * props
 */
const modal = defineModel<boolean>("sortPosition", { required: true });
const props = defineProps({
  fetchDataTable: Function,
});

/** ข้อมูล Table*/
const rows = ref<DataSortPos[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    required: true,
    label: "ชื่อ",
    align: "left",
    field: "name",
    sortable: true,
  },
]);

/**
 * fiunction จัดลำดับ
 * @param from ตำแหน่งปัจุบัน
 * @param to ตำแหน่งที่จะย้ายไป
 */
function onDrop(from: number, to: number) {
  rows.value.splice(to, 0, rows.value.splice(from, 1)[0]);
}

/**
 * function บันทึกการจัดลำดับ
 */
function save() {
  dialogConfirm($q, () => {
    const data = rows.value;
    const dataId = data.map((item: DataSortPos) => item.id);
    showLoader();
    http
      .post(config.API.orgPosSortEmp, {
        id: store.treeId,
        type: store.level,
        sortId: dataId,
      })
      .then(async () => {
        await props.fetchDataTable?.(store.treeId, store.level, false);
        await success($q, "บันทึกข้อมูลสำเร็จ");
        modal.value = false;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * function เรียกรายการข้อมูลตำแหน่ง
 */
function getData() {
  showLoader();
  http
    .post(config.API.orgPosMasterListEmp, {
      id: store.treeId,
      type: store.level,
      isAll: false,
      page: 1,
      pageSize: 100,
      keyword: "",
      revisionId: store.activeId,
    })
    .then((res) => {
      const dataList = res.data.result.data;

      const dataMap = dataList.map((item: any) => ({
        id: item.id,
        name: `${item.orgShortname} ${
          item.posMasterNoPrefix ? item.posMasterNoPrefix : ""
        }${item.posMasterNo ? item.posMasterNo : ""}${
          item.posMasterNoSuffix ? item.posMasterNoSuffix : ""
        } ${item.fullNameCurrentHolder ? item.fullNameCurrentHolder : ""}`,
        posMasterNoPrefix: item.posMasterNoPrefix,
        posMasterNo: item.posMasterNo,
        posMasterNoSuffix: item.posMasterNoSuffix,
      }));
      rows.value = dataMap;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * callback function ทำงานเมื่อ modal = true ทำการเรียกข้อมูลตำแหน่ง
 */
watch(
  () => modal.value,
  () => {
    if (modal.value == true) {
      getData();
    }
  }
);
</script>
<template>
  <template>
    <q-dialog v-model="modal" persistent>
      <q-card style="min-width: 50vw">
        <DialogHeader
          :tittle="`จัดลำดับตำแหน่ง`"
          :close="() => (modal = false)"
        />
        <q-separator />

        <q-card-section style="max-height: 70vh" class="scroll">
          <q-table
            v-if="rows.length > 0"
            v-draggable-table="{
              options: {
                mode: 'row',
                onlyBody: true,
                dragHandler: 'th,td',
              },
              onDrop,
            }"
            flat
            bordered
            :rows="rows"
            :columns="columns"
            :rows-per-page-options="[100]"
            row-key="orgTreeId"
            hide-bottom
            hide-pagination
            hide-header
          />
          <div v-else class="bg-grey-1 text-center q-pa-md">ไม่มีข้อมูล</div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn
            :disable="rows.length === 0"
            type="submit"
            :label="`บันทึก`"
            color="public"
            @click="save"
          >
            <q-tooltip>บันทึก</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-card>
    </q-dialog>
  </template>
</template>
