<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="max-width: 70vw">
      <q-form @submit="onSubmit">
        <q-card-section class="q-ma-none q-pa-sm">
          <div class="row">
            <div class="col-auto text-h6">
              {{ $t("register dialog") }}
            </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 class="scroll" style="width: 60vw">
          <q-list>
            <q-item>
              <q-item-section avatar class="header_label">
                {{ $t("register code") }}
              </q-item-section>
              <q-item-section>
                <div style="word-break: break-all">
                  {{ register_code }}
                </div>
              </q-item-section>
              <q-item-section avatar>
                <qrcode-vue :value="register_code" level="H" />
              </q-item-section>
              <q-item-section avatar>
                <q-btn
                  round
                  flat
                  icon="content_copy"
                  color="green"
                  @click="
                    copyToClipboard(register_code).then(() =>
                      $q.notify({
                        color: 'positive',
                        icon: 'done',
                        message: $t('copy') + $t('success'),
                        position: 'top',
                        timeout: 1500,
                      })
                    )
                  "
                >
                  <q-tooltip>
                    {{ $t("copy") }}{{ $t("register code") }}
                  </q-tooltip>
                </q-btn>
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section avatar class="header_label">
                {{ $t("active code") }}
              </q-item-section>
              <q-item-section>
                <q-input
                  type="textarea"
                  v-model="active_code"
                  lazy-rules
                  :rules="[
                    (val) =>
                      (val && val.length > 0) || $t('Please type something'),
                  ]"
                />
              </q-item-section>
            </q-item>
          </q-list>
        </q-card-section>

        <q-separator />

        <q-card-actions align="right">
          <q-btn
            :loading="loading"
            flat
            :label="$t('Cancel')"
            color="primary"
            v-close-popup
          />
          <q-btn
            ref="accept"
            flat
            :label="$t('register')"
            :loading="loading"
            type="submit"
            color="primary"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

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

<script lang="ts">
import {
  defineComponent,
  ref,
  Ref,
  watch,
  computed,
  onMounted,
  onBeforeUnmount,
  nextTick,
} from "vue";
import { useStore } from "src/store";
import { useQuasar, copyToClipboard } from "quasar";
import { useI18n } from "vue-i18n";
import GlobalData from "src/common/GlobalData";
import QrcodeVue from "qrcode.vue";

export default defineComponent({
  name: "ComponentRegisterDialog",
  components: { QrcodeVue },
  setup() {
    let $store = useStore();
    let $q = useQuasar();
    let $t = useI18n();

    let show_dialog = ref(false);
    let loading = ref(false);
    let register_code: Ref<string> = ref("");
    let active_code: Ref<string> = ref("");

    return {
      show_dialog,
      loading,
      register_code,
      active_code,
      copyToClipboard,
      isShow() {
        return show_dialog.value;
      },
      async showDialog() {
        show_dialog.value = true;
        loading.value = true;

        try {
          let response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.getRegisterInfo();
          if (response) {
            if (response.registered) {
              const app_config = GlobalData.getInstance().applicationConfig;
              if (app_config) {
                app_config.registered = true;
                show_dialog.value = false;
              }
            }
            register_code.value = response.register_code;
          }
          loading.value = false;
        } catch (e) {
          console.log(e);
          show_dialog.value = false;
        }
      },
      resetData() {
        loading.value = false;
        active_code.value = "";
        register_code.value = "";
      },

      async onSubmit() {
        loading.value = true;
        try {
          let success = false;
          const response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.registerDevice(register_code.value, active_code.value);
          if (response) {
            success = response.success;
          }

          $q.notify({
            color: success ? "positive" : "negative",
            icon: success ? "done" : "warning",
            message:
              $t.t("register device") +
              (success ? $t.t("success") : $t.t("fail")) +
              "!",
            position: "top",
            timeout: 1500,
          });
          show_dialog.value = false;
        } catch {}
        loading.value = false;
      },
      toggleFullScreen(e: any) {
        console.log(e);
        const target = e.target.parentNode.parentNode.parentNode;
        console.log(target);
        $q.fullscreen
          .toggle(target)
          .then(() => {})
          .catch((err) => {
            console.error(err);
          });
      },
    };
  },
});
</script>
