<script setup lang="ts">
import { ref, watch, defineProps } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";
import type { QTableProps } from "quasar";

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

import { useCounterMixin } from "@/stores/mixin";
import { usePositionEmp } from "@/modules/16_positionEmployee/store/organizational";

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

const modal = defineModel<boolean>("sortPosition", { required: true });
const rows = ref<any>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    required: true,
    label: "ชื่อ",
    align: "left",
    field: "name",
    sortable: true,
  },
]);

const props = defineProps({
  fetchDataTable: Function,
});

function onDrop(from: any, to: any) {
  onDropRow(from, to);
}

function onDropRow(from: any, to: any) {
  rows.value.splice(to, 0, rows.value.splice(from, 1)[0]);
}

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

function getData() {
  showLoader();
  http
    .post(config.API.orgPosMasterList, {
      id: store.treeId,
      type: store.level,
      isAll: false,
      page: 1,
      pageSize: 100,
      keyword: "",
      revisionId: store.draftId,
    })
    .then((res) => {
      const dataList = res.data.result.data;
      const dataMap = dataList.map((item: any) => ({
        id: item.id,
        name: `${item.orgShortname}${item.posMasterNoPrefix}${item.posMasterNo}${item.posMasterNoSuffix}`,
        posMasterNoPrefix: item.posMasterNoPrefix,
        posMasterNo: item.posMasterNo,
        posMasterNoSuffix: item.posMasterNoSuffix,
      }));
      rows.value = dataMap;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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>
          <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-card-actions>
      </q-card>
    </q-dialog>
  </template>
</template>
