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

import config from "@/app.config";
import http from "@/plugins/http";

import { useCounterMixin } from "@/stores/mixin";

import type { DataStrategic } from "@/modules/01_masterdata/interface/response/Strategic";

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

const $q = useQuasar();
const mixin = useCounterMixin();
const { showLoader, hideLoader, success, messageError } = mixin;
const props = defineProps({
  dataSort: Array as PropType<DataStrategic[]>,
  idSort: String,
  getData: Function,
});

const modal = defineModel<boolean>("modal", { required: true });
const rows = ref<any[]>([]);

const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    align: "left",
    label: "ยุทธศาสตร์",
    field: "name",
  },
]);

/**
 * ฟังก์ชันการจัดลำดับการแสดงผล
 * @param from ตำแหน่งปัจจบัน
 * @param to ตำแหน่งที่ต้องการไป
 */
function onDrop(from: number, to: number) {
  rows.value.splice(to, 0, rows.value.splice(from, 1)[0]);
}

function closeDialog() {
  modal.value = false;
}

async function onSubmit() {
  const minLevel = Math.min(...rows.value.map((item) => item.level));
  const strategyId = rows.value.map((item: any) => item.id);
  const body = {
    strategy: minLevel,
    strategyId: strategyId,
    id: minLevel == 1 ? null : props.idSort,
  };
  showLoader();
  await http
    .post(config.API.devStrategySort, body)
    .then(async(res) => {
      await props.getData?.();
      closeDialog();
      success($q, "บันทึกสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

watch(modal, () => {
  if (modal.value && props.dataSort) {
    const listData = props.dataSort;
    rows.value = [];
    rows.value.push(...listData);
  }
});
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 80%">
      <DialogHeader tittle="จัดลำดับการแสดงผล" :close="closeDialog" />
      <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="name"
          hide-bottom
          hide-pagination
          hide-header
        />
      </q-card-section>
      <q-separator />

      <q-card-actions align="right">
        <q-btn label="บันทึก" color="secondary" type="submit" @click="onSubmit"
          ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
        >
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
