<script setup lang="ts">
import { ref, reactive, watch } 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 { useOrganizational } from "@/modules/02_organizationalNew/store/organizational";

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

const type = defineModel<number>("type", { required: true });

const props = defineProps({
  fetchDataTree: {
    type: Function,
    require: true,
    default: () => "",
  },
});

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

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, () => {
    showLoader();
    const data = rows.value;
    const dataId = data.map((item: any) => 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((res) => {
        modal.value = false;
        props.fetchDataTree(store.draftId);
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}
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">
        <!-- <form @submit.prevent="validateForm"> -->
        <DialogHeader
          :tittle="`จัดลำดับ${type == 0 ? 'หน่วยงาน' : 'ส่วนราชการ'}`"
          :close="() => (modal = false)"
        />
        <q-separator />

        <q-card-section>
          <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" class="bg-white text-teal">
          <q-btn type="submit" :label="`บันทึก`" color="public" @click="save" />
        </q-card-actions>
        <!-- </form> -->
      </q-card>
    </q-dialog>
  </template>
</template>
