<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 { useOrganizational } from "@/modules/02_organization/store/organizational";

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

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

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

/**
 * props
 */
const type = defineModel<number>("type", { required: true });
const modal = defineModel<boolean>("sortAgency", { required: true });
const modalSort = defineModel<Array<any>>("data", { required: true });
const props = defineProps({
  fetchDataTree: {
    type: Function,
    require: true,
    default: () => "",
  },
});

/** ข้อมูล Table*/
const rows = ref<DataSortAgency[]>([]);
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, () => {
    showLoader();
    const data = rows.value;
    const dataId = data.map((item: DataSortAgency) => item.orgTreeId);
    http
      .post(config.API.organizationShortName, {
        id: data[0].orgLevel === 0 ? data[0].orgRevisionId : data[0].orgRootId,
        type: data[0].orgLevel,
        sortId: dataId,
      })
      .then(async () => {
        await props.fetchDataTree(store.draftId);
        await success($q, "บันทึกข้อมูลสำเร็จ");
        modal.value = false;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * callback function ทำงานเมื่อ modal = true ทำการเรียกข้อมูลตำแหน่ง
 */
watch(
  () => modal.value,
  () => {
    if (modal.value == true) {
      rows.value = [];
      const dataStandant = modalSort.value;
      const mappedData = dataStandant.map((item: any) => ({
        name: `${item.orgTreeName} (${item.orgTreeShortName})`,
        orgRootId: item.orgRootId,
        orgTreeId: item.orgTreeId,
        orgLevel: item.orgLevel,
        orgTreeName: item.orgTreeName,
        orgTreeShortName: item.orgTreeShortName,
        orgRevisionId: item.orgRevisionId,
      }));
      rows.value = mappedData;
    }
  }
);
</script>
<template>
  <template>
    <q-dialog v-model="modal" persistent>
      <q-card style="min-width: 50vw">
        <DialogHeader
          :tittle="`จัดลำดับ${type == 0 ? 'หน่วยงาน' : 'ส่วนราชการ'}`"
          :close="() => (modal = false)"
        />
        <q-separator />

        <q-card-section style="max-height: 70vh" class="scroll">
          <q-table
            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
          />
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn type="submit" :label="`บันทึก`" color="public" @click="save">
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-card>
    </q-dialog>
  </template>
</template>
