<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: 60vw">
      <q-form @submit="onSubmit">
        <q-card-section class="q-ma-none q-pa-sm">
          <div class="row">
            <div class="col-auto text-h6">
              {{ $t("clock") }}
            </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: 68vh; width: 55vw" class="scroll">
          <q-list>
            <q-item v-if="false">
              <q-item-section avatar class="head_1">
                {{ $t("font name") }}
              </q-item-section>
              <q-item-section>
                <q-input v-model="clock_entity.font_name" />
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section>
                <q-item>
                  <q-item-section avatar class="head_1">
                    {{ $t("clock type") }}
                  </q-item-section>
                  <q-item-section>
                    <q-select
                      v-model="clock_entity.type"
                      :options="[
                        {
                          label: $t('normal clock'),
                          value: 0,
                        },
                        {
                          label: $t('analog clock'),
                          value: 2,
                        },
                      ]"
                      emit-value
                      map-options
                    >
                    </q-select>
                  </q-item-section>
                </q-item>
              </q-item-section>
              <q-item-section>
                <q-item>
                  <q-item-section avatar class="head_1">
                    {{ $t("font size") }}
                  </q-item-section>
                  <q-item-section>
                    <q-input
                      v-model="clock_entity.font_size"
                      type="number"
                      lazy-rules
                      :rules="[
                        (val) =>
                          (val && val.toString().length > 0) ||
                          $t('Please type something'),
                      ]"
                    >
                      <template v-slot:append>
                        <span>pt</span>
                      </template>
                    </q-input>
                  </q-item-section>
                </q-item>
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section class="q-mr-md">
                <q-item>
                  <q-item-section avatar class="head_1">
                    {{ $t("font color") }}
                  </q-item-section>
                  <q-item-section>
                    <q-input
                      v-model="clock_entity.font_color"
                      :rules="['anyColor']"
                    >
                      <template v-slot:append>
                        <q-icon name="colorize" class="cursor-pointer">
                          <q-popup-proxy
                            cover
                            transition-show="scale"
                            transition-hide="scale"
                          >
                            <q-color v-model="clock_entity.font_color" />
                          </q-popup-proxy>
                        </q-icon>
                      </template>
                    </q-input>
                  </q-item-section>
                </q-item>
              </q-item-section>
              <q-item-section>
                <q-item>
                  <q-item-section avatar class="head_1">
                    {{ $t("background color") }}
                  </q-item-section>
                  <q-item-section>
                    <q-input
                      :disable="
                        clock_entity.type == 2 ||
                        clock_entity.background_transparent
                      "
                      v-model="clock_entity.background_color"
                      :rules="['anyColor']"
                    >
                      <template v-slot:append>
                        <q-icon name="colorize" class="cursor-pointer">
                          <q-popup-proxy
                            cover
                            transition-show="scale"
                            transition-hide="scale"
                          >
                            <q-color v-model="clock_entity.background_color" />
                          </q-popup-proxy>
                        </q-icon>
                      </template>
                    </q-input>
                    <q-tooltip v-if="clock_entity.type == 2">
                      {{ $t("only normal clock support") }}</q-tooltip
                    >
                  </q-item-section>
                </q-item>
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section>
                <q-item>
                  <q-item-section avatar class="head_1">
                    {{ $t("date format") }}
                  </q-item-section>
                  <q-item-section>
                    <q-select
                      :disable="clock_entity.type == 2"
                      v-model="clock_entity.date_format"
                      :options="date_format_options"
                      emit-value
                      map-options
                    >
                    </q-select>
                    <q-tooltip v-if="clock_entity.type == 2">
                      {{ $t("only normal clock support") }}</q-tooltip
                    >
                  </q-item-section>
                </q-item>
              </q-item-section>

              <q-item-section>
                <q-item>
                  <q-item-section avatar class="head_1">
                    {{ $t("time format") }}
                  </q-item-section>
                  <q-item-section>
                    <q-select
                      :disable="clock_entity.type == 2"
                      v-model="clock_entity.time_format"
                      :options="time_format_options"
                      emit-value
                      map-options
                    >
                    </q-select>
                    <q-tooltip v-if="clock_entity.type == 2">
                      {{ $t("only normal clock support") }}</q-tooltip
                    >
                  </q-item-section>
                </q-item>
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section>
                <q-item>
                  <q-item-section avatar class="head_2">
                    {{ $t("text") }}
                  </q-item-section>
                  <q-item-section>
                    <q-input
                      :disable="
                        clock_entity.type == 0 && clock_entity.multiple_lines
                      "
                      v-model="clock_entity.text"
                    />
                  </q-item-section>
                </q-item>
              </q-item-section>
              <q-tooltip
                v-if="clock_entity.type == 0 && clock_entity.multiple_lines"
              >
                {{
                  $t(
                    "the current property is only valid for single-line displays"
                  )
                }}</q-tooltip
              >
            </q-item>
            <q-item>
              <q-item-section>
                <q-checkbox
                  left-label
                  v-model="clock_entity.show_date"
                  :label="$t('date')"
                />
              </q-item-section>
              <q-item-section>
                <q-checkbox
                  :disable="clock_entity.type == 2"
                  left-label
                  v-model="clock_entity.show_time"
                  :label="$t('time')"
                >
                  <q-tooltip v-if="clock_entity.type == 2">
                    {{ $t("only normal clock support time hiding") }}</q-tooltip
                  >
                </q-checkbox>
              </q-item-section>
              <q-item-section>
                <q-checkbox
                  left-label
                  v-model="clock_entity.show_week"
                  :label="$t('week')"
                />
              </q-item-section>
              <q-item-section>
                <q-checkbox
                  :disable="clock_entity.type == 2"
                  v-model="clock_entity.background_transparent"
                  left-label
                  :label="$t('background transparent')"
                >
                  <q-tooltip v-if="clock_entity.type == 2">
                    {{ $t("only normal clock support") }}</q-tooltip
                  >
                </q-checkbox>
              </q-item-section>
              <q-item-section>
                <q-checkbox
                  :disable="clock_entity.type == 2"
                  left-label
                  v-model="clock_entity.multiple_lines"
                  :label="$t('multiple lines')"
                >
                  <q-tooltip v-if="clock_entity.type == 2">
                    {{
                      $t("only normal clock support multiple lines")
                    }}</q-tooltip
                  >
                </q-checkbox>
              </q-item-section>
              <q-item-section>
                <q-checkbox
                  v-model="clock_entity.bold"
                  left-label
                  :label="$t('font bold')"
                />
              </q-item-section>
            </q-item>
            <div class="q-mt-xs" v-if="clock_entity.type == 2">
              <q-separator class="q-mb-md" />
              <q-item>
                <q-item-section>
                  <q-btn
                    flat
                    no-caps
                    class="fit"
                    :style="{
                      'background-color': clock_entity.analog_second_color,
                      color:
                        getForegroundColor(clock_entity.analog_second_color) +
                        ' !important',
                    }"
                    :label="$t('hour mark color')"
                  >
                    <q-popup-proxy
                      cover
                      transition-show="scale"
                      transition-hide="scale"
                    >
                      <q-color
                        v-model="clock_entity.analog_second_color"
                      /> </q-popup-proxy></q-btn
                ></q-item-section>
                <q-item-section>
                  <q-btn
                    flat
                    no-caps
                    class="fit"
                    :style="{
                      'background-color':
                        clock_entity.analog_hour_pointer_color,
                      color:
                        getForegroundColor(
                          clock_entity.analog_hour_pointer_color
                        ) + ' !important',
                    }"
                    :label="$t('hour pointer color')"
                  >
                    <q-popup-proxy
                      cover
                      transition-show="scale"
                      transition-hide="scale"
                    >
                      <q-color
                        v-model="clock_entity.analog_hour_pointer_color"
                      /> </q-popup-proxy></q-btn
                ></q-item-section>
                <q-item-section>
                  <q-btn
                    flat
                    no-caps
                    class="fit"
                    :style="{
                      'background-color': clock_entity.analog_minute_color,
                      color:
                        getForegroundColor(clock_entity.analog_minute_color) +
                        ' !important',
                    }"
                    :label="$t('minute mark color')"
                  >
                    <q-popup-proxy
                      cover
                      transition-show="scale"
                      transition-hide="scale"
                    >
                      <q-color
                        v-model="clock_entity.analog_minute_color"
                      /> </q-popup-proxy
                  ></q-btn>
                </q-item-section>
                <q-item-section>
                  <q-btn
                    flat
                    no-caps
                    class="fit"
                    :style="{
                      'background-color':
                        clock_entity.analog_minute_pointer_color,
                      color:
                        getForegroundColor(
                          clock_entity.analog_minute_pointer_color
                        ) + ' !important',
                    }"
                    :label="$t('minute pointer color')"
                  >
                    <q-popup-proxy
                      cover
                      transition-show="scale"
                      transition-hide="scale"
                    >
                      <q-color
                        v-model="clock_entity.analog_minute_pointer_color"
                      /> </q-popup-proxy></q-btn
                ></q-item-section>
                <q-item-section>
                  <q-btn
                    flat
                    no-caps
                    class="fit"
                    :style="{
                      'background-color':
                        clock_entity.analog_second_pointer_color,
                      color:
                        getForegroundColor(
                          clock_entity.analog_second_pointer_color
                        ) + ' !important',
                    }"
                    :label="$t('second pointer color')"
                  >
                    <q-popup-proxy
                      cover
                      transition-show="scale"
                      transition-hide="scale"
                    >
                      <q-color
                        v-model="clock_entity.analog_second_pointer_color"
                      /> </q-popup-proxy></q-btn
                ></q-item-section>
              </q-item>
            </div>
          </q-list>
        </q-card-section>

        <q-separator />
        <q-card-actions>
          <q-space />
          <q-btn
            :loading="loading"
            flat
            no-caps
            :label="$t('close and reset')"
            color="primary"
            v-close-popup
          />
          <q-btn
            ref="accept"
            flat
            no-caps
            :label="$t('close and save')"
            :loading="loading"
            type="submit"
            color="primary"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.head_1 {
  width: 25%;
}

