<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { checkPermission } from "@/utils/permissions";

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

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

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

const nodes = ref<DataStrategic[]>([]);
const filter = ref<string>("");
const expanded = ref<Array<string>>([]);
const nodeId = ref<string>("");
const modalDialog = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);
const strategicName = ref<string>("");
const levelnode = ref<number>(0);
const titleDialog = ref<string>("");

/** ดึงข้อมูล ในรูปแบบ tree */
function fetchDataTree() {
  showLoader();
  http
    .get(config.API.devStrategy + `/edit/strategic`)
    .then((res) => {
      const data: DataStrategic[] = res.data.result;
      nodes.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * เพิ่ม ลบ แก้ไข
 * @param type ประเภท node
 * @param data ข้อมูล
 */
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;
  }
}

/**
 * เปิด dialog
 * @param status true/false
 * @param data ข้อมูลยุทธศาสตร์
 */
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;
}

/** ปิด dialog */
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 method = isStatusEdit.value ? "patch" : "post";
      await http[method](config.API.devStrategy, formData);
      fetchDataTree();
      success($q, "บันทึกข้อมูลสำเร็จ");
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
      closeDialog();
    }
  });
}

/** ลบข้อมูลตาม id */
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
          v-if="checkPermission($route)?.attrIsCreate"
          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="name"
        :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
              v-if="
                checkPermission($route)?.attrIsCreate ||
                checkPermission($route)?.attrIsGet ||
                checkPermission($route)?.attrIsUpdate ||
                checkPermission($route)?.attrIsDelete
              "
              flat
              dense
              color="grey-13"
              icon="mdi-dots-vertical"
              round
            >
              <q-menu>
                <q-list dense style="min-width: 100px">
                  <q-item
                    v-if="
                      prop.node.level !== 4 &&
                      checkPermission($route)?.attrIsCreate
                    "
                    clickable
                    v-close-popup
                    @click.stop="onClickAction('ADD', prop.node)"
                  >
                    <q-item-section avatar style="min-width: 20px">
                      <q-icon size="17px" :color="'primary'" :name="'add'" />
                    </q-item-section>

                    <q-item-section v-if="prop.node.level === 1">
                      {{ `เพิ่มยุทธศาสตร์ที่ 1` }}
                    </q-item-section>
                    <q-item-section v-if="prop.node.level === 2">
                      {{ `เพิ่มยุทธศาสตร์ย่อย` }}
                    </q-item-section>
                    <q-item-section v-if="prop.node.level === 3">
                      {{ `เพิ่มกลยุทธ์ที่/เป้าประสงค์` }}
                    </q-item-section>
                  </q-item>
                  <q-item
                    v-if="
                      checkPermission($route)?.attrIsUpdate &&
                      checkPermission($route)?.attrIsGet
                    "
                    clickable
                    v-close-popup
                    @click.stop="onClickAction('EDIT', prop.node)"
                  >
                    <q-item-section avatar style="min-width: 20px">
                      <q-icon size="17px" :color="'edit'" :name="'edit'" />
                    </q-item-section>
                    <q-item-section v-if="prop.node.level === 1">
                      {{ `แก้ไขยุทธศาสตร์/แผน` }}
                    </q-item-section>
                    <q-item-section v-if="prop.node.level === 2">
                      {{ `แก้ไขยุทธศาสตร์ที่ 1` }}
                    </q-item-section>
                    <q-item-section v-if="prop.node.level === 3">
                      {{ `แก้ไขยุทธศาสตร์ย่อย` }}
                    </q-item-section>
                    <q-item-section v-if="prop.node.level === 4">
                      {{ `แก้ไขกลยุทธ์ที่/เป้าประสงค์` }}
                    </q-item-section>
                  </q-item>
                  <q-item
                    v-if="checkPermission($route)?.attrIsDelete"
                    clickable
                    v-close-popup
                    @click.stop="onClickAction('DEL', prop.node)"
                  >
                    <q-item-section avatar style="min-width: 20px">
                      <q-icon size="17px" :color="'red'" :name="'delete'" />
                    </q-item-section>
                    <q-item-section> ลบข้อมูล </q-item-section>
                  </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>
          <div class="row">
            <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">
          <q-btn label="บันทึก" id="onSubmit" type="submit" color="public">
            <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>
