<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 mode")
                  : type == 2
                  ? $t("edit mode")
                  : $t("add mode")
              }}
            </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>
              <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('mode name')"
                  :hint="$t('please input mode 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-input
                  autofocus
                  :loading="loading"
                  :disable="loading"
                  filled
                  type="number"
                  min="0"
                  max="65535"
                  v-model.number="index"
                  :label="$t('mode index')"
                  :hint="$t('please input mode index')"
                  lazy-rules
                  :rules="[checkIndex]"
                  @keydown="
                    (evt) => {
                      if (evt.keyCode == 13) {
                        $refs?.accept?.click();
                      }
                    }
                  "
                >
                </q-input>
              </q-item-section>
            </q-item>
            <q-item
              v-show="
                !$store.state.custom_defines.is_custom_isv ||
                $store.state.advanced_debug
              "
            >
              <q-card class="full-width" style="height: 25vh">
                <q-card-section
                  ><span>{{ $t("joint action equipment") }}</span>
                  <q-btn
                    style="float: right; top: -10px"
                    round
                    flat
                    icon="add"
                    color="green"
                    @click="addEquipment"
                  >
                    <q-tooltip>{{ $t("add") }}</q-tooltip>
                  </q-btn>
                </q-card-section>
                <q-separator />
                <q-scroll-area style="height: 19vh" class="full-width scroll">
                  <q-list class="fit">
                    <q-item v-for="(item, index) of equipments" :key="index">
                      <q-item-section avatar class="q-mr-md">
                        {{ $t("equipment") }}:
                      </q-item-section>
                      <q-item-section>
                        <q-select
                          :options="equipment_options"
                          emit-value
                          map-options
                          v-model="item.key"
                          option-value="key"
                          option-label="value"
                          lazy-rules
                        />
                        <!-- {{ getEquipmentName(item.key) }} -->
                      </q-item-section>
                      <q-item-section avatar class="q-mr-md">
                        {{ $t("mode") }}:
                      </q-item-section>
                      <q-item-section>
                        <q-input v-model="item.value"></q-input>
                      </q-item-section>
                      <q-space />
                      <q-item-section avatar>
                        <q-btn
                          @click="deleteEquipment(index)"
                          round
                          flat
                          icon="delete"
                          color="red"
                        >
                          <q-tooltip>{{ $t("delete") }}</q-tooltip>
                        </q-btn>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-scroll-area>
              </q-card>
            </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>
  <list-joint-action-equipment-dialog
    ref="list_joint_action_equipment_dialog"
  />
</template>

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

<script lang="ts">
import { defineComponent, ref, watch, computed, Ref } from "vue";
import { useStore } from "src/store";
import GlobalData from "src/common/GlobalData";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { api } from "boot/axios";
import { HttpProtocol } from "src/entities/HttpProtocol";
import { StringKeyValueEntity } from "src/entities/StringKeyValueEntity";
import ListJointActionEquipmentDialog from "src/components/ListJointActionEquipmentDialog.vue";
import JointActionEquipmentTableEntity from "src/entities/JointActionEquipmentTableEntity";
import EventBus, { EventNamesDefine } from "src/common/EventBus";

export default defineComponent({
  name: "ComponentModeDialog",

  components: { ListJointActionEquipmentDialog },

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

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

    const equipments: Ref<StringKeyValueEntity[]> = ref([]);
    const list_joint_action_equipment_dialog: Ref<any> = ref(null);

    const equipment_options: Ref<StringKeyValueEntity[]> = ref([]);

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

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

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

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

    const updateEquipmentOptions = () => {
      GlobalData.getInstance()
        .getCurrentClient()
        ?.getJointActionEquipments()
        .then((response) => {
          if (response && Array.isArray(response.entities)) {
            equipment_options.value = [];
            for (const item of response.entities) {
              if (item) {
                equipment_options.value.push({
                  key: item.uuid,
                  value: item.name,
                });
              }
            }
          }
        });
    };

    EventBus.getInstance().on(
      EventNamesDefine.RefreshJointActionEquipmentList,
      () => {
        updateEquipmentOptions();
      }
    );

    return {
      show_dialog,
      type,
      name,
      index,
      uuid,
      selected,
      loading,
      tree_nodes,
      equipments,
      equipment_options,

      list_joint_action_equipment_dialog,

      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;
            index.value = options.data?.item_data?.number ?? 0;
            backup_index = index.value;
            equipments.value =
              options.data?.item_data?.joint_action_equipments ?? [];
          } else {
            selected.value = options.data?.uuid ?? null;
            uuid.value = options.data?.uuid ?? null;
            index.value = 0;
          }

          updateEquipmentOptions();
          equipments.value = [];
          {
            let obj = null;
            if (
              typeof options.data?.item_data?.joint_action_equipments ==
              "string"
            ) {
              try {
                obj = JSON.parse(
                  options.data?.item_data?.joint_action_equipments
                );
              } catch (e) {
                console.error(e);
              }
            }
            if (Array.isArray(obj)) {
              for (const item of obj) {
                if (item && typeof item != "undefined") {
                  const temp_item = item as StringKeyValueEntity;
                  if (temp_item) {
                    const f = equipment_options.value.find(
                      (element) => element && element.key == temp_item.key
                    );
                    if (f) {
                      equipments.value.push(temp_item);
                    }
                  }
                }
              }
            }
          }
        }
        show_dialog.value = true;
      },
      resetData() {
        loading.value = false;
        equipments.value = [];
        selected.value = null;
        name.value = null;
        type.value = 1;
        backup_index = 0;
      },
      treeNodesFilter(node: any, filter: any) {
        return node.is_group;
      },
      checkIndex(val: number) {
        return new Promise(async (resolve, reject) => {
          if (val < 0) {
            resolve($t.t("Please type 0~65535"));
          } else {
            try {
              let url = GlobalData.getInstance().createCurrentRequestUrl();
              if (!url) {
                url = new URL(window.location.hostname);
              }
              url.pathname = HttpProtocol.RequestCheckModeIndex;
              url.searchParams.append("index", index.value.toString());
              let response = (await api.get(url.toString())).data as boolean;
              if (typeof response != "boolean") {
                try {
                  response = JSON.parse(response);
                } catch {
                  response = false;
                }
              }
              if (index.value == backup_index) {
                response = true;
              }
              if (!response) {
                resolve($t.t("index exised") + "!");
              } else {
                resolve(true);
              }
            } catch (e) {
              resolve($t.t("check error"));
            }
          }
        });
      },
      async onSubmit() {
        loading.value = true;
        try {
          await (type.value == 2 ? requestEditMode() : requestAddMode());
          show_dialog.value = false;
        } catch {}
        loading.value = false;
      },
      async addEquipment() {
        const response = await GlobalData.getInstance()
          .getCurrentClient()
          ?.getJointActionEquipments();
        if (response && Array.isArray(response.entities)) {
          if (response.entities.length) {
            const v = new StringKeyValueEntity();
            v.key = response.entities[0].uuid;
            v.value = "mode name";
            equipments.value.push(v);
          } else {
            $q.notify({
              color: "warning",
              icon: "warning",
              message: $t.t(
                "joint action equipment is empty! please add equipment first!"
              ),
              position: "top",
              timeout: 1500,
            });

            if (list_joint_action_equipment_dialog.value) {
              list_joint_action_equipment_dialog.value.showDialog();
            }
          }
        } else {
          $q.notify({
            color: "negative",
            icon: "warning",
            message: "data error!",
            position: "top",
            timeout: 1500,
          });
        }
      },
      deleteEquipment(index: number) {
        equipments.value.splice(index, 1);
      },
    };
  },
});
</script>
