<template>
  <q-dialog
    persistent
    v-model="show_dialog"
    @before-hide="resetData"
    @keydown="
      (evt) => {
        if (!loading && evt.keyCode == 27) {
          show_dialog = false;
        }
      }
    "
  >
    <q-card class="overflow-hidden" style="overflow-y: scroll; max-width: 45vw">
      <q-form @submit="onSubmit">
        <q-card-section class="q-ma-none q-pa-sm">
          <div class="row">
            <div class="col-auto text-h6">
              {{
                type == 1
                  ? $t("add group")
                  : type == 2
                  ? $t("edit group")
                  : $t("add group")
              }}
            </div>
            <q-space />
            <div>
              <q-btn
                :loading="loading"
                flat
                round
                icon="close"
                :disable="loading"
                color="red"
                v-close-popup
              >
                <q-tooltip>
                  {{ $t("close") }}
                </q-tooltip>
              </q-btn>
            </div>
          </div>
        </q-card-section>

        <q-separator />

        <q-card-section style="max-height: 50vh; width: 45vw" class="scroll">
          <q-list>
            <q-item v-if="/*type != 2*/ true">
              <q-item-label>{{ $t("parent group") }}:</q-item-label>
            </q-item>
            <q-item v-if="/*type != 2*/ true" class="q-pa-none q-ma-none">
              <q-item-section style="padding-right: 10px">
                <q-tree
                  ref="tree"
                  class="scroll"
                  :class="loading ? 'disable_tree' : ''"
                  v-model:selected="selected"
                  :nodes="tree_nodes"
                  default-expand-all
                  node-key="uuid"
                  labelKey="name"
                  filter="group filter"
                  :filter-method="treeNodesFilter"
                >
                  <template v-slot:default-header="prop">
                    <q-item
                      class="full-width"
                      :class="
                        prop.tree.selected == prop.key ? 'item-selected-bg' : ''
                      "
                    >
                      <q-item-section avatar>
                        <q-icon
                          :name="'img:source_icon/group.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-item>
                  </template>
                </q-tree>
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section>
                <q-input
                  autofocus
                  :loading="loading"
                  :disable="loading"
                  filled
                  v-model="name"
                  :label="$t('group name')"
                  :hint="$t('please input group name')"
                  lazy-rules
                  :rules="[
                    (val) =>
                      (val && val.length > 0) || $t('Please type something'),
                  ]"
                  @keydown="
                    (evt) => {
                      if (evt.keyCode == 13) {
                        $refs?.accept?.click();
                      }
                    }
                  "
                >
                  <template v-if="name" v-slot:append>
                    <q-icon
                      name="cancel"
                      @click.stop="name = null"
                      class="cursor-pointer"
                    />
                  </template>
                </q-input>
              </q-item-section>
            </q-item>
          </q-list>
        </q-card-section>

        <q-separator />

        <q-card-actions align="right">
          <q-btn
            :loading="loading"
            flat
            :label="$t('Cancel')"
            no-caps
            color="primary"
            v-close-popup
          />
          <q-btn
            ref="accept"
            flat
            :label="$t('Accept')"
            no-caps
            :loading="loading"
            type="submit"
            color="primary"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.disable_tree {
  background: #9e9e9e;
  cursor: wait;
  pointer-events: none;
}
</style>

<script lang="ts">
import { defineComponent, ref, watch, computed } from "vue";
import { useStore } from "src/store";
import GlobalData from "src/common/GlobalData";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";

export default defineComponent({
  name: "ComponentSignalSourceGroupDialog",

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

    let show_dialog = ref(false);
    let type = ref(1);
    let name = ref(null);
    let uuid = ref("");
    const selected: any = ref(null);
    let loading = ref(false);

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

    watch(
      () => selected.value,
      (newValue, oldValue) => {
        if (newValue == null) {
          selected.value = "";
        }
      }
    );

    const requestAddSignalSourceGroup = async () => {
      let response = await GlobalData.getInstance()
        .getCurrentClient()
        ?.addSignalSourceGroup(selected.value, name.value ?? "");
      if (response) {
        $q.notify({
          color: response.success ? "positive" : "negative",
          icon: response.success ? "done" : "warning",
          message:
            $t.t("add group") +
            (response.success ? $t.t("success") : $t.t("fail")) +
            "!",
          position: "top",
          timeout: 1500,
        });
      }
    };

    const requestEditSignalSourceGroup = async () => {
      let response = await GlobalData.getInstance()
        .getCurrentClient()
        ?.editSignalSourceGroup(
          uuid.value,
          name.value ?? "",
          selected.value ?? ""
        );
      if (response) {
        $q.notify({
          color: response.success ? "positive" : "negative",
          icon: response.success ? "done" : "warning",
          message:
            $t.t("edit group") +
            (response.success ? $t.t("success") : $t.t("fail")) +
            "!",
          position: "top",
          timeout: 1500,
        });
      }
    };

    return {
      show_dialog,
      type,
      name,
      uuid,
      selected,
      loading,
      tree_nodes,
      showDialog(options: any) {
        if (options) {
          type.value = options.type ?? 1;
          if (type.value == 2) {
            name.value = options.data?.name ?? null;
          }

          const signal_item_data_ =
            GlobalData.getInstance().signal_source_groups.find(
              (e) => e && e.uuid == options.data?.uuid
            );
          if (signal_item_data_) {
            selected.value = signal_item_data_.parent_uuid;
          } else {
            selected.value = "";
          }
          uuid.value = options.data?.uuid ?? null;
        }
        show_dialog.value = true;
      },
      resetData() {
        loading.value = false;
        (selected.value = null), (name.value = null);
        type.value = 1;
      },
      treeNodesFilter(node: any, filter: any) {
        return node.is_group && !node.item_data?.system_default;
      },

      async onSubmit() {
        loading.value = true;
        try {
          await (type.value == 2
            ? requestEditSignalSourceGroup()
            : requestAddSignalSourceGroup());
          show_dialog.value = false;
        } catch {}
        loading.value = false;
      },
    };
  },
});
</script>
