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

import type { ItemsMenu } from "@/modules/15_development/interface/index/Main";
import type { DataStrategic } from "@/modules/15_development/interface/response/Strategic";

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

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

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

const ListMenu = ref<ItemsMenu[]>([
  {
    label: "เพิ่ม",
    icon: "add",
    value: "ADD",
    color: "primary",
  },
  {
    label: "แก้ไข",
    icon: "edit",
    value: "EDIT",
    color: "edit",
  },
  {
    label: "ลบ",
    icon: "delete",
    value: "DEL",
    color: "red",
  },
]);

const nodes = ref<any[]>([]);
const filter = ref<string>("");
const expanded = ref<Array<string>>([]);
const nodeId = ref<string>("");

function fetchDataTree() {
  showLoader();
  http
    .get(config.API.devStrategy)
    .then((res) => {
      const data: DataStrategic[] = res.data.result;
      nodes.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onClickAction(type: string, data: DataStrategic | null = null) {
  switch (type) {
    case "ADD":
      onClickOpenDialog(false, data);
      break;
    case "EDIT":
      onClickOpenDialog(true, data);
      break;
    case "DEL":
      data && onDelete(data);
      break;
    default:
      break;
  }
}

const modalDialog = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);
const strategicName = ref<string>("");
const levelnode = ref<number>(0);
const titleDialog = ref<string>("");
function onClickOpenDialog(
  status: boolean = false,
  data: DataStrategic | null = null
) {
  isStatusEdit.value = status;
  if (status) {
    if (data) {
      nodeId.value = data.id;
      strategicName.value = data.name;
      levelnode.value = data.level;
      titleDialog.value =
        data.level === 1
          ? "ยุทธศาสตร์/แผน"
          : data.level === 2
          ? "ยุทธศาสตร์ที่"
          : data.level === 3
          ? "ยุทธศาสตร์ย่อย"
          : data.level === 4
          ? "กลยุทธ์ที่/เป้าประสงค์ที่"
          : "";
    }
  } else {
    if (data) {
      titleDialog.value =
        data.level === 1
          ? "ยุทธศาสตร์ที่"
          : data.level === 2
          ? "ยุทธศาสตร์ย่อย"
          : data.level === 3
          ? "กลยุทธ์ที่/เป้าประสงค์ที่"
          : "";
      levelnode.value = data.level;
      nodeId.value = data.id;
    } else {
      levelnode.value = 0;
      titleDialog.value = "ยุทธศาสตร์/แผน";
    }
  }
  modalDialog.value = true;
}

function closeDialog() {
  modalDialog.value = false;
  strategicName.value = "";
}

function onSubmit() {
  dialogConfirm($q, async () => {
    const formData = {
      idnode: levelnode.value === 0 ? "0" : nodeId.value,
      levelnode: levelnode.value,
      name: strategicName.value,
    };
    try {
      // const url = isStatusEdit.value
      //   ? config.API.devStrategy;
      //   : config.API.devStrategy;
      const method = isStatusEdit.value ? "patch" : "post";
      await http[method](config.API.devStrategy, formData);
      fetchDataTree();
      success($q, "บันทึกข้อมูลสำเร็จ");
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
      closeDialog();
    }
  });
}

function onDelete(data: DataStrategic) {
  dialogRemove($q, () => {
    showLoader();
    const formData = {
      idnode: data.id,
      levelnode: data.level,
    };
    http
      .delete(config.API.devStrategy, { data: formData })
      .then(() => {
        fetchDataTree();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

onMounted(() => {
  fetchDataTree();
});
</script>
<template>
  <div class="toptitle text-dark col-12 row items-center">ยุทธศาสตร์</div>
  <q-card flat bordered class="q-pa-md">
    <div class="row q-col-gutter-sm q-pl-sm">
      <q-toolbar class="text-primary">
        <q-btn
          dense
          flat
          round
          color="primary"
          icon="add"
          @click.stop="onClickAction('ADD')"
        >
          <q-tooltip>เพิ่มยุทธศาสตร์</q-tooltip>
        </q-btn>

        <q-input dense outlined v-model="filter" label="ค้นหา">
          <template v-slot:append>
            <q-icon
              v-if="filter !== ''"
              name="clear"
              class="cursor-pointer"
              @click="filter = ''"
            />
            <q-icon v-else name="search" color="grey-5" />
          </template>
        </q-input>
      </q-toolbar>
    </div>
    <div class="bg-white tree-container q-pa-xs">
      <q-tree
        class="q-pa-sm q-gutter-sm"
        dense
        :nodes="nodes"
        node-key="id"
        label-key="id"
        :filter="filter"
        no-results-label="ไม่พบข้อมูลที่ค้นหา"
        no-nodes-label="ไม่มีข้อมูล"
        v-model:expanded="expanded"
      >
        <template v-slot:default-header="prop">
          <q-item
            clickable
            @click.stop
            :active="nodeId == prop.node.name"
            active-class="my-list-link text-primary text-weight-medium"
            class="row col-12 items-center text-dark q-py-xs q-pl-sm rounded-borders my-list"
          >
            <div>
              <div class="text-weight-medium">
                {{ prop.node.name }}
              </div>
            </div>
            <q-btn
              flat
              dense
              icon="mdi-dots-vertical"
              class="q-ml-xs"
              color="grey-13"
              size="12px"
              round
            >
              <q-menu>
                <q-list
                  dense
                  v-for="(item, index) in prop.node.level !== 4
                    ? ListMenu
                    : ListMenu.slice(1, 4)"
                  :key="index"
                  style="min-width: 100px"
                >
                  <q-item
                    clickable
                    v-close-popup
                    @click.stop="onClickAction(item.value, prop.node)"
                  >
                    <q-item-section avatar style="min-width: 20px">
                      <q-icon
                        size="17px"
                        :color="item.color"
                        :name="item.icon"
                      />
                    </q-item-section>

                    <div v-if="item.value === 'ADD'">
                      <q-item-section v-if="prop.node.level === 1">
                        {{ `${item.label}ยุทธศาสตร์ที่ 1` }}
                      </q-item-section>
                      <q-item-section v-if="prop.node.level === 2">
                        {{ `${item.label}ยุทธศาสตร์ย่อย` }}
                      </q-item-section>
                      <q-item-section v-if="prop.node.level === 3">
                        {{ `${item.label}กลยุทธ์ที่/เป้าประสงค์` }}
                      </q-item-section>
                    </div>

                    <div v-else-if="item.value === 'EDIT'">
                      <q-item-section v-if="prop.node.level === 1">
                        {{ `${item.label}ยุทธศาสตร์/แผน` }}
                      </q-item-section>
                      <q-item-section v-if="prop.node.level === 2">
                        {{ `${item.label}ยุทธศาสตร์ที่` }}
                      </q-item-section>
                      <q-item-section v-if="prop.node.level === 3">
                        {{ `${item.label}ยุทธศาสตร์ย่อย` }}
                      </q-item-section>
                      <q-item-section v-if="prop.node.level === 4">
                        {{ `${item.label}กลยุทธ์ที่/เป้าประสงค์` }}
                      </q-item-section>
                    </div>

                    <div v-else>
                      <q-item-section>{{ item.label }}</q-item-section>
                    </div>
                  </q-item>
                </q-list>
              </q-menu>
            </q-btn>
          </q-item>
        </template>
      </q-tree>
    </div>
  </q-card>

  <q-dialog v-model="modalDialog" persistent>
    <q-card style="width: 700px; max-width: 80vw">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          :tittle="`${
            isStatusEdit ? `แก้ไข${titleDialog}` : `เพิ่ม${titleDialog}`
          }`"
          :close="closeDialog"
        />
        <q-separator />

        <q-card-section class="q-pt-none">
          <div class="row q-pa-md">
            <div class="col">
              <q-input
                dense
                outlined
                v-model="strategicName"
                :label="`ชื่อ${titleDialog}`"
                hide-bottom-space
                lazy-rules
                :rules="[
                  (val:string) =>
                    !!val || `${'กรุณากรอกชื่อ'}${titleDialog}`,
      
                ]"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />

        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn
            dense
            unelevated
            label="บันทึก"
            id="onSubmit"
            type="submit"
            color="public"
            class="q-px-md"
          >
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style lang="scss" scoped>
.tree-container {
  overflow: auto;
  height: 75vh;
}
</style>