.head_2 {
  width: 12%;
}
</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, date as DateHelper } from "quasar";
import { useI18n } from "vue-i18n";
import ClockWindowParamEntity from "src/entities/ClockWindowParamEntity";
import { Protocol } from "src/entities/WSProtocol";

export default defineComponent({
  name: "ComponentClockSignalSourceDialog",
  components: {},

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

    const now = Date.now();

    const date_formats_en_ = [
      {
        label: DateHelper.formatDate(now, "YYYY/MM/DD"),
        value: "yyyy/MM/dd",
      },
      {
        label: DateHelper.formatDate(now, "YYYY-MM-DD"),
        value: "yyyy-MM-dd",
      },
      {
        label: DateHelper.formatDate(now, "DD/MM/YYYY"),
        value: "dd/MM/yyyy",
      },
      {
        label: DateHelper.formatDate(now, "DD-MM-YYYY"),
        value: "dd-MM-yyyy",
      },
    ];

    const date_formats_zh_ = [
      {
        label: DateHelper.formatDate(now, "YYYY年MM月DD日"),
        value: "yyyy年MM月dd日",
      },
      {
        label: DateHelper.formatDate(now, "DD日MM月YYYY年"),
        value: "dd日MM月yyyy年",
      },
    ];

    const time_formats_en_ = [
      {
        label: DateHelper.formatDate(now, "HH:mm:ss"),
        value: "hh:mm:ss",
      },
    ];

    const time_formats_zh_ = [
      {
        label: DateHelper.formatDate(now, "HH时mm分ss秒"),
        value: "hh时mm分ss秒",
      },
    ];

    const date_format_options: Ref<Array<any>> = ref([]);

    const time_format_options: Ref<Array<any>> = ref([]);

    const refresh_formats = () => {
      date_format_options.value = [];

      time_format_options.value = [];
      console.log();
      if ($t.locale.value == "zh-CN") {
        date_format_options.value = [...date_formats_en_, ...date_formats_zh_];
        time_format_options.value = [...time_formats_en_, ...time_formats_zh_];
      } else {
        date_format_options.value = date_formats_en_;
        time_format_options.value = time_formats_en_;
      }
    };

    refresh_formats();

    watch(
      () => $store.state.device_attribute,
      (value) => {
        refresh_formats();
      }
    );

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

    let clock_entity: Ref<ClockWindowParamEntity> = ref(
      new ClockWindowParamEntity()
    );

    let _resolove: any = null;

    const initialize_properties = (json: string) => {
      if (json) {
        try {
          const temp = JSON.parse(json);

          for (const item of Object.keys(clock_entity.value)) {
            if (typeof temp[item] != "undefined") {
              (<any>clock_entity.value)[item] = temp[item];
            }
          }
        } catch {}
      }
    };

    return {
      show_dialog,
      loading,
      clock_entity,
      date_format_options,
      time_format_options,

      showDialogAsync(options: any) {
        if (_resolove) {
          _resolove();
          _resolove = null;
        }
        show_dialog.value = true;
        initialize_properties(options);

        return new Promise((resolove) => {
          _resolove = resolove;
        });
      },
      resetData() {
        loading.value = false;
        if (_resolove) {
          _resolove();
          _resolove = null;
        }
      },
      async onSubmit() {
        loading.value = true;
        try {
          if (_resolove) {
            try {
              clock_entity.value.font_size = parseInt(
                clock_entity.value.font_size.toString()
              );
              _resolove(JSON.stringify(clock_entity.value));
            } catch {
              _resolove(null);
            }
          }
          show_dialog.value = false;
        } catch {}
        loading.value = false;
      },
      getForegroundColor(color: string) {
        // rgbToHex(0, 51, 255) => "#0033ff"
        function rgbToHex(r: any, g: any, b: any) {
          return (
            "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
          );
        }

        //hexToRgb("#0033ff") => {r: 0, g: 51, b: 255}
        //hexToRgb("#0033ff").g => 51
        function hexToRgb(hex: any) {
          // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
          var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
          hex = hex.replace(
            shorthandRegex,
            function (m: any, r: any, g: any, b: any) {
              return r + r + g + g + b + b;
            }
          );

          var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
          return result
            ? {
                r: parseInt(result[1], 16),
                g: parseInt(result[2], 16),
                b: parseInt(result[3], 16),
              }
            : null;
        }

        //灰度 = 红×0.299 + 绿×0.587 + 蓝×0.114
        function getGrayLevelFromRgb(r: any, g: any, b: any) {
          return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
        }

        // getGrayLevel('#167df0') => 0.4208352941176471
        function getGrayLevel(hex: any) {
          var rgb = hexToRgb(hex);
          if (rgb) {
            return getGrayLevelFromRgb(rgb.r, rgb.g, rgb.b);
          }
          return "#000000";
        }

        function getColor(background_color: any) {
          var grayLevel = getGrayLevel(background_color);
          return grayLevel > 0.5 ? "#000000b3" : "#fff";
        }
        return getColor(color ?? "#000000");
      },
    };
  },
});
</script>
