<script setup lang="ts">
import { ref, watch } from "vue";
import type { QTableProps } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useRouter, useRoute } from "vue-router";
import { useInsigniaDataStore } from "@/modules/01_metadataNew/stores/InsigniaStore";
import dialogHeader from "@/components/DialogHeader.vue";
import { useQuasar } from "quasar";
import DialogHeader from "@/components/DialogHeader.vue";

import http from "@/plugins/http";
import config from "@/app.config";
const store = useInsigniaDataStore();
const mixin = useCounterMixin();
const { dialogRemove, dialogConfirm, showLoader, hideLoader, messageError } =
  mixin;
const $q = useQuasar();
const route = useRoute();
const modal = defineModel("modal", { type: Boolean });
const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    required: true,
    label: "ชื่อเครื่องราชฯ",
    align: "left",
    field: "name",
    sortable: true,
  },
  {
    name: "shortName",
    align: "center",
    label: "ชื่อย่อ",
    field: "shortName",
  },
  {
    name: "insigniaType",
    align: "left",
    label: "ลำดับชั้นเครื่องราชฯ",
    field: "insigniaType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sortable: true,
  },
]);
const id = ref<string>(route.params.id.toString());

const props = defineProps({
  fetchData: {
    type: Function,
    default: () => console.log("not function"),
  },
});

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

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

async function save() {
  const dataPost = await rows.value.map((obj: any) => {
    return obj.id;
  });
  console.log("post data===> ", dataPost);
  modal.value = false;

  showLoader();
  await http
    .put(config.API.insigniaSort(id.value), { id: dataPost })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
      store.row = rows.value;
      props.fetchData(id.value);
    });
}

async function onSubmit() {
  dialogConfirm($q, async () => {
    save();
  });
}

watch(modal, () => {
  if (modal.value === true) {
    // rows.value = store.row;
    rows.value = [...store.row]; // ดึงมาใช้ sort แล้วใน store ไม่เปลี่ยน
  }
});
</script>

<template>
  <q-dialog v-model="modal" class="dialog" persistent>
    <q-card style="min-width: 50vw" class="bg-grey-11">
      <form @submit.prevent="onSubmit">
        <DialogHeader
          tittle="จัดลำดับการแสดงผล"
          :close="() => (modal = false)"
        />
        <q-separator />
        <q-card-section class="q-pa-md bg-grey-1">
          <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="name"
            hide-bottom
            hide-pagination
            hide-header
          />
          <!-- <q-table
            v-draggable-table="{
              options: {
                mode: 'row',
                onlyBody: true,
                dragHandler: 'tr',
              },
              onDrop,
            }"
            ref="table"
            :columns="columns"
            :rows="rows"
            row-key="name"
            flat
            bordered
            hide-bottom
          /> -->
        </q-card-section>

        <q-separator />
        <q-card-actions align="right">
          <q-btn
            type="submit"
            dense
            unelevated
            label="บันทึก"
            color="public"
            class="q-px-md"
          >
            <!-- icon="mdi-content-save-outline" -->
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </form>
    </q-card>
  </q-dialog>
</template>
