<template>
  <div>
    <q-scroll-area
      :style="{ height: content_height + 'px' }"
      style="width: 20vw"
    >
      <q-tree ref="tree" :nodes="tree_nodes" node-key="uuid" labelKey="name">
        <template v-slot:default-header="prop">
          <q-item
            class="full-width"
            clickable
            :disable="!$store.state.power_state"
            :draggable="prop.node.uuid != '' && $store.state.power_state"
            @dragstart="(evt) => onDragStart(evt, prop.node)"
            @dragover="(evt) => onDragOver(evt, prop.node)"
            @drop="(evt) => onDrop(evt, prop.node)"
            @dblclick="
              (evt) => !prop.node.is_group && runPlan(prop.node.item_data)
            "
          >
            <q-item-section avatar>
              <q-icon
                style="pointer-events: none"
                :name="
                  prop.node.is_group
                    ? 'img:source_icon/group.png'
                    : 'img:new_icon/plan_icon.png'
                "
                color="orange"
                size="28px"
                class="q-mr-sm"
              />
            </q-item-section>
            <q-item-section>
              <div class="text-weight-bold text-primary">
                {{ prop.node.name }}
              </div>
            </q-item-section>
            <q-popup-proxy :context-menu="$store.state.power_state">
              <q-list>
                <q-item
                  v-if="
                    prop.node.name == $t('plan') ||
                    (prop.node.is_group && prop.node.item_data)
                  "
                  clickable
                  v-close-popup
                  v-ripple
                  @click="
                    $refs.plan_dialog.showDialog({
                      type: 1,
                      data: { uuid: prop.node.uuid },
                    })
                  "
                >
                  <q-item-section avatar><q-icon name="add" /></q-item-section>
                  <q-item-section>{{ $t("add plan item") }}</q-item-section>
                </q-item>
                <q-item
                  clickable
                  v-close-popup
                  v-if="
                    prop.node.name == $t('plan') ||
                    (prop.node.is_group && prop.node.item_data)
                  "
                  v-ripple
                  @click="
                    () =>
                      $refs.group_dialog.showDialog({
                        type: 1,
                        data: prop.node,
                      })
                  "
                >
                  <q-item-section avatar
                    ><q-icon name="create_new_folder"
                  /></q-item-section>
                  <q-item-section>{{ $t("add group") }}</q-item-section>
                </q-item>
                <q-item
                  clickable
                  v-ripple
                  v-close-popup
                  v-if="
                    prop.node.item_data &&
                    power_on_plan != prop.node.item_data.uuid &&
                    !prop.node.is_group
                  "
                  @click="
                    (evt) => setPowerOnPlan(evt, prop.node.item_data.uuid)
                  "
                >
                  <q-item-section avatar
                    ><q-icon name="timer"
                  /></q-item-section>
                  <q-item-section>{{
                    $t("set power on start")
                  }}</q-item-section>
                </q-item>
                <q-item
                  clickable
                  v-ripple
                  v-close-popup
                  v-if="
                    prop.node.item_data &&
                    power_on_plan == prop.node.item_data.uuid &&
                    !prop.node.is_group
                  "
                  @click="
                    (evt) => unsetPowerOnPlan(evt, prop.node.item_data.uuid)
                  "
                >
                  <q-item-section avatar
                    ><q-icon name="timer_off"
                  /></q-item-section>
                  <q-item-section>{{
                    $t("unset power on start")
                  }}</q-item-section>
                </q-item>
                <q-item
                  clickable
                  v-ripple
                  v-close-popup
                  v-if="prop.node.item_data && prop.node.item_data.uuid"
                  @click="
                    () =>
                      (prop.node.is_group
                        ? $refs.group_dialog
                        : $refs.plan_dialog
                      ).showDialog({
                        type: 2,
                        data: prop.node,
                      })
                  "
                >
                  <q-item-section avatar><q-icon name="edit" /></q-item-section>
                  <q-item-section>{{ $t("edit") }}</q-item-section>
                </q-item>

                <q-item
                  clickable
                  v-ripple
                  v-close-popup
                  v-if="prop.node.item_data && prop.node.item_data.uuid"
                  @click="
                    (evt) => deleteItem(evt, prop.node.is_group, prop.node.uuid)
                  "
                >
                  <q-item-section avatar
                    ><q-icon color="red" name="delete"
                  /></q-item-section>
                  <q-item-section>{{ $t("delete") }} &nbsp;</q-item-section>
                </q-item>
              </q-list>
            </q-popup-proxy>
          </q-item>
        </template>
      </q-tree>
    </q-scroll-area>
  </div>
  <plan-group-dialog ref="group_dialog" />
  <plan-dialog ref="plan_dialog" />
</template>

<script lang="ts">
import { defineComponent, computed, onMounted, ref, nextTick } from "vue";
import { useStore } from "src/store";
import PlanGroupDialog from "src/components/PlanGroupDialog.vue";
import PlanDialog from "src/components/PlanDialog.vue";
import { Common } from "src/common/Common";
import GlobalData from "src/common/GlobalData";
import { useQuasar, extend } from "quasar";
import { useI18n } from "vue-i18n";
import EventBus, { EventNamesDefine } from "src/common/EventBus";
import { Protocol } from "src/entities/WSProtocol";
import { PlanEntity, PlanTreeItemEntity } from "src/entities/PlanEntity";
import { NotifyMessage } from "src/common/ClientConnection";

