<template>
  <q-dialog
    persistent
    v-model="show_dialog"
    @before-hide="resetData"
    @keydown="
      (evt) => {
        if (evt.keyCode == 27) {
          show_dialog = false;
        }
      }
    "
  >
    <q-card class="overflow-hidden" style="overflow-y: scroll; max-width: 50vw">
      <q-form @submit="onSubmit">
        <q-card-section class="q-ma-none q-pa-sm">
          <div class="row">
            <div class="col-auto text-h6">
              {{ $t("polling setting") }}
            </div>
            <q-space />
            <div>
              <q-btn
                :loading="loading"
                flat
                round
                icon="close"
                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: 70vh; width: 50vw" class="scroll">
          <q-list>
            <q-item>
              <q-item-section avatar>
                <div class="text-h6 q-pb-md">
                  {{ $t("polling name") }}:
                </div></q-item-section
              >
              <q-item-section
                ><q-input
                  v-model="polling_name"
                  lazy-rules
                  :placeholder="$t('please input polling name')"
                  :rules="[
                    (val) =>
                      (val && val.length > 0) || $t('Please type something'),
                  ]"
              /></q-item-section>
            </q-item>
            <q-item>
              <q-item-section>
                <q-table
                  style="height: 50vh"
                  :rows="datas"
                  :columns="columns"
                  virtual-scroll
                  :title="$t('polling data') + ':'"
                  hide-bottom
                  color="primary"
                  row-key="name"
                  :loading="loading"
                  :rows-per-page-options="[0]"
                  :virtual-scroll-sticky-size-start="48"
                  @row-contextmenu="onContextMenu"
                >
                  <template v-slot:loading>
                    <q-inner-loading showing color="primary" />
                  </template>
                  <template v-slot:body-cell="props">
                    <q-td :props="props">
                      <div v-if="props.col.name == 'value'">
                        <div v-if="props.pageIndex % 2">
                          {{ props.value }}{{ $t("s") }}
                          <q-popup-edit v-model="props.row.value">
                            <q-input
                              type="number"
                              v-model="props.row.value"
                              :min="min_delay"
                              dense
                              autofocus
                            >
                              <template v-slot:append>
                                <span>{{ $t("s") }}</span>
                              </template>
                            </q-input>
                          </q-popup-edit>
                        </div>
                        <div v-else>
                          <q-popup-edit
                            ref="popup_edit"
                            v-model="props.row.value"
                          >
                            <q-tree
                              ref="tree"
                              :nodes="$store.state.signal_source_tree"
                              node-key="uuid"
                              labelKey="name"
                              default-expand-all
                            >
                              <template v-slot:default-header="prop">
                                <q-item
                                  class="full-width"
                                  :clickable="!prop.node.is_group"
                                  @click="
                                    (evt) => {
                                      props.row.value = prop.node.uuid;
                                      $refs.popup_edit.hide();
                                    }
                                  "
                                  :style="{
                                    border:
                                      props.row.value == prop.node.uuid
                                        ? '1px solid #aacceec2'
                                        : 'none',
                                  }"
                                >
                                  <q-item-section avatar>
                                    <q-icon
                                      :name="
                                        prop.node.is_group
                                          ? 'img:source_icon/group.png'
                                          : getItemIcon(
                                              prop.node.item_data?.window_type
                                            )
                                      "
                                      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-popup-edit>
                          {{
                            signals.find(
                              (element) =>
                                element && element.uuid == props.row.value
                            )?.name ?? ""
                          }}
                        </div>
                      </div>
                      <div v-else>
                        {{ $t(props.value) }}
                      </div>
                    </q-td>
                  </template>
                </q-table>
              </q-item-section>
            </q-item>
          </q-list>
        </q-card-section>
        <q-separator />

        <q-card-actions align="left">
          <q-btn
            :loading="loading"
            flat
            :label="$t('add row')"
            color="primary"
            @click="addRow"
          />
          <q-space />
          <q-btn
            :loading="loading"
            flat
            :label="$t('Cancel')"
            color="primary"
            v-close-popup
          />
          <q-btn
            ref="accept"
            flat
            :label="$t('Accept')"
            :loading="loading"
            type="submit"
            color="primary"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
  <div>
    <q-menu :target="target_dom" v-model="show_context_menu">
      <q-list>
        <q-item clickable v-close-popup @click="(evt) => deleteRow()">
          <q-item-section avatar
            ><q-icon name="delete" color="red"
          /></q-item-section>
          <q-item-section>{{ $t("delete row") }}</q-item-section>
        </q-item>
        <q-item clickable v-close-popup @click="(evt) => addRow()">
          <q-item-section avatar><q-icon name="add" /></q-item-section>
          <q-item-section>{{ $t("add row") }}</q-item-section>
        </q-item>
      </q-list>
    </q-menu>
  </div>
