<template>
  <q-dialog
    persistent
    v-model="show_dialog"
    @dragstart.prevent
    @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-card-section class="q-ma-none q-pa-sm">
        <div class="row">
          <div class="col-auto text-h6">
            {{ $t("system setting") }}
          </div>
          <q-space />
          <div>
            <q-btn
              :loading="loading"
              flat
              round
              :disable="loading"
              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: 75vh; width: 60vw" class="scroll">
        <q-tabs
          v-model="tab"
          dense
          active-color="primary"
          indicator-color="primary"
          align="justify"
          narrow-indicator
          outside-arrows
          mobile-arrows
          class="bg-grey-2 text-teal"
          @update:model-value="onTabChanged"
        >
          <q-tab
            name="network"
            no-caps
            icon="img:new_icon/network_setting.png"
            :label="$t('network setting')"
            :disable="loading"
          />
          <q-tab
            v-if="
              $store.state.advanced_debug&&!$store.state.custom_defines.function_fusion ||
              /*!$store.state.custom_defines.is_custom_isv */ (!$store.state
                .custom_defines.function_output_board &&
                $store.state.isLedPlayer()) &&!$store.state.custom_defines.function_fusion
            "
            name="graphics"
            no-caps
            icon="img:new_icon/graphics_setting.png"
            :label="
              $store.state.custom_defines.function_output_board
                ? $t('graphics setting')
                : $t('output setting')
            "
            :disable="loading"
          />
          <q-tab
          v-if="$store.state.custom_defines.function_fusion &&
                $store.state.isLedPlayer()"
            name="graphics"
            no-caps
            icon="img:new_icon/graphics_setting.png"
            :label="
               $t('output setting')
            "
            :disable="loading"
          />

          <q-tab
            name="timing_task"
            no-caps
            icon="img:new_icon/timing_task.png"
            :label="$t('timing task')"
            :disable="loading"
          />
          <q-tab
            v-if="
              $store.state.advanced_debug ||
              (!$store.state.custom_defines.is_custom_isv &&
                $store.state.custom_defines.function_output_board &&
                $store.state.isLedPlayer())
            "
            name="output_board"
            no-caps
            icon="save"
            :label="$t('output board setting')"
            :disable="loading"
          />

          <q-tab
            name="other"
            no-caps
            icon="build"
            :label="$t('other setting')"
            :disable="loading"
          />
          <q-tab
            name="cloud_server"
            no-caps
            icon="cloud"
            :label="$t('cloud server')"
            :disable="loading"
          />
          <q-tab
            name="user"
            no-caps
            icon="account_circle"
            :label="$t('user')"
            :disable="loading"
          />
          <q-tab
            name="about"
            no-caps
            :icon="'info' /*'img:new_icon/about.png'*/"
            :label="$t('about')"
            :disable="loading"
            @click="++click_count"
          />
        </q-tabs>
        <q-separator />
        <q-tab-panels v-model="tab" animated>
          <q-tab-panel name="network" class="_panel">
            <q-card class="fit">
              <q-card-section>
                <q-form ref="network_form" @submit="applyNetwork">
                  <q-list>
                    <q-item class="q-pa-none">
                      <q-item-section avatar class="width_5_1">{{
                        $t("auto ip") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-select
                          v-model="auto_ip"
                          :options="[$t('enable'), $t('disable')]"
                          :loading="loading"
                          :disable="loading"
                          @update:model-value="autoIpChanged"
                        />
                      </q-item-section>
                    </q-item>
                    <q-item
                      class="q-pa-none"
                      v-if="true || auto_ip != $t('enable')"
                    >
                      <q-item-section avatar class="width_5_1">{{
                        $t("ip address") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="ip_address"
                          :loading="loading"
                          :disable="auto_ip == $t('enable') || loading"
                          maxlength="15"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                            (val) =>
                              isIpAddress(val) ||
                              $t('Please input vaild ip address'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item
                      class="q-pa-none"
                      v-if="true || auto_ip != $t('enable')"
                    >
                      <q-item-section avatar class="width_5_1">{{
                        $t("netmask") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          :loading="loading"
                          :disable="auto_ip == $t('enable') || loading"
                          v-model="netmask"
                          maxlength="15"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                            (val) =>
                              isMaskAddress(val) ||
                              $t('Please input vaild netmask address'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item
                      class="q-pa-none"
                      v-if="true || auto_ip != $t('enable')"
                    >
                      <q-item-section avatar class="width_5_1">{{
                        $t("gateway") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          :loading="loading"
                          :disable="auto_ip == $t('enable') || loading"
                          v-model="gateway"
                          maxlength="15"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                            (val) =>
                              isIpAddress(val) ||
                              $t('Please input vaild ip address'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item
                      class="q-pa-none"
                      v-if="false && auto_ip != $t('enable')"
                    >
                      <q-item-section avatar class="width_5_1">{{
                        $t("dns server") + "1:"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          :loading="loading"
                          :disable="auto_ip == $t('enable') || loading"
                          v-model="dns1"
                          maxlength="15"
                          :rules="[
                            (val) =>
                              isIpAddress(val) ||
                              val.length == 0 ||
                              $t('Please input vaild ip address'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item
                      class="q-pa-none"
                      v-if="false && auto_ip != $t('enable')"
                    >
                      <q-item-section avatar class="width_5_1">{{
                        $t("dns server") + "2:"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          :loading="loading"
                          :disable="auto_ip == $t('enable') || loading"
                          v-model="dns2"
                          maxlength="15"
                          :rules="[
                            (val) =>
                              isIpAddress(val) ||
                              val.length == 0 ||
                              $t('Please input vaild ip address'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item class="q-pa-none">
                      <q-item-section avatar class="width_5_1">{{
                        $t("mac address") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="mac_address"
                          :loading="loading"
                          :disable="loading"
                          maxlength="17"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                            (val) =>
                              isMacAddress(val) ||
                              $t('Please input vaild mac address') +
                                '  (XX:XX:XX:XX:XX:XX)',
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item class="q-pa-none">
                      <q-item-section> </q-item-section>
                      <q-item-section avatar>
                        <q-btn
                          @click="onAdvanceNetwork"
                          outline
                          color="primary"
                          no-caps
                          :label="$t('advanced')"
                        ></q-btn>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-form>
              </q-card-section>
            </q-card>
          </q-tab-panel>

          <q-tab-panel name="graphics" class="_panel">
            <q-card class="fit">
              <q-card-section>
                <q-form ref="graphics_form" @submit="applyGraphics">
                  <q-list>
                    <q-item v-if="false">
                      <q-item-section avatar class="width_5_2">{{
                        $t("brightness") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="brightness"
                          :loading="loading"
                          :disable="loading"
                          type="number"
                          :rules="[
                            (val) =>
                              (val != null &&
                                val != undefined &&
                                val.toString().length > 0) ||
                              $t('Please type something'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item v-if="false">
                      <q-item-section avatar class="width_5_2">{{
                        $t("contrast") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="contrast"
                          :loading="loading"
                          :disable="loading"
                          type="number"
                          :rules="[
                            (val) =>
                              (val != null &&
                                val != undefined &&
                                val.toString().length > 0) ||
                              $t('Please type something'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item v-if="false">
                      <q-item-section avatar class="width_5_2">{{
                        $t("hue") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="hue"
                          :loading="loading"
                          :disable="loading"
                          type="number"
                          :rules="[
                            (val) =>
                              (val != null &&
                                val != undefined &&
                                val.toString().length > 0) ||
                              $t('Please type something'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section avatar class="width_5_2_2">
                        {{ $t("current real resolution") }}:
                      </q-item-section>
                      <q-item-section>
                        {{ $store.state.device_screen_width }}X
                        {{ $store.state.device_screen_height }}@{{
                          $store.state.device_screen_refresh_rate
                        }}
                      </q-item-section>
                      <q-item-section avatar>
                        <q-btn flat round icon="help" color="green">
                          <q-tooltip>{{
                            $t(
                              "depending on the display device, the actual output resolution may differ from the target resolution"
                            )
                          }}</q-tooltip>
                        </q-btn>
                      </q-item-section>
                    </q-item>
                    <q-item
                      v-if="
                        $store.state.custom_defines.function_mirroring_output
                      "
                    >
                      <q-item-section avatar class="width_5_2_2"
                        >{{ $t("mirroring output") }}:</q-item-section
                      >
                      <q-item-section>
                        <q-checkbox
                          v-model="mirroring_output"
                          :loading="loading"
                          :disable="loading"
                          @update:model-value="tooltipMirroringTime"
                        />
                      </q-item-section>
                    </q-item>
                    <q-item
                      v-if="!$store.state.custom_defines.function_output_board ||$store.state.custom_defines.function_fusion"
                    >
                      <q-item-section avatar class="width_5_2_2"
                        >{{ $t("output type") }}:</q-item-section
                      >
                      <q-item-section>
                        <q-select
                          v-model="device_resolution_type"
                          :loading="loading"
                          :disable="loading"
                          :options="device_resolution_type_options"
                          emit-value
                          map-options
                        />
                      </q-item-section>
                      <q-item-section avatar>
                        <q-btn flat round icon="help" color="green">
                          <q-tooltip>
                            <p>
                              {{
                                $t(
                                  "EDID: list of resolutions recommended by the display device"
                                )
                              }}
                            </p>
                            <p>
                              {{
                                $t(
                                  "FOCEOUTPUT: force resolution output to be specified"
                                )
                              }}
                            </p>
                            <p>
                              {{
                                $t(
                                  "FOCEOUTPUT(CUSTOM): uses the specified timing output"
                                )
                              }}
                            </p>
                          </q-tooltip>
                        </q-btn>
                      </q-item-section>
                    </q-item>
                    <q-item
                      v-if="
                        !$store.state.custom_defines.function_output_board &&
                        device_resolution_type.toUpperCase() == 'EDID'||$store.state.custom_defines.function_fusion&&
                        device_resolution_type.toUpperCase() == 'EDID'
                      "
                    >
                      <q-item-section avatar class="width_5_2_2"
                        >{{ $t("target resolution") }}:</q-item-section
                      >
                      <q-item-section>
                        <q-select
                          v-model="device_resolution"
                          :loading="loading"
                          :disable="loading"
                          :options="device_resolution_options"
                        />
                      </q-item-section>
                    </q-item>
                    <q-item
                      v-if="
                        !$store.state.custom_defines.function_output_board &&
                        device_resolution_type.toUpperCase() == 'CVT'||$store.state.custom_defines.function_fusion&&
                        device_resolution_type.toUpperCase() == 'CVT'
                      "
                    >
                      <q-item-section avatar class="width_5_2_2"
                        >{{ $t("target resolution") }}:</q-item-section
                      >
                      <q-item-section>
                        <q-input
                          v-model="device_resolution"
                          :rules="[checkResolution]"
                          :placeholder="$t('for example: ') + '1920x1080@60'"
                          :hint="$t('for example: ') + '1920x1080@60'"
                        />
                      </q-item-section>
                    </q-item>
                    <q-item
                      v-if="
                        !$store.state.custom_defines.function_output_board &&
                        device_resolution_type.toUpperCase() == 'CUSTOM'||$store.state.custom_defines.function_fusion&&
                        device_resolution_type.toUpperCase() == 'CUSTOM'
                      "
                    >
                      <q-item-section avatar class="width_5_2_2"
                        >{{ $t("custom")
                        }}{{ $t("timing sequence") }}:</q-item-section
                      >
                      <q-item-section>
                        <q-input
                          v-model="device_resolution_timing"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                          ]"
                          :placeholder="
                            $t('for example: ') +
                            '1920x1080@60 ' +
                            $t('or') +
                            ' 173.00  1920 2048 2248 2576  1080 1083 1088 1120 -hsync +vsync'
                          "
                          :hint="
                            $t('for example: ') +
                            '1920x1080@60 ' +
                            $t('or') +
                            ' 173.00  1920 2048 2248 2576  1080 1083 1088 1120 -hsync +vsync'
                          "
                        />
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section avatar class="width_5_2_2">{{
                        $t("device rotate") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-select
                          v-model="device_rotate"
                          :loading="loading"
                          :disable="loading"
                          :options="device_rotate_options"
                          emit-value
                          map-options
                        />
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-form>
              </q-card-section>
            </q-card>
          </q-tab-panel>

          <q-tab-panel name="timing_task" class="_panel">
            <q-card class="fit">
              <q-card-section>
                <q-scroll-area class="full-width" style="height: 55.5vh">
                  <q-list>
                    <div v-for="(item, index) of timing_tasks" :key="index">
                      <q-item clickable>
                        <q-item-section avatar>
                          <q-chip color="teal" text-color="white" icon="alarm">
                            {{ getTaskTypeName(item.task_type) }}
                          </q-chip>
                        </q-item-section>
                        <q-item-section>
                          <q-item-label>{{ item.task_name }}</q-item-label>
                          <q-item-label caption lines="2"
                            ><span class="q-mr-md">{{ item.timing_time }}</span>
                            <span
                              class="q-mx-xs"
                              v-if="
                                item.timing_week_days & e_week_Days.EWeekMonday
                              "
                              >{{ $t("monday") }}</span
                            >
                            <span
                              class="q-mx-xs"
                              v-if="
                                item.timing_week_days & e_week_Days.EWeekTuesday
                              "
                              >{{ $t("tuesday") }}</span
                            >
                            <span
                              class="q-mx-xs"
                              v-if="
                                item.timing_week_days &
                                e_week_Days.EWeekWednesday
                              "
                              >{{ $t("wednesday") }}</span
                            >
                            <span
                              class="q-mx-xs"
                              v-if="
                                item.timing_week_days &
                                e_week_Days.EWeekThursday
                              "
                              >{{ $t("thursday") }}</span
                            >
                            <span
                              class="q-mx-xs"
                              v-if="
                                item.timing_week_days & e_week_Days.EWeekFriday
                              "
                              >{{ $t("friday") }}</span
                            >
                            <span
                              class="q-mx-xs"
                              v-if="
                                item.timing_week_days &
                                e_week_Days.EWeekSaturday
                              "
                              >{{ $t("saturday") }}</span
                            >
                            <span
                              class="q-mx-xs"
                              v-if="
                                item.timing_week_days & e_week_Days.EWeekSunday
                              "
                              >{{ $t("sunday") }}</span
                            >
                          </q-item-label>
                        </q-item-section>
                        <q-item-section avatar>
                          <q-btn
                            @click="deleteTimingTask(item)"
                            icon="delete"
                            color="red"
                            flat
                            round
                          >
                            <q-tooltip>
                              {{ $t("delete") }}{{ $t("timing task") }}
                            </q-tooltip>
                          </q-btn>
                        </q-item-section>
                      </q-item>
                    </div>
                  </q-list>
                </q-scroll-area>
              </q-card-section>
            </q-card>
          </q-tab-panel>

          <q-tab-panel name="other" class="_panel">
            <q-card class="fit">
              <q-scroll-area style="height: 55vh">
                <q-card-section>
                  <q-form ref="other_form" @submit="applyOther">
                    <q-list>
                      <q-item>
                        <q-item-section avatar class="width_5_3">{{
                          $t("output audio card") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="output_audio_card"
                            :loading="loading"
                            :disable="loading"
                            :options="output_audio_card_options"
                            emit-value
                            map-options
                          />
                        </q-item-section>
                      </q-item>
                      <q-item v-if="false">
                        <q-item-section avatar class="width_5_3">{{
                          $t("muted") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="system_muted"
                            :loading="loading"
                            :disable="loading"
                            :options="[$t('on'), $t('off')]"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item v-if="false && system_muted == $t('off')">
                        <q-item-section avatar class="width_5_3">{{
                          $t("volume") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="system_volume"
                            :loading="loading"
                            :disable="loading"
                            max="100"
                            min="0"
                            type="number"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                              (val) =>
                                (parseInt(val) >= 0 && parseInt(val) <= 100) ||
                                $t('number must between') +
                                  '0 ~ 100' +
                                  $t('CN_BERWEEN_SUFFIX'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_3">{{
                          $t("use ntp") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="use_ntp"
                            :loading="loading"
                            :disable="loading"
                            :options="[$t('enable'), $t('disable')]"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item v-if="use_ntp == $t('enable')">
                        <q-item-section avatar class="width_5_3">{{
                          $t("ntp server") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="ntp_server"
                            :loading="loading"
                            :disable="loading"
                            :rules="[
                              (val) =>
                                (val && val.length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item v-if="use_ntp == $t('enable')">
                        <q-item-section avatar class="width_5_3">{{
                          $t("ntp sync delay(S)") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="ntp_sync_delay"
                            :loading="loading"
                            :disable="loading"
                            type="number"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item v-if="use_ntp == $t('disable')">
                        <q-item-section avatar class="width_5_3">{{
                          $t("current datetime") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="current_date"
                            :loading="loading"
                            :disable="loading"
                            type="date"
                            :rules="[
                              (val) =>
                                (val && val.length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="current_time"
                            :loading="loading"
                            :disable="loading"
                            type="time"
                            :rules="[
                              (val) =>
                                (val && val.length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_3">{{
                          $t("time zone") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="time_zone"
                            :loading="loading"
                            :disable="loading"
                            :options="time_zone_options"
                          />
                        </q-item-section>
                      </q-item>
                    </q-list>
                  </q-form>
                </q-card-section>
              </q-scroll-area>
            </q-card>
          </q-tab-panel>

          <q-tab-panel
            name="output_board"
            class="_panel"
            v-if="
              $store.state.custom_defines.function_output_board ||
              $store.state.advanced_debug ||$store.state.custom_defines.function_fusion
            "
          >
            <q-card class="fit">
              <q-card-section>
                <q-scroll-area style="height: 55vh">
                  <q-form ref="output_board_form" @submit="applyOutputBoard">
                    <q-list>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("wall row") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="output_board_wall_row"
                            :loading="loading"
                            :disable="loading"
                            type="number"
                            max="5"
                            min="1"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                              (val) =>
                                (parseInt(val) >= 1 && parseInt(val) <= 5) ||
                                $t('number must between') +
                                  '1 ~ 5' +
                                  $t('CN_BERWEEN_SUFFIX'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("wall col") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="output_board_wall_col"
                            :loading="loading"
                            :disable="loading"
                            max="5"
                            min="1"
                            type="number"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                              (val) =>
                                (parseInt(val) >= 1 && parseInt(val) <= 5) ||
                                $t('number must between') +
                                  '1 ~ 5' +
                                  $t('CN_BERWEEN_SUFFIX'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("splicing") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="output_board_splicing"
                            :loading="loading"
                            :disable="loading"
                            :options="[$t('on'), $t('off')]"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("vertical blanking") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="output_board_vertical_blanking"
                            :loading="loading"
                            :disable="loading"
                            type="number"
                            max="255"
                            min="0"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                              (val) =>
                                (parseInt(val) >= 0 && parseInt(val) <= 255) ||
                                $t('number must between') +
                                  '0 ~ 255' +
                                  $t('CN_BERWEEN_SUFFIX'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("horizon blanking") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="output_board_horizon_blanking"
                            :loading="loading"
                            :disable="loading"
                            max="255"
                            min="0"
                            type="number"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                              (val) =>
                                (parseInt(val) >= 0 && parseInt(val) <= 255) ||
                                $t('number must between') +
                                  '0 ~ 255' +
                                  $t('CN_BERWEEN_SUFFIX'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("rotate") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="output_board_rotate"
                            :loading="loading"
                            :disable="loading"
                            :options="output_board_rotate_options"
                            emit-value
                            map-options
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("volume") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="output_board_volume"
                            :loading="loading"
                            :disable="loading"
                            type="number"
                            max="100"
                            min="0"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                              (val) =>
                                (parseInt(val) >= 0 && parseInt(val) <= 100) ||
                                $t('number must between') +
                                  '0 ~ 100' +
                                  $t('CN_BERWEEN_SUFFIX'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("mute") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="output_board_mute"
                            :loading="loading"
                            :disable="loading"
                            :options="[$t('on'), $t('off')]"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("output board resolution") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="output_board_resolution"
                            :loading="loading"
                            :disable="loading"
                            :options="output_board_resolution_options"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section>
                          <q-btn
                            class="q-mx-xl"
                            no-caps
                            :label="$t('restore output board')"
                            @click="restoreOutputBoard"
                          ></q-btn>
                        </q-item-section>
                      </q-item>
                    </q-list>
                  </q-form>
                </q-scroll-area>
              </q-card-section>
            </q-card>
          </q-tab-panel>

          <q-tab-panel name="cloud_server" class="_panel">
            <q-card class="fit">
              <q-card-section>
                <q-form ref="cloud_server_form" @submit="applyCloudServer">
                  <q-list>
                    <q-item class="q-pa-none">
                      <q-item-section avatar class="width_5_1">{{
                        $t("enable") + $t(" ") + $t("server") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-select
                          v-model="cloud_server_enable"
                          :options="[$t('enable'), $t('disable')]"
                          :loading="loading"
                          :disable="loading"
                          @update:model-value="autoIpChanged"
                        />
                      </q-item-section>
                    </q-item>
                    <q-item
                      class="q-pa-none"
                      :disable="cloud_server_enable != $t('enable')"
                    >
                      <q-item-section avatar class="width_5_1">{{
                        $t("server address") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="cloud_server_address"
                          :loading="loading"
                          :disable="
                            cloud_server_enable != $t('enable') || loading
                          "
                          maxlength="15"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                            (val) =>
                              isIpAddress(val) ||
                              $t('Please input vaild ip address'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item
                      class="q-pa-none"
                      :disable="cloud_server_enable != $t('enable')"
                    >
                      <q-item-section avatar class="width_5_1">{{
                        $t("device verify key") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          :loading="loading"
                          :disable="
                            cloud_server_enable != $t('enable') || loading
                          "
                          v-model="cloud_server_verify_key"
                          maxlength="6"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                            (val) =>
                              (val && val.length == 6) ||
                              $t('verify key length is 6'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item
                      class="q-pa-none"
                      :disable="cloud_server_enable != $t('enable')"
                    >
                      <q-item-section avatar class="width_5_1">{{
                        $t("use wss") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-select
                          v-model="cloud_server_use_wss"
                          :options="[$t('enable'), $t('disable')]"
                          :loading="loading"
                          :disable="
                            cloud_server_enable != $t('enable') || loading
                          "
                        />
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-form>
              </q-card-section>
            </q-card>
          </q-tab-panel>

          <q-tab-panel name="user" class="_panel">
            <q-card class="fit">
              <q-card-section>
                <q-form ref="user_form" @submit="applyUser()">
                  <q-list>
                    <q-item class="q-pa-none">
                      <q-item-section avatar class="width_5_1">{{
                        $t("user name") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="user_name"
                          :loading="loading"
                          :disable="loading"
                          maxlength="16"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item class="q-pa-none">
                      <q-item-section avatar class="width_5_1">{{
                        $t("old password") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="old_password"
                          :loading="loading"
                          :disable="loading"
                          :type="show_old_password ? 'text' : 'password'"
                          maxlength="16"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                          ]"
                          lazy-rules
                        >
                          <template v-if="old_password" v-slot:append>
                            <q-icon
                              :name="
                                show_old_password
                                  ? 'visibility'
                                  : 'visibility_off'
                              "
                              class="cursor-pointer"
                              @click="show_old_password = !show_old_password"
                            />
                            <q-icon
                              name="cancel"
                              @click.stop="old_password = ''"
                              class="cursor-pointer"
                            />
                          </template>
                        </q-input>
                      </q-item-section>
                    </q-item>
                    <q-item class="q-pa-none">
                      <q-item-section avatar class="width_5_1">{{
                        $t("new password") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="new_password"
                          :loading="loading"
                          :disable="loading"
                          :type="show_new_password ? 'text' : 'password'"
                          maxlength="16"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                          ]"
                          lazy-rules
                        >
                          <template v-if="new_password" v-slot:append>
                            <q-icon
                              :name="
                                show_new_password
                                  ? 'visibility'
                                  : 'visibility_off'
                              "
                              class="cursor-pointer"
                              @click="show_new_password = !show_new_password"
                            />
                            <q-icon
                              name="cancel"
                              @click.stop="new_password = ''"
                              class="cursor-pointer"
                            />
                          </template>
                        </q-input>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-form>
              </q-card-section>
            </q-card>
          </q-tab-panel>

          <q-tab-panel name="about" class="_panel">
            <q-card class="fit">
              <q-card-section>
                <q-form ref="about_form">
                  <q-list>
                    <q-item v-if="false">
                      <q-item-section avatar class="width_5_5_5">
                        {{ $t("product name") }}:
                      </q-item-section>
                      <q-item-section>
                        {{ $t("TV splicing box") }}
                      </q-item-section>
                    </q-item>
                    <q-item v-if="false">
                      <q-item-section avatar class="width_5_5_5">
                        {{ $t("copyright") }}:
                      </q-item-section>
                      <q-item-section>
                        {{ $t("guangdong chuangxian jishu") }} LTD.
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section avatar class="width_5_5_5"
                        >{{ $t("client version") }}:
                      </q-item-section>
                      <q-item-section>
                        {{ client_version.version }}
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section avatar class="width_5_5_5"
                        >{{ $t("server version") }}:
                      </q-item-section>
                      <q-item-section>
                        {{ server_version }}
                      </q-item-section>
                    </q-item>

                    <div
                      v-if="
                        click_count >= target_click_count ||
                        click_count >= target_click_count ||
                        $store.state.advanced_debug
                      "
                    >
                      <q-item>
                        <q-item-section avatar class="width_5_5_5"
                          >{{ $t("server commit hash") }}:
                        </q-item-section>
                        <q-item-section>
                          {{ server_commit_hash }}
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_5_5"
                          >{{ $t("server branch name") }}:
                        </q-item-section>
                        <q-item-section>
                          {{ server_branch_name }}
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_5_5"
                          >{{ $t("server build date") }}:
                        </q-item-section>
                        <q-item-section>
                          {{ server_build_date }}
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_5_5"
                          >{{ $t("kernel version") }}:
                        </q-item-section>
                        <q-item-section>
                          {{ kernel_version }}
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_5_5"
                          >{{ $t("rootfs version") }}:
                        </q-item-section>
                        <q-item-section>
                          {{ rootfs_version }}
                        </q-item-section>
                      </q-item>
                    </div>
                    <q-item class="q-mt-xl border">
                      <q-space />

                      <q-btn
                        @click="onRestore"
                        outline
                        :label="$t('system') + $t(' ') + $t('restore')"
                        color="primary"
                        class="q-mx-md"
                        no-caps
                      />
                      <q-space />
                    </q-item>
                    <q-item class="border" v-if="$store.state.isLedPlayer()">
                      <q-space />
                      <q-btn
                        @click="onCleanBrowserCache"
                        outline
                        :label="$t('clean browser cache')"
                        color="primary"
                        class="q-mx-md"
                        no-caps
                      />

                      <q-space />
                    </q-item>
                  </q-list>
                </q-form>
              </q-card-section>
            </q-card>
          </q-tab-panel>
        </q-tab-panels>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <q-btn
          :loading="loading"
          flat
          no-caps
          :label="tab == 'timing_task' ? $t('exit') : $t('revert and exit')"
          color="primary"
          v-close-popup
        />
        <q-btn
          v-if="tab != 'timing_task'"
          :loading="loading"
          flat
          no-caps
          :label="$t('revert')"
          color="primary"
          @click="refresh_all"
        />
        <q-btn
          v-if="tab != 'timing_task'"
          :loading="loading"
          flat
          no-caps
          :label="$t('apply')"
          color="primary"
          @click="apply"
        />
        <q-btn
          v-else
          :loading="loading"
          flat
          no-caps
          :label="$t('add timing task')"
          color="primary"
          @click="addTimingTask"
        />
        <q-btn
          v-if="false"
          :loading="loading"
          flat
          no-caps
          :label="$t('apply and exit')"
          color="primary"
          @click="applyAndExit"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>

  <timing-task-dialog ref="timing_task_dialog" />
  <systen-setting-advanced-network-dialog
    ref="system_setting_advanced_network_dialog"
  />
</template>

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

.width_5_2 {
  width: 10%;
}

.width_5_2_2 {
  width: 22%;
}

.width_5_3 {
  width: 20%;
}

.width_5_4 {
  width: 20%;
}

.width_5_5 {
  width: 30%;
}

.width_5_5_5 {
  width: 35%;
}

.width_5_6 {
  width: 40%;
}

._panel {
  padding: 3px;
  height: 60vh;
}
</style>

<script lang="ts">
import { defineComponent, ref, Ref, watch, computed } from "vue";
import { useStore } from "src/store";
import { useQuasar, SessionStorage, Cookies } from "quasar";

import TimingTaskDialog from "src/components/TimingTaskDialog.vue";

import { useI18n } from "vue-i18n";
import GlobalData from "src/common/GlobalData";
import ValidationUtil from "src/common/ValidationUtil";
import { date } from "quasar";
import { Protocol } from "src/entities/WSProtocol";
import TimingTaskEntity, {
  TimingTaskType,
} from "src/entities/TimingTaskEntity";
import { EWeekDays } from "src/entities/EWeekDays";

import SystenSettingAdvancedNetworkDialog from "src/components/SystenSettingAdvancedNetworkDialog.vue";
import { AdvancedIpAddressEntity } from "src/entities/AdvancedIpAddressEntity";

import version from "../../package.json";

import { Md5 } from "ts-md5";

const _time_zones = [
  "UTC-12(Central Pacific)",
  "UTC-11(Central Pacific)",
  "UTC-10(Honolulu of USA)",
  "UTC-9(Alaska of USA)",
  "UTC-8(California of USA)",
  "UTC-7(Phoenix of USA, Arizona of USA)",
  "UTC-6(Chicago of USA, Mexico)",
  "UTC-5(New York of USA)",
  "UTC-4(Republic of Chile)",
  "UTC-3(Brazil, Argentina)",
  "UTC-2(Mid Atlantic)",
  "UTC-1(West African continent)",
  "UTC(England, Portugal)",
  "UTC+1(Spain, France, Germany, ...)",
  "UTC+2(Turkey, South Africa, Rome, Egypt, ...)",
  "UTC+3(Moscow of Russia, Iran)",
  "UTC+4(The united Arab emirates)",
  "UTC+5(Pakistan, India)",
  "UTC+6(Bangladesh, Myanmar, Xinjiang Autonomous Region of China)",
  "UTC+7(Thailand, Malaysia, Singapore)",
  "UTC+8(Beijing of China, Philippines)",
  "UTC+9(Japan)",
  "UTC+10(Vladivostok of Russia, Guam, Australia)",
  "UTC+11(Solomon Islands)",
  "UTC+12(New Zealand)",
];
import vue3ResizeDrag from "src/third_lib/vue3-resize-drag/components/vue3-resize-drag/index.vue";

export default defineComponent({
  name: "ComponentSystemSettingDialog",
  components: {
    TimingTaskDialog,
    SystenSettingAdvancedNetworkDialog,
    vue3ResizeDrag,
  },

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

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

    const timing_task_dialog: Ref<any> = ref(null);
    const system_setting_advanced_network_dialog: Ref<any> = ref(null);

    const tab = ref("network");

    const auto_ip = ref($t.t("enable"));
    const ip_address = ref("127.0.0.1");
    const gateway = ref("127.0.0.1");
    const netmask = ref("127.0.0.1");
    const dns1 = ref();
    const dns2 = ref();
    const mac_address = ref("11:22:33:44:55:66");
    let ip_address_list: AdvancedIpAddressEntity[] = [];
    let host_name = "player";

    const brightness = ref(0);
    const contrast = ref(0);
    const hue = ref(0);

    const mirroring_output = ref(false);

    const device_resolution = ref("");
    const device_resolution_options: Ref<string[]> = ref([]);
    const device_rotate = ref(0);
    const device_rotate_options = ref([
      {
        label: "0°",
        value: 0,
      },
      {
        label: "90°",
        value: 1,
      },
      {
        label: "180°",
        value: 2,
      },
      {
        label: "270°",
        value: 3,
      },
      // {
      //   label: $t.t("horizontal flipped"),
      //   value: 4,
      // },
      // {
      //   label: $t.t("horizontal flipped") + "90°",
      //   value: 5,
      // },
      // {
      //   label: $t.t("horizontal flipped") + "180°",
      //   value: 6,
      // },
      // {
      //   label: $t.t("horizontal flipped") + "270°",
      //   value: 7,
      // },
    ]);
    const device_resolution_type = ref("EDID");
    const device_resolution_type_options = ref([
      { label: "EDID", value: "EDID" },
      { label: $t.t("force output") /*+ "(CVT)"*/, value: "CVT" },
      {
        label: $t.t("force output") + "(" + $t.t("custom") + ")",
        value: "CUSTOM",
      },
    ]);
    const device_resolution_timing = ref("");

    const output_board_resolution = ref("");
    const output_board_resolution_options = ref(["1", "2", "3"]);

    const system_muted = ref($t.t("off"));
    const system_volume = ref(100);
    const output_audio_card_options = ref([
      { label: $t.t("all"), value: "all" },
      { label: "3.5mm", value: "3.5mm" },
      { label: "HDMI1", value: "HDMI1" },
    ]);
    let old_output_audio_card = "";
    const output_audio_card = ref(output_audio_card_options.value[0].value);
    const use_ntp = ref($t.t("enable"));
    const ntp_server = ref("");
    const ntp_sync_delay = ref(180);
    const current_date = ref("");
    const current_time = ref("");
    const time_zone = ref("");
    const time_zone_options: Ref<string[]> = ref([]);
    for (const item of _time_zones) {
      time_zone_options.value.push($t.t(item));
    }

    const network_form: Ref<any> = ref(null);
    const other_form: Ref<any> = ref(null);
    const graphics_form: Ref<any> = ref(null);
    const output_board_form: Ref<any> = ref(null);
    const user_form: Ref<any> = ref(null);
    const cloud_server_form: Ref<any> = ref(null);

    const output_board_wall_row = ref(2);
    const output_board_wall_col = ref(2);
    const output_board_splicing = ref($t.t("on"));
    const output_board_vertical_blanking = ref(0);
    const output_board_horizon_blanking = ref(0);
    const output_board_rotate = ref(0);
    const output_board_rotate_options = ref([
      { label: "0°", value: 0 },
      { label: "180°", value: 1 },
    ]);
    const output_board_volume = ref(100);
    const output_board_mute = ref($t.t("on"));

    const timing_tasks: Ref<TimingTaskEntity[]> = ref([]);

    const click_count = ref(0);
    const target_click_count = ref(20);
    const client_version = ref(version);
    const server_version = ref("unknow");
    const server_commit_hash = ref("unknow");
    const server_build_date = ref("unknow");
    const server_branch_name = ref("unknow");
    const kernel_version = ref("unknow");
    const rootfs_version = ref("unknow");

    const cloud_server_enable = ref($t.t("enable"));
    const cloud_server_address = ref("");
    const cloud_server_verify_key = ref("");
    const cloud_server_use_wss = ref($t.t("enable"));

    const refresh_network = () => {
      const config = GlobalData.getInstance()?.applicationConfig;
      if (config) {
        auto_ip.value =
          config.auto_ip_address != "0" ? $t.t("enable") : $t.t("disable");
        gateway.value = config.gateway || "192.168.1.1";
        netmask.value = config.subnet_mask || "255.255.0.0";
        mac_address.value = config.mac_address || "5A:30:C2:5A:54:Bf";
        ip_address.value = $store.state.device_ip_address || "192.168.1.168";
        dns1.value = config.dns1 || "";
        dns2.value = config.dns2 || "";
        ip_address_list = config.ip_list || [];
      }
    };

    const refresh_graphics = () => {
      const config = GlobalData.getInstance()?.applicationConfig;
      if (config) {
        setTimeout(async () => {
          const support_resolutions = await GlobalData.getInstance()
            .getCurrentClient()
            ?.getSupportResolutions();
          if (support_resolutions) {
            device_resolution_options.value = [];
            for (const item of support_resolutions.device_edid_support_resolutions) {
              device_resolution_options.value.push(item);
            }
            device_resolution_type.value =
              support_resolutions.target_resolution.type;
            device_resolution.value =
              support_resolutions.target_resolution.name;
            device_resolution_timing.value =
              support_resolutions.target_resolution.timing;
          }

          mirroring_output.value = config.device_hdmi_output_count == 2;
        }, 1);

        brightness.value = parseInt(config.graphics_brightness.toString());
        contrast.value = parseInt(config.graphics_contrast.toString());
        hue.value = parseInt(config.graphics_hue.toString());

        device_rotate.value = parseInt(config.device_rotate.toString());
      }
    };

    let backup_timezine = time_zone_options.value[0];
    const refresh_other = () => {
      const config = GlobalData.getInstance()?.applicationConfig;
      if (config) {
        output_audio_card.value = config.output_audio_card;
        old_output_audio_card = output_audio_card.value;
        let muted = parseInt(config.system_muted.toString());
        if (isNaN(muted)) {
          muted = 0;
        }
        system_muted.value = muted ? $t.t("on") : $t.t("off");
        system_volume.value = config.system_volume;

        use_ntp.value =
          config.use_ntp != "0" ? $t.t("enable") : $t.t("disable");
        ntp_server.value = config.ntp_server;
        ntp_sync_delay.value = parseInt(config.ntp_sync_delay);
        if (isNaN(ntp_sync_delay.value)) {
          ntp_sync_delay.value = 180;
        }
        try {
          time_zone.value = time_zone_options.value[config.time_zone];
        } catch (e) {
          time_zone.value = time_zone_options.value[0];
        }
        backup_timezine = time_zone.value;

        const timeStamp = Date.now();
        current_date.value = date.formatDate(timeStamp, "YYYY-MM-DD");
        current_time.value = date.formatDate(timeStamp, "HH:mm:ss");
      }
    };
    const refresh_output_board = async () => {
      const settings = await GlobalData.getInstance()
        .getCurrentClient()
        ?.getOutputBoardSetting();
      if (settings) {
        output_board_wall_row.value = settings.wall_row;
        output_board_wall_col.value = settings.wall_col;
        output_board_splicing.value = settings.splicing
          ? $t.t("on")
          : $t.t("off");
        output_board_vertical_blanking.value = settings.vertical_blanking;
        output_board_horizon_blanking.value = settings.horizon_blanking;
        output_board_rotate.value = settings.rotate;
        output_board_volume.value = settings.volume;
        output_board_mute.value = settings.mute ? $t.t("on") : $t.t("off");

        {
          output_board_resolution_options.value = [];
          for (const item of Object.keys(
            settings.output_board_support_resolutions
          ).sort()) {
            output_board_resolution_options.value.push(
              (settings.output_board_support_resolutions as any)[item]
            );
          }

          const val = output_board_resolution_options.value.find(
            (element) =>
              element && element == settings.current_output_board_resolution
          );
          output_board_resolution.value =
            val ?? output_board_resolution_options.value[0];
        }
      }
    };

    const refresh_cloud_server = () => {
      const config = GlobalData.getInstance()?.applicationConfig;
      if (config) {
        cloud_server_enable.value = parseInt(config.cloud_server_enable)
          ? $t.t("enable")
          : $t.t("disable");
        cloud_server_address.value =
          config.cloud_server_address || "192.168.1.1";
        cloud_server_verify_key.value =
          config.cloud_server_verify_key || "123456";
        cloud_server_use_wss.value = parseInt(config.cloud_server_use_wss)
          ? $t.t("enable")
          : $t.t("disable");
      }
    };

    const refresh_all = () => {
      refresh_network();
      refresh_graphics();
      refresh_other();
      refresh_output_board();
      refresh_cloud_server();
    };

    const wait_for = async (delay_ms: number) => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(null);
        }, delay_ms);
      });
    };

    const applyNetwork = async () => {
      loading.value = true;
      const request = new Protocol.SetSystemNetworkRequestEntity();
      request.auto_ip = auto_ip.value == $t.t("enable");
      request.ip_address = ip_address.value;
      request.gateway = gateway.value;
      request.net_mask = netmask.value;
      request.mac_address = mac_address.value;
      request.dns1 = dns1.value ?? "";
      request.dns2 = dns2.value ?? "";
      request.ip_address_list = ip_address_list ?? [];
      request.host_name = host_name ?? "";

      let success = false;
      try {
        await GlobalData.getInstance()
          .getCurrentClient()
          ?.setSystemNetwork(request);
        setTimeout(() => {
          if (request.ip_address != $store.state.device_ip_address) {
            setTimeout(() => {
              SessionStorage.clear();
              if (
                window.location.hostname.toLowerCase() == "192.168.1.1" ||
                window.location.hostname.toLowerCase() == "localhost"
              ) {
                window.location.reload();
              } else {
                window.location.hostname = request.ip_address;
              }
            }, 2500);
          }
        }, 1000 * 10);
        success = true;
      } catch {}
      $q.notify({
        color: success ? "positive" : "negative",
        icon: success ? "done" : "warning",
        message:
          $t.t("set system network") +
          (success ? $t.t("success") : $t.t("fail")) +
          "!",
        position: "top",
        timeout: 2500,
      });
      loading.value = false;
    };

    const applyGraphics = async () => {
      const _apply_graphics = async () => {
        loading.value = true;
        const request = new Protocol.SetSystemGraphicsRequestEntity();
        request.brightness = parseInt(brightness.value.toString());
        request.contrast = parseInt(contrast.value.toString());
        request.hue = parseInt(hue.value.toString());
        request.target_resolution_type = device_resolution_type.value;
        request.device_resolution_name = device_resolution.value;
        request.target_resolution_timing = device_resolution_timing.value;
        request.rotate = parseInt(device_rotate.value.toString());
        request.hdmi_output_count = mirroring_output.value ? 2 : 1;
        if (!$store.state.custom_defines.function_mirroring_output) {
          request.hdmi_output_count = 1;
        }

        let success = false;
        try {
          const response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.setSystemGraphics(request);
          if (response && response.success) {
            success = true;
          }
        } catch {}
        $q.notify({
          color: success ? "positive" : "negative",
          icon: success ? "done" : "warning",
          message:
            $t.t("set system graphics") +
            (success ? $t.t("success") : $t.t("fail")) +
            "!",
          position: "top",
          timeout: 2500,
        });
        loading.value = false;
      };
      if (device_resolution_type.value?.toUpperCase() == "CUSTOM") {
        $q.dialog({
          title: $t.t("use custom output"),
          message:
            $t.t("are you sure to use the timing force output") +
            "?" +
            "\n" +
            $t.t("the screen output may be abnormal") +
            "!",
          ok: {
            label: $t.t("ok"),
            noCaps: true,
            flat: true,
          },
          cancel: {
            label: $t.t("cancel"),
            noCaps: true,
            flat: true,
          },
          persistent: true,
        }).onOk(_apply_graphics);
      } else {
        _apply_graphics();
      }
    };

    const applyOther = async () => {
      loading.value = true;

      const request = new Protocol.SetSystemOtherRequestEntity();

      request.system_volume = parseInt(system_volume.value.toString());
      request.system_muted = system_muted.value == $t.t("on");
      request.output_audio_card = output_audio_card.value;
      request.use_ntp = use_ntp.value == $t.t("enable");
      request.ntp_sync_delay = parseInt(ntp_sync_delay.value.toString());
      request.ntp_server = ntp_server.value;
      request.time_zone = time_zone_options.value.findIndex(
        (element) => element && element == time_zone.value
      );
      if (request.time_zone < 0) {
        request.time_zone =
          GlobalData.getInstance().applicationConfig?.time_zone ?? 21;
      }
      request.datetime = current_date.value + " " + current_time.value;

      let success = false;
      try {
        await GlobalData.getInstance()
          .getCurrentClient()
          ?.setSystemOther(request);
        success = true;
        if (old_output_audio_card != request.output_audio_card) {
          try {
            $q.dialog({
              title: $t.t("Confirm"),
              message:
                $t.t(
                  "the sound card takes effect only after it is restarted. Restart the system"
                ) + "?",
              ok: {
                label: $t.t("ok"),
                noCaps: true,
                flat: true,
              },
              cancel: {
                label: $t.t("cancel"),
                noCaps: true,
                flat: true,
              },
              persistent: true,
            }).onOk(async () => {
              await GlobalData.getInstance()
                .getCurrentClient()
                ?.restartDevice(1000 * 3);
              $q.notify({
                color: "positive",
                icon: "done",
                message:
                  $t.t("restart command send") +
                  $t.t("success") +
                  "!" +
                  $t.t("the system will reboot after the setup is complete") +
                  "!",
                position: "top",
                timeout: 2500,
              });
            });
          } catch {}
        } else if (backup_timezine != time_zone.value) {
          try {
            $q.dialog({
              title: $t.t("Confirm"),
              message:
                $t.t(
                  "the time zone takes effect only after it is restarted. Restart the system"
                ) + "?",
              ok: {
                label: $t.t("ok"),
                noCaps: true,
                flat: true,
              },
              cancel: {
                label: $t.t("cancel"),
                noCaps: true,
                flat: true,
              },
              persistent: true,
            }).onOk(async () => {
              await GlobalData.getInstance()
                .getCurrentClient()
                ?.restartDevice(1000 * 3);
              $q.notify({
                color: "positive",
                icon: "done",
                message:
                  $t.t("restart command send") +
                  $t.t("success") +
                  "!" +
                  $t.t("the system will reboot after the setup is complete") +
                  "!",
                position: "top",
                timeout: 2500,
              });
            });
            backup_timezine = time_zone.value;
          } catch {}
        }
      } catch {}
      $q.notify({
        color: success ? "positive" : "negative",
        icon: success ? "done" : "warning",
        message:
          $t.t("set system other") +
          (success ? $t.t("success") : $t.t("fail")) +
          "!",
        position: "top",
        timeout: 2500,
      });
      old_output_audio_card = request.output_audio_card;
      loading.value = false;
    };

    const applyOutputBoard = async () => {
      loading.value = true;
      const request = new Protocol.SetOutputBoardSettingRequestEntity();
      const response = await GlobalData.getInstance()
        .getCurrentClient()
        ?.getMagicWallConfig();
      request.wall_col = parseInt(output_board_wall_col.value.toString());
      request.wall_row = parseInt(output_board_wall_row.value.toString());
      request.splicing = output_board_splicing.value == $t.t("on");
      request.vertical_blanking = parseInt(
        output_board_vertical_blanking.value.toString()
      );
      request.horizon_blanking = parseInt(
        output_board_horizon_blanking.value.toString()
      );
      request.rotate = parseInt(output_board_rotate.value.toString());
      request.volume = parseInt(output_board_volume.value.toString());
      request.mute = output_board_mute.value == $t.t("on");
      request.output_board_resolution = output_board_resolution.value;
      let success = false;
      try {
        await GlobalData.getInstance()
          .getCurrentClient()
          ?.setOutputBoardSetting(request);
        success = true;
        if (
          $store.state.custom_defines.function_magic_wall &&
          response &&
          success
        ) {
          const output_length =
            parseInt(output_board_wall_col.value.toString()) *
            parseInt(output_board_wall_row.value.toString());
          if (output_length != response.config.col * response.config.row) {
            $store.commit("setShowMonitorList", []);
          }
        }
      } catch {}
      $q.notify({
        color: success ? "positive" : "negative",
        icon: success ? "done" : "warning",
        message:
          $t.t("set output board") +
          (success ? $t.t("success") : $t.t("fail")) +
          "!",
        position: "top",
        timeout: 2500,
      });
      loading.value = false;
    };

    const apply = () => {
      switch (tab.value) {
        case "network":
          network_form.value.submit();
          break;
        case "graphics":
          graphics_form.value.submit();
          break;
        case "other":
          other_form.value.submit();

          break;
        case "output_board":
          output_board_form.value.submit();
          break;
        case "cloud_server":
          cloud_server_form.value.submit();
          break;
        case "user":
          user_form.value.submit();
          break;
      }
    };

    const applyCloudServer = async () => {
      loading.value = true;

      let success = false;

      try {
        await GlobalData.getInstance()
          .getCurrentClient()
          ?.setCloudServerSetting(
            cloud_server_address.value,
            cloud_server_verify_key.value,
            cloud_server_use_wss.value == $t.t("enable"),
            cloud_server_enable.value == $t.t("enable")
          );

        success = true;
      } catch {}

      $q.notify({
        color: success ? "positive" : "negative",
        icon: success ? "done" : "warning",
        message:
          $t.t("set cloud server setting") +
          $t.t(" ") +
          (success ? $t.t("success") : $t.t("fail")) +
          "!",
        position: "top",
        timeout: 2500,
      });
      loading.value = false;
    };

    const applyUser = async () => {
      loading.value = true;
      const request = new Protocol.SetOutputBoardSettingRequestEntity();
      request.wall_col = parseInt(output_board_wall_col.value.toString());
      request.wall_row = parseInt(output_board_wall_row.value.toString());
      request.splicing = output_board_splicing.value == $t.t("on");
      request.vertical_blanking = parseInt(
        output_board_vertical_blanking.value.toString()
      );
      request.horizon_blanking = parseInt(
        output_board_horizon_blanking.value.toString()
      );
      request.rotate = parseInt(output_board_rotate.value.toString());
      request.volume = parseInt(output_board_volume.value.toString());
      request.mute = output_board_mute.value == $t.t("on");
      request.output_board_resolution = output_board_resolution.value;

      let success = false;
      try {
        const appconfig = GlobalData.getInstance().applicationConfig;
        if (
          user_name.value.trim().length > 0 &&
          old_password.value.trim().length > 0 &&
          new_password.value.trim().length > 0 &&
          appconfig
        ) {
          const old_pwd = Md5.hashStr(old_password.value.trim()).toLowerCase();
          const new_pwd = Md5.hashStr(new_password.value.trim()).toLowerCase();
          if (
            appconfig.password &&
            appconfig.password.toLowerCase() == old_pwd
          ) {
            if (user_name.value.trim() != appconfig.user_name) {
              GlobalData.getInstance()
                .getCurrentClient()
                ?.setUserName(user_name.value.trim());
            }

            if (new_pwd != old_pwd) {
              GlobalData.getInstance().getCurrentClient()?.setPassword(new_pwd);
              Cookies.remove("auto_login");
              SessionStorage.clear();
              try {
                $q.fullscreen.exit();
              } catch {}
              window.location.reload();
            }
            success = true;
          } else {
            $q.notify({
              color: "negative",
              icon: "warning",
              message:
                $t.t("edit user or password") +
                $t.t(" ") +
                $t.t("fail") +
                ", " +
                $t.t("old password error") +
                "!",
              position: "top",
              timeout: 2500,
            });
            loading.value = false;
            return;
          }
        }
      } catch {}
      $q.notify({
        color: success ? "positive" : "negative",
        icon: success ? "done" : "warning",
        message:
          $t.t("edit user or password") +
          (success ? $t.t("success") : $t.t("fail")) +
          "!",
        position: "top",
        timeout: 2500,
      });
      loading.value = false;
    };

    const restoreOutputBoard = () => {
      GlobalData.getInstance().getCurrentClient()?.restoreOutputBoard();
    };

    const refreshTimingTasks = async () => {
      try {
        const response = await GlobalData.getInstance()
          .getCurrentClient()
          ?.getTimingTasks();
        if (response) {
          timing_tasks.value = response.tasks;
        }
      } catch (e) {
        console.error(e);
      }
    };

    const user_name = ref(
      GlobalData.getInstance().applicationConfig?.user_name ?? "admin"
    );
    const old_password = ref("");
    const show_old_password = ref(false);
    const new_password = ref("");
    const show_new_password = ref(false);

    watch(
      () => tab.value,
      (newV, oldV) => {
        if (newV == "user") {
          user_name.value =
            GlobalData.getInstance().applicationConfig?.user_name ?? "admin";
          old_password.value = "";
          new_password.value = "";
          show_old_password.value = false;
          show_new_password.value = false;
        }
        if (newV != "about") {
          click_count.value = 0;
        }
      }
    );
    return {
      show_dialog,
      e_week_Days: ref(EWeekDays),
      timing_task_dialog,
      system_setting_advanced_network_dialog,
      timing_tasks,
      loading,
      tab,
      auto_ip,
      ip_address,
      gateway,
      netmask,
      dns1,
      dns2,
      mac_address,
      brightness,
      contrast,
      hue,
      device_rotate,
      device_rotate_options,
      device_resolution,
      device_resolution_options,
      device_resolution_type,
      device_resolution_type_options,
      device_resolution_timing,
      output_board_resolution,
      output_board_resolution_options,
      output_audio_card,
      output_audio_card_options,
      system_muted,
      system_volume,
      use_ntp,
      ntp_server,
      ntp_sync_delay,
      current_date,
      current_time,
      time_zone,
      time_zone_options,
      output_board_mute,
      output_board_volume,
      output_board_rotate_options,
      output_board_rotate,
      output_board_horizon_blanking,
      output_board_vertical_blanking,
      output_board_splicing,
      output_board_wall_col,
      output_board_wall_row,
      network_form,
      other_form,
      graphics_form,
      output_board_form,
      cloud_server_form,
      user_form,
      mirroring_output,
      click_count,
      target_click_count,
      client_version,
      server_version,
      server_commit_hash,
      server_build_date,
      server_branch_name,
      kernel_version,
      rootfs_version,
      cloud_server_enable,
      cloud_server_address,
      cloud_server_verify_key,
      cloud_server_use_wss,
      user_name,
      old_password,
      new_password,
      show_new_password,
      show_old_password,
      refresh_all,
      apply,
      restoreOutputBoard,
      applyNetwork,
      applyGraphics,
      applyOther,
      applyOutputBoard,
      applyCloudServer,
      applyUser,
      loga(a: any) {
        console.log(a);
      },
      showDialog() {
        show_dialog.value = true;

        GlobalData.getInstance()
          .getCurrentClient()
          ?.getSystemNetworkInfo()
          .then((response) => {
            if (response) {
              host_name = (response.host_name ?? "player").trim();
            }
          });

        refresh_all();

        try {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.getBuildInfo()
            ?.then((build_info) => {
              if (build_info) {
                server_version.value = build_info.version;
                server_commit_hash.value = build_info.commit_hash;
                server_build_date.value = build_info.build_date;
                server_branch_name.value = build_info.branch_name;
                kernel_version.value = build_info.kernel_version;
                rootfs_version.value = build_info.rootfs_version;
              }
            });
          // console.log(build_info);
        } catch {}
      },
      resetData() {
        click_count.value = 0;
        loading.value = false;
        tab.value = "network";
      },
      async applyAndExit() {
        await apply();
        show_dialog.value = false;
      },
      getTaskTypeName(index: number) {
        let result = $t.t("unknow");
        switch (index) {
          case TimingTaskType.TaskPowerOn:
            result = $t.t("power on");
            break;
          case TimingTaskType.TaskPowerOff:
            result = $t.t("power off");
            break;
        }
        return result;
      },
      async addTimingTask() {
        if (timing_task_dialog.value) {
          let success = false;
          try {
            const result = await timing_task_dialog.value.showDialogAsync();
            if (result) {
              const request_param = new TimingTaskEntity();
              for (const rk of Object.keys(result)) {
                if ((<any>request_param)[rk] !== undefined) {
                  (<any>request_param)[rk] = result[rk];
                }
              }
              const response = await GlobalData.getInstance()
                .getCurrentClient()
                ?.addTimingTask(request_param);
              if (response && response.success) {
                request_param.uuid = response.uuid;
                timing_tasks.value.push(request_param);
                success = true;
              }
            } else {
              // 对话框点击了确定但是返回的数据是空的
              console.error("addTimingTask result is null!");
              return;
            }
          } catch {
            // 对话框点击了取消
            return;
          }

          $q.notify({
            color: success ? "positive" : "negative",
            icon: success ? "done" : "warning",
            message:
              $t.t("add") +
              $t.t("timing task") +
              (success ? $t.t("success") : $t.t("fail")) +
              "!",
            position: "top",
            timeout: 2500,
          });
        }
      },
      async deleteTimingTask(item: TimingTaskEntity) {
        let success = false;
        if (item) {
          try {
            const response = await GlobalData.getInstance()
              .getCurrentClient()
              ?.deleteTimingTask(item.uuid);
            if (response && response.success) {
              const index = timing_tasks.value.findIndex(
                (element) => element && element.uuid == item.uuid
              );
              if (index != -1) {
                timing_tasks.value.splice(index, 1);
              }
              success = true;
            }
          } catch (e) {
            console.error(e);
          }
        }
        $q.notify({
          color: success ? "positive" : "negative",
          icon: success ? "done" : "warning",
          message:
            $t.t("delete") +
            $t.t("timing task") +
            (success ? $t.t("success") : $t.t("fail")) +
            "!",
          position: "top",
          timeout: 2500,
        });
      },
      onTabChanged(value: string) {
        switch (value) {
          case "timing_task":
            refreshTimingTasks();
            break;
        }
      },
      async autoIpChanged(value: string) {
        const enabled = value == $t.t("enable");
        let flag = false;
        if (enabled) {
          try {
            const info = await GlobalData.getInstance()
              .getCurrentClient()
              ?.getSystemNetworkInfo();
            if (info) {
              gateway.value = info.gateway || "192.168.1.1";
              netmask.value = info.net_mask || "255.255.0.0";
              dns1.value =
                GlobalData.getInstance()?.applicationConfig?.dns1 || "";
              dns2.value =
                GlobalData.getInstance()?.applicationConfig?.dns2 || "";
              mac_address.value = info.mac_address || "5A:30:C2:5A:54:Bf";
              ip_address.value = info.ip_address || "192.168.1.168";
              flag = true;
            }
          } catch {}
        }

        if (!flag) {
          const config = GlobalData.getInstance()?.applicationConfig;
          if (config) {
            gateway.value = config.gateway;
            netmask.value = config.subnet_mask;
            mac_address.value = config.mac_address;
            ip_address.value = config.ip_address;
          }
        }
      },
      tooltipMirroringTime(value: boolean) {
        if (value) {
          $q.dialog({
            title: $t.t("info"),
            message: $t.t(
              "after mirroring output is enabled, the second output may need to wait 1 or 2 minutes before the screen appears!"
            ),
            persistent: true,
            ok: {
              label: $t.t("i have known"),
              noCaps: true,
              flat: true,
            },
          });
        }
      },
      isIpAddress(str: string) {
        return ValidationUtil.isIpAddress(str);
      },
      isMacAddress(str: string) {
        return ValidationUtil.isMacAddress(str);
      },
      isMaskAddress(str: string) {
        return ValidationUtil.isMaskAddress(str);
      },
      checkResolution(str: string) {
        return (
          ValidationUtil.isResolution(str) ||
          $t.t("the resolution format is incorrect,") +
            $t.t("for example: ") +
            "1920x1080@60"
        );
      },
      async onAdvanceNetwork() {
        const result =
          await system_setting_advanced_network_dialog.value.showDialogAsync(
            GlobalData.getInstance()?.applicationConfig?.ip_list
          );
        if (result) {
          if (Array.isArray(result.ip_address_list)) {
            ip_address_list = result.ip_address_list;
          } else {
            ip_address_list =
              GlobalData.getInstance()?.applicationConfig?.ip_list || [];
          }
          if (typeof result.host_name == "string") {
            host_name = result.host_name.trim();
          } else {
            host_name = "player";
          }
        }
      },
      onRestore() {
        $q.dialog({
          title: $t.t("restore"),
          message: $t.t(
            "are you sure to restore factory settings? the configuration parameters, signal source, mode, and plan will be deleted!"
          ),
          options: {
            type: "checkbox",
            model: [],
            // inline: true
            items: [
              {
                label: $t.t("delete upload files ."),
                value: "delete_upload",
                color: "secondary",
              },
            ],
          },
          ok: {
            label: $t.t("ok"),
            noCaps: true,
            flat: true,
          },
          cancel: {
            label: $t.t("cancel"),
            noCaps: true,
            flat: true,
          },
          persistent: true,
        }).onOk((data) => {
          if (Array.isArray(data)) {
            const delete_upload = data.length != 0;
            GlobalData.getInstance()
              .getCurrentClient()
              ?.restoreDevice(delete_upload);
            $q.notify({
              color: "positive",
              icon: "done",
              message: $t.t("send restore command success!"),
              position: "top",
              timeout: 1500,
            });
          }
        });
      },
      onCleanBrowserCache() {
        GlobalData.getInstance().getCurrentClient()?.cleanBrowserCache();
        $q.notify({
          color: "positive",
          icon: "done",
          message: $t.t("clean browser cache command send success") + " !",
          position: "top",
          timeout: 1000 * 2,
        });
      },
    };
  },
});
</script>