export default defineComponent({
  name: "ComponentPlanTree",

  components: { PlanGroupDialog, PlanDialog },

  setup() {
    const $store = useStore();
    const $q = useQuasar();
    const $t = useI18n();

    const tree_nodes = computed({
      get: () => $store.state.plan_tree,
      set: (val) => {},
    });

    const power_on_plan = computed({
      get: () => $store.state.power_on_plan,
      set: (val) => {},
    });

    const content_height = ref(0);

    const refresh_content_height = () => {
      content_height.value = window.innerHeight - 135;
    };
    refresh_content_height();

    EventBus.getInstance().on(EventNamesDefine.WindowResize, () => {
      refresh_content_height();
    });

    const tree: any | null = ref(null);

    onMounted(async () => {
      while (!tree.value?.nodes?.length) {
        await Common.waitFor(100);
      }
      tree.value?.setExpanded("", true);
    });

    return {
      tree,
      tree_nodes,
      content_height,
      power_on_plan,
      loga(a: any) {
        console.log(a);
      },
      deleteItem(evt: MouseEvent | null, is_group: boolean, uuid: string) {
        const show_tooltip = (success: boolean) => {
          $q.notify({
            color: success ? "positive" : "negative",
            icon: success ? "done" : "warning",
            message:
              $t.t("delete") + (success ? $t.t("success") : $t.t("fail")) + "!",
            position: "top",
            timeout: 1500,
          });
        };
        if (is_group) {
          $q.dialog({
            title: $t.t("Confirm"),
            message: $t.t(
              "delete group should be delete all child! do you want to delete this group?"
            ),
            ok: {
              label: $t.t("ok"),
              noCaps: true,
              flat: true,
            },
            cancel: {
              label: $t.t("cancel"),
              noCaps: true,
              flat: true,
            },
            persistent: true,
          }).onOk(async () => {
            let success = false;
            let response = await GlobalData.getInstance()
              .getCurrentClient()
              ?.deletePlanGroup(uuid);
            if (response) {
              success = response.success;
            }
            show_tooltip(success);
          });
        } else {
          $q.dialog({
            title: $t.t("Confirm"),
            message: $t.t("do you want to delete the item") + "?",
            ok: {
              label: $t.t("ok"),
              noCaps: true,
              flat: true,
            },
            cancel: {
              label: $t.t("cancel"),
              noCaps: true,
              flat: true,
            },
            persistent: true,
          }).onOk(async () => {
            let success = false;
            let response = await GlobalData.getInstance()
              .getCurrentClient()
              ?.deletePlan(uuid);
            if (response) {
              success = response.success;
            }
            show_tooltip(success);
          });
        }
      },
      runPlan(item: PlanEntity) {
        if (!$store.state.power_state) {
          return;
        }
        GlobalData.getInstance().getCurrentClient()?.runPlan(item.uuid);
        $q.notify({
          color: "positive",
          icon: "done",
          message: $t.t("run plan directives send") + $t.t("success") + "!",
          position: "top",
          timeout: 1500,
        });
      },
      unsetPowerOnPlan(evt: MouseEvent, uuid: string) {
        evt.stopPropagation();
        GlobalData.getInstance().getCurrentClient()?.setPowerOnPlan("");
      },
      setPowerOnPlan(evt: MouseEvent, uuid: string) {
        evt.stopPropagation();
        GlobalData.getInstance().getCurrentClient()?.setPowerOnPlan(uuid);
      },
      onDragStart(e: DragEvent, node: PlanTreeItemEntity) {
        e.dataTransfer?.setData("uuid", node.uuid);
        e.dataTransfer?.setData("type", "plan");
        e.dataTransfer?.setData("group", node.is_group ? "true" : "false");
        e.dataTransfer?.setData("node_object", JSON.stringify(node));
        if (e.dataTransfer) {
          e.dataTransfer.dropEffect = "move";
        }
      },
      onDragOver(e: DragEvent, node: PlanTreeItemEntity) {
        if (node && node.is_group) {
          e.preventDefault();
        }
      },
      onDrop(e: DragEvent, node: PlanTreeItemEntity) {
        if (node && node.is_group && node.item_data) {
          if (e.dataTransfer) {
            const type = e.dataTransfer.getData("type");
            if (type == "plan") {
              const uuid = e.dataTransfer.getData("uuid");
              const group = e.dataTransfer.getData("group");
              if (
                typeof uuid == "string" &&
                type &&
                type.length > 0 &&
                group &&
                group.length > 0
              ) {
                if (group == "true") {
                  const plan_group = GlobalData.getInstance().plan_groups.find(
                    (item) => item && (item as any).uuid == uuid
                  );
                  if (plan_group) {
                    if (plan_group.parent_uuid == node.item_data.uuid) {
                      return;
                    }
                    GlobalData.getInstance()
                      .getCurrentClient()
                      ?.editPlanGroup(
                        plan_group.uuid,
                        plan_group.name,
                        node.item_data.uuid
                      );
                  } else {
                    console.log("can't find plan group, uuid:" + uuid);
                  }
                } else if (group == "false") {
                  const plan = GlobalData.getInstance().plans.find(
                    (item) => item && (item as any).uuid == uuid
                  );
                  if (plan) {
                    if (plan.group_uuid == node.item_data.uuid) {
                      return;
                    }
                    const entity = extend(false, plan) as PlanEntity;
                    entity.group_uuid = node.item_data.uuid;
                    GlobalData.getInstance()
                      .getCurrentClient()
                      ?.editPlan(entity);
                  } else {
                    console.log("can't find plan, uuid:" + uuid);
                  }
                }
              }
            } else {
              console.log("type error");
            }
          }
        }
      },
    };
  },
});
</script>