</template>

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

.width_5_1 {
  width: 18%;
}
</style>

<script lang="ts">
import { defineComponent, ref, 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";
import { StringKeyValueEntity } from "src/entities/StringKeyValueEntity";
import { Common } from "src/common/Common";

const __MIN_DELAY = 10;

export default defineComponent({
  name: "ComponentPollingSettingDialog",

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

    const min_delay = ref(__MIN_DELAY);
    let show_dialog = ref(false);

    let loading = ref(false);
    let datas: Ref<StringKeyValueEntity[]> = ref([]);
    let signals = ref(GlobalData.getInstance().signal_source);
    let polling_name = ref("");

    const columns = [
      {
        align: "left",
        name: "key",
        required: true,
        label: $t.t("operator"),
        field: "key",
        sortable: false,
      },
      {
        align: "left",
        name: "value",
        label: $t.t("operator value"),
        field: "value",
        sortable: false,
      },
    ];

    let show_context_menu = ref(false);
    let target_dom: any = ref(document.body.children[0]);
    let current_index = 0;

    let _resolve: any = null;

    return {
      show_dialog,
      min_delay,
      loading,
      datas,
      columns,
      show_context_menu,
      target_dom,
      signals,
      polling_name,
      loga(a: any) {
        console.log(a);
      },
      showDialog(name: string, options: StringKeyValueEntity[] | null) {
        show_dialog.value = true;
        if (options) {
          datas.value = [];
          for (const item of options) {
            datas.value.push(item);
          }
        }
        polling_name.value = name ?? $t.t("new polling");
      },
      showDialogAsync(name: string, options: StringKeyValueEntity[] | null) {
        return new Promise((resolve) => {
          if (_resolve) {
            _resolve();
            _resolve = null;
          }
          _resolve = resolve;
          show_dialog.value = true;
          if (options) {
            datas.value = [];
            for (const item of options) {
              datas.value.push(item);
            }
            signals.value = GlobalData.getInstance().signal_source;
          }
          polling_name.value = name ?? $t.t("new polling");
        });
      },
      resetData() {
        loading.value = false;
        if (_resolve) {
          _resolve();
          _resolve = null;
        }
      },
      addRow() {
        datas.value.push({
          key: "operator_signal_source",
          value: GlobalData.getInstance().signal_source[0].uuid,
        });

        datas.value.push({
          key: "param_delay",
          value: __MIN_DELAY.toString(),
        });
        signals.value = GlobalData.getInstance().signal_source;
      },
      onContextMenu(
        evt: PointerEvent,
        row: StringKeyValueEntity,
        index: number
      ) {
        evt.preventDefault();
        evt.stopPropagation();

        target_dom.value = evt.srcElement;
        if (row) {
          current_index = index;
          show_context_menu.value = true;
        }
      },
      deleteRow() {
        if (datas.value.length > current_index) {
          const start = Math.floor(current_index / 2);
          if (!isNaN(start)) {
            datas.value.splice(start, 2);
          }
        }
      },
      async onSubmit() {
        loading.value = true;
        try {
          if (_resolve) {
            _resolve({
              name: polling_name.value,
              datas: datas.value,
            });
            _resolve = null;
          }
          show_dialog.value = false;
        } catch {}
        loading.value = false;
      },
      getItemIcon(item_type: string) {
        return Common.getSignalSourceIcon(item_type);
      },
    };
  },
});
</script>
