<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">
              {{ is_add ? $t("add") : $t("edit") }}
              {{ $t("joint action equipment") }}
            </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-section avatar class="form_header">{{
                $t("name")
              }}</q-item-section>
              <q-item-section>
                <q-input
                  v-model="show_name"
                  maxlength="255"
                  :rules="[
                    (val) =>
                      (val && val.length > 0) || $t('Please type something'),
                  ]"
                  lazy-rules
                />
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section avatar class="form_header">{{
                $t("type")
              }}</q-item-section>
              <q-item-section>
                <q-select
                  :options="types"
                  @update:model-value="onTypeSelectChanged"
                  emit-value
                  map-options
                  v-model="show_type"
                  option-value="key"
                  option-label="label"
                  lazy-rules
                  :rules="[
                    (val) =>
                      (is_add ? show_type != 'UNKNOW' : true) ||
                      $t('type can not be unknow'),
                  ]"
                />
              </q-item-section>
            </q-item>
            <q-item v-if="connect_type == 'network'">
              <q-item-section avatar class="form_header">{{
                $t("host")
              }}</q-item-section>
              <q-item-section>
                <q-input
                  v-model="host"
                  maxlength="255"
                  :rules="[
                    (val) =>
                      (val && val.length > 0) || $t('Please type something'),
                    (val) =>
                      isHost(val) ||
                      $t(
                        'Please input vaild host. example: 192.168.1.1 or 192.168.1.1:8080'
                      ),
                  ]"
                  lazy-rules
                />
              </q-item-section>
            </q-item>
          </q-list>
        </q-card-section>

        <q-separator />

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

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

.form_header {
  width: 20%;
}
</style>

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

export default defineComponent({
  name: "ComponentEditJointActionEquipmentDialog",

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

    let show_dialog = ref(false);
    const loading = ref(false);
    const is_add = ref(false);

    const kDefaultTypeIndex = 1;

    const types = [
      {
        key: "UNKNOW",
        label: $t.t("unknow"),
        value: {
          protocol: "UNKNOW",
          protocol_version: "UNKNOW",
        },
      },
      {
        key: "VTRON",
        label: $t.t("VTRON"),
        value: {
          protocol: "VTRON",
          protocol_version: "Normal",
          connect_type: "network",
        },
      },
      {
        key: "CX_MISP3000",
        label: $t.t("CX_MISP3000"),
        value: {
          protocol: "CX_MISP3000",
          protocol_version: "Normal",
          connect_type: "network",
        },
      },
      // {
      //   key: "VTRON2",
      //   label: $t.t("VTRON2"),
      //   value: {
      //     protocol: "VTRON",
      //     protocol_version: "Normal2",
      //     connect_type: "serialport",
      //   },
      // },
    ];

    let equipment: JointActionEquipmentTableEntity =
      new JointActionEquipmentTableEntity();
    const show_name = ref($t.t("new name"));
    const show_type = ref("");
    const connect_type: Ref<string | undefined> = ref("network");
    const host = ref("192.168.1.1");

    const onTypeSelectChanged = (value: string) => {
      const type = types.find((element) => element && element.key == value);
      if (type) {
        connect_type.value = type.value.connect_type;
      } else {
        connect_type.value = "";
      }
    };

    const copy_propertys = (
      const_obj: any,
      obj: JointActionEquipmentTableEntity
    ) => {
      if (const_obj) {
        try {
          for (const item of Object.keys(const_obj)) {
            if (typeof const_obj[item] != "undefined") {
              (<any>obj)[item] = const_obj[item];
            }
          }
        } catch {}
      }
    };

    return {
      show_dialog,
      loading,
      is_add,
      show_name,
      show_type,
      types,
      connect_type,
      host,

      onTypeSelectChanged,
      async showDialog(data: JointActionEquipmentTableEntity | null) {
        show_dialog.value = true;
        is_add.value = !data;
        equipment = new JointActionEquipmentTableEntity();

        show_type.value = types[kDefaultTypeIndex].key;
        if (data) {
          copy_propertys(data, equipment);
          show_name.value = data.name;

          {
            const temp = types.find(
              (element) =>
                element &&
                element.value &&
                element.value.protocol == data.protocol &&
                element.value.protocol_version == data.protocol_version
            );
            if (temp) {
              show_type.value = temp.key;
            }
          }

          host.value = data.address;
        }
        onTypeSelectChanged(show_type.value);
      },

      resetData() {
        show_name.value = $t.t("new name");
        show_type.value = types[kDefaultTypeIndex].key;
        EventBus.getInstance().emit(
          EventNamesDefine.RefreshJointActionEquipmentList
        );

        loading.value = false;
      },
      async onSubmit() {
        loading.value = true;
        let success = false;
        try {
          let request_data = null;
          if (is_add.value) {
            request_data = new JointActionEquipmentTableEntity();
            request_data.uuid = uid().replace(/-/g, "");
          } else {
            request_data = equipment;
          }
          if (request_data) {
            request_data.name = show_name.value;
            request_data.address = host.value;
            const temp = types.find(
              (element) => element && element.key == show_type.value
            );
            if (temp && temp.value) {
              request_data.protocol = temp.value.protocol;
              request_data.protocol_version = temp.value.protocol_version;
            }
            const response = await GlobalData.getInstance()
              .getCurrentClient()
              ?.setJointActionEquipment(request_data);
            success = !!(response && response.success);
          }
        } catch {}
        $q.notify({
          color: success ? "positive" : "negative",
          icon: success ? "done" : "warning",
          message:
            (is_add.value ? $t.t("add") : $t.t("edit")) +
            $t.t(" ") +
            $t.t(" ") +
            $t.t("equipment data") +
            (success ? $t.t("success") : $t.t("fail")) +
            "!",
          position: "top",
          timeout: 1500,
        });
        loading.value = false;
        if (success) {
          show_dialog.value = false;
        }
      },
      isHost(str: string) {
        return (
          str == "localhost" ||
          /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/.test(
            str
          ) ||
          /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\:([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/.test(
            str
          )
        );
      },
    };
  },
});
</script>
