<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>
                <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 v-model="props.row.value">
                            <q-select
                              :options="signals"
                              option-label="name"
                              option-value="uuid"
                              emit-value
                              map-options
                              v-model="props.row.value"
                            >
                            </q-select>
                          </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 { PlanEntity } from "src/entities/PlanEntity";
import { resolve } from "dns";

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);

    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,
      loga(a: any) {
        console.log(a);
      },
      showDialog(options: StringKeyValueEntity[] | null) {
        show_dialog.value = true;
        if (options) {
          datas.value = [];
          for (const item of options) {
            datas.value.push(item);
          }
        }
      },
      showDialogAsync(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;
          }
        });
      },
      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(datas.value);
            _resolve = null;
          }
          show_dialog.value = false;
        } catch {}
        loading.value = false;
      },
    };
  },
});
</script>
