<template>
  <q-dialog persistent v-model="show_dialog" @before-hide="resetData">
    <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 plan")
                  : type == 2
                  ? $t("edit plan")
                  : $t("add plan")
              }}
            </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: 50vh; width: 45vw" class="scroll">
          <q-list>
            <q-item>
              <q-item-label>{{ $t("parent group") }}:</q-item-label>
            </q-item>
            <q-item 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('plan name')"
                  :hint="$t('please input plan 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-item>
              <q-item-section>
                <q-table
                  style="height: 50vh"
                  :rows="datas"
                  :columns="columns"
                  virtual-scroll
                  :title="$t('plan 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"
                              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="modes"
                              option-label="name"
                              option-value="uuid"
                              emit-value
                              map-options
                              v-model="props.row.value"
                            >
                            </q-select>
                          </q-popup-edit>
                          {{
                            modes.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;
}
</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";

export default defineComponent({
  name: "ComponentPlanDialog",

  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);
    let datas: Ref<StringKeyValueEntity[]> = ref([]);
    let modes = ref(GlobalData.getInstance().modes);
    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;

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

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

    const requestAddPlan = async () => {
      let entity = new PlanEntity();
      entity.group_uuid = selected.value;
      entity.uuid = uuid.value;
      entity.name = name.value ?? "";
      entity.datas = datas.value;
      let response = await GlobalData.getInstance()
        .getCurrentClient()
        ?.addPlan(entity);
      if (response) {
        $q.notify({
          color: response.success ? "positive" : "negative",
          icon: response.success ? "done" : "warning",
          message:
            $t.t("add plan") +
            (response.success ? $t.t("success") : $t.t("fail")) +
            "!",
          position: "top",
          timeout: 1000,
        });
      }
    };

    const requestEditPlan = async () => {
      let entity = new PlanEntity();
      entity.group_uuid = selected.value;
      entity.uuid = uuid.value;
      entity.name = name.value ?? "";
      entity.datas = datas.value;
      let response = await GlobalData.getInstance()
        .getCurrentClient()
        ?.editPlan(entity);
      if (response) {
        $q.notify({
          color: response.success ? "positive" : "negative",
          icon: response.success ? "done" : "warning",
          message:
            $t.t("edit plan") +
            (response.success ? $t.t("success") : $t.t("fail")) +
            "!",
          position: "top",
          timeout: 1000,
        });
      }
    };

    return {
      show_dialog,
      type,
      name,
      uuid,
      selected,
      loading,
      datas,
      columns,
      show_context_menu,
      target_dom,
      tree_nodes,
      modes,
      loga(a: any) {
        console.log(a);
      },
      showDialog(options: any) {
        if (options) {
          type.value = options.type ?? 1;
          if (type.value == 2) {
            name.value = options.data?.name ?? null;
            selected.value = options.data?.item_data?.group_uuid ?? null;
            uuid.value = options.data?.item_data?.uuid ?? null;
            datas.value = JSON.parse(
              JSON.stringify(options.data?.item_data?.datas ?? [])
            );
          } else {
            name.value = options.data?.name ?? null;
            selected.value = options.data?.uuid ?? null;
            uuid.value = options.data?.uuid ?? null;
            datas.value = options.data?.item_data?.datas ?? [];
          }
          modes.value = GlobalData.getInstance().modes;

          let temp = [];
          for (
            let i = 0;
            i <
            (datas.value.length % 2
              ? datas.value.length - 1
              : datas.value.length);
            i += 2
          ) {
            const item = datas.value[i];
            console.log(item);
            if (item && item.key.startsWith("operator_")) {
              const item_value = GlobalData.getInstance().modes.find(
                (element) => element && element.uuid == item.value
              );
              if (item_value) {
                temp.push(datas.value[i]);
                temp.push(datas.value[i + 1]);
              }
            }
          }
          if (temp.length != datas.value.length) {
            $q.notify({
              type: "warning",
              message: $t.t("auto delete unknow mode success"),
              position: "top",
              timeout: 1000,
            });
          }
          datas.value = temp;
        }
        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;
      },
      addRow() {
        datas.value.push({
          key: "operator_call_mode",
          value: GlobalData.getInstance().modes[0].uuid,
        });

        datas.value.push({
          key: "param_delay",
          value: "3000",
        });
      },
      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 {
          await (type.value == 2 ? requestEditPlan() : requestAddPlan());
          show_dialog.value = false;
        } catch {}
        loading.value = false;
      },
    };
  },
});
</script>
