<template>
  <q-dialog
    persistent
    v-model="show_dialog"
    @before-hide="resetData"
    @keydown="
      (evt) => {
        if (!loading && evt.keyCode == 27) {
          show_dialog = false;
        }
        if (
          evt.keyCode == 37 &&
          (current_index != -1 || multiple_select.length > 1)
        ) {
          //左
          sub_x();
        }
        if (
          evt.keyCode == 38 &&
          (current_index != -1 || multiple_select.length > 1)
        ) {
          //上
          sub_y();
        }
        if (
          evt.keyCode == 39 &&
          (current_index != -1 || multiple_select.length > 1)
        ) {
          //右
          add_x();
        }
        if (
          evt.keyCode == 40 &&
          (current_index != -1 || multiple_select.length > 1)
        ) {
          //下
          add_y();
        }
        if (evt.keyCode == 17) {
          //ctrl
          multiple = true;
        }
      }
    "
    @keyup="
      (evt) => {
        if (evt.keyCode == 17) {
          //ctrl
          multiple = false;
        }
      }
    "
  >
    <q-card class="overflow-hidden" style="overflow-y: scroll; max-width: 60vw">
      <q-form @submit="onSubmit" >
        <q-card-section class="q-ma-none q-pa-sm">
          <div class="row">
            <div class="col-auto text-h6">
              {{ $t("magic wall") }}
            </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: 80vh; width: 55vw" class="scroll">
          <q-card class="my-card" flat bordered>
            <q-card-section horizontal>
              <q-card-section class="col-3" style="">
                <div class="text-h5">{{ $t("angle") }}</div>
                <q-separator />
                <br />
                <div class="row no-wrap items-center">
                  <q-item>
                    <q-item-section avatar>
                      <span class="q-mb-md" style="font-size: 1rem">
                        angle:</span
                      >
                    </q-item-section>
                    <q-item-section>
                      <q-input
                        v-if="current_index > -1"
                        type="number"
                        min="0"
                        v-model="test_monitor_wall[current_index].angle"
                        oninput="if(value<0)value=0;if(value>360)value=360;"
                        hint=""
                        @update:model-value="changeAngle()"
                        :max="max_angle()"
                      >
                        <template v-slot:append>
                          <span class="input_append">°</span>
                        </template>
                      </q-input>
                      <q-input
                        v-else
                        type="number"
                        min="0"
                        :model-value="0"
                        :disable="true"
                        hint=""
                      >
                        <template v-slot:append>
                          <span class="input_append">°</span>
                        </template>
                      </q-input>
                    </q-item-section>
                  </q-item>
                </div>
                <br />
                <div class="text-h5">{{ $t("physical central location") }}</div>
                <q-separator />
                <br />
                <div class="row no-wrap items-center">
                  <q-item>
                    <q-item-section avatar>
                      <span class="q-mb-md">X:</span>
                    </q-item-section>
                    <q-item-section>
                      <q-input
                        v-if="current_index > -1"
                        type="number"
                        :min="min_x()"
                        v-model="test_monitor_wall[current_index].centerx"
                        @update:model-value="center_x()"
                        :max="max_x()"
                        :rules="[
                          (val) =>
                            (val != null &&
                              val != undefined &&
                              val.toString().length > 0) ||
                            $t('Please type something'),
                          (val) =>
                            parseInt(val) >= 0 ||
                            $t('the number must be greater than 0'),
                        ]"
                        lazy-rules
                        hint=""
                      >
                        <template v-slot:append>
                          <span class="input_append text-h6">px</span>
                        </template>
                      </q-input>
                      <q-input
                        v-else
                        type="number"
                        min="0"
                        :model-value="0"
                        :disable="true"
                        hint=""
                      >
                        <template v-slot:append>
                          <span class="input_append text-h6">px</span>
                        </template>
                      </q-input>
                    </q-item-section>
                  </q-item>
                </div>
                <br />

                <div class="row">
                  <q-item>
                    <q-item-section avatar>
                      <span class="q-mb-md">Y:</span>
                    </q-item-section>
                    <q-item-section>
                      <q-input
                        v-if="current_index > -1"
                        :hint="''"
                        type="number"
                        :min="min_y()"
                        :max="max_y()"
                        v-model="test_monitor_wall[current_index].centery"
                        @update:model-value="center_y()"
                        :rules="[
                          (val) =>
                            (val != null &&
                              val != undefined &&
                              val.toString().length > 0) ||
                            $t('Please type something'),
                          (val) =>
                            parseInt(val) > 0 ||
                            $t('the number must be greater than 0'),
                        ]"
                        lazy-rules
                      >
                        <template v-slot:append>
                          <span class="input_append text-h6">px</span>
                        </template>
                      </q-input>
                      <q-input
                        v-else
                        type="number"
                        min="0"
                        :model-value="0"
                        :disable="true"
                        hint=""
                      >
                        <template v-slot:append>
                          <span class="input_append text-h6">px</span>
                        </template>
                      </q-input>
                    </q-item-section>
                  </q-item>
                </div>
              </q-card-section>
              <q-separator vertical></q-separator>

              <q-card-section
                @dragenter="onDragEnter"
                @dragleave="onDragLeave"
                @dragover="onDragOver"
                @drop="onDrop"
                style="max-height: 80vh; width: 55vw; position: relative"
              >
                <div class="text-h6 row">
                  <div for="" class="col-2">{{ $t("resize") }}</div>
                  <q-slider
                    class="col"
                    style="font-size: 0.7rem"
                    v-model="percenter"
                    @update:model-value="changePercenter()"
                    label
                    :label-value="percenter"
                    markers
                    switch-marker-labels-side
                    label-always
                    :min="0.1"
                    :max="2"
                    :step="0.1"
                  />
                </div>
                <div
                  style="
                    position: absolute;
                    height: 20.7vw;
                    width: 36.8vw;
                    text-align: center;
                  "
                  :class="$store.state.power_state ? 'wall' : ''"
                >
                  <div
                    class="row"
                    v-for="i in 64 / 8"
                    :key="i"
                    style="height: 12.5%; align-items: center"
                    :class="i % 2 == 0 ? 'wall_row' : ''"
                  >
                    <div class="col" v-for="j in 8" :key="j">
                      {{ i * j }}
                    </div>
                  </div>
                </div>
                <div
                  ref="wall"
                  v-if="$store.state.power_state"
                  style="
                    position: absolute;
                    height: 20.7vw;
                    width: 36.8vw;
                    overflow: hidden;
                  "
                  @click="canel_active()"
                >
                  <div
                    v-for="(item, index) of test_monitor_wall"
                    @click.stop="Unchecked == false"
                  >
                    <vue3-resize-drag
                      v-if="item.isShow"
                      :w="item.w"
                      :h="item.h"
                      :x="item.currentx"
                      :y="item.currenty"
                      :isActive="true"
                      :isGuide="true && item.angle == 0"
                      :rotate="parseInt(item.angle.toString())"
                      :is-resizable="false"
                      :resizeIconSize="10"
                      style="
                        background-color: grey;
                        text-align: center;
                        position: absolute;
                      "
                      @moveHandler="moveingMonitor(item, $event, index)"
                      @moveEndHandler="moveMonitor(item, $event)"
                      @mousedown="activeMouseDown(item, index)"
                      :z-index="item.active ? 99 : 0"
                    >
                      <div
                        class="full-height full-width"
                        :class="item.active ? 'monitor_selected' : ''"
                        style="text-align: center"
                        :style="{ lineHeight: show_box_line_height(item.h) }"
                      >
                        <q-popup-proxy context-menu>
                          <q-list>
                            <q-item clickable v-close-popup>
                              <q-item-section @click="closeWindow(item, index)">
                                {{ $t("close this window") }}
                              </q-item-section>
                            </q-item>
                            <q-item clickable v-close-popup>
                              <q-item-section
                                @click="closeOtherWindows(item, index)"
                              >
                                {{ $t("close other windows") }}
                              </q-item-section>
                            </q-item>
                            <q-item clickable v-close-popup>
                              <q-item-section @click="closeAllWindows()">
                                {{ $t("close all windows") }}
                              </q-item-section>
                            </q-item>
                          </q-list>
                        </q-popup-proxy>
                        {{ item.uuid }}
                        <q-separator></q-separator>
                        x:{{ item.centerx }} y:{{ item.centery }}
                      </div>
                    </vue3-resize-drag>
                  </div>
                </div>
              </q-card-section>
            </q-card-section>
          </q-card>
          <br />
          <q-card class="my-card" flat bordered>
            <q-item>
              <q-item-section>
                <q-item-label class="text-h6">{{
                  $t("monitors list")
                }}</q-item-label>
              </q-item-section>
            </q-item>
            <q-separator></q-separator>
            <q-card-section horizontal>
              <q-list key="uuid" class="full-width">
                <div
                  v-for="item in Math.ceil(test_monitor_list.length / 4)"
                  class="row justify-around"
                >
                  <div
                    v-for="j in 4"
                    style="display: inline-block"
                    v-if="
                      item < test_monitor_list.length / 4 ||
                      test_monitor_list.length % 4 == 0
                    "
                    :style="{ lineHeight: box_height(item, j) }"
                  >
                    <div
                      v-if="test_monitor_list[(item - 1) * 4 + (j - 1)].isHide"
                    ></div>
                    <div
                      v-else
                      style="
                        background-color: grey;
                        border: 1px solid black;
                        text-align: center;
                      "
                      :style="{
                        width: box_width(item, j),
                        height: box_height(item, j),
                      }"
                      :draggable="$store.state.power_state"
                      @dragstart="
                        (evt) =>
                          onDragStart(
                            evt,
                            test_monitor_list[(item - 1) * 4 + (j - 1)]
                          )
                      "
                      @dragend="(evt) => onDragend(evt, item, j)"
                    >
                      {{ test_monitor_list[(item - 1) * 4 + (j - 1)].uuid }}
                    </div>
                  </div>
                  <div
                    v-else
                    v-for="j in test_monitor_list.length % 4"
                    style="display: inline-block; text-align: center"
                    :style="{ lineHeight: box_height(item, j) }"
                  >
                    <div
                      v-if="test_monitor_list[(item - 1) * 4 + (j - 1)].isHide"
                    ></div>
                    <div
                      v-else
                      style="background-color: grey; border: 1px solid black"
                      :style="{
                        width: box_width(item, j),
                        height: box_height(item, j),
                      }"
                      :draggable="$store.state.power_state"
                      @dragstart="
                        (evt) =>
                          onDragStart(
                            evt,
                            test_monitor_list[(item - 1) * 4 + (j - 1)]
                          )
                      "
                      @dragend="(evt) => onDragend(evt, item, j)"
                    >
                      {{ test_monitor_list[(item - 1) * 4 + (j - 1)].uuid }}
                    </div>
                  </div>
                </div>
              </q-list>
            </q-card-section>
          </q-card>

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

<style scoped>
.monitor_selected {
  outline-style: dashed;
  outline-color: transparent;
  background-color: dimgrey;
}

.wall {
  border: 1px solid black;
}

.wall_row {
  background-color: #166fab;
}

.drag-enter {
  outline-style: dashed;
}
</style>

<script lang="ts">
import { defineComponent, ref, watch, computed, Ref, reactive } from "vue";
import { useStore } from "src/store";
import {
  useQuasar,
  extend,
  QBtn,
  QCard,
  QCardActions,
  QCardSection,
  QDialog,
  QInput,
  QItem,
  QItemLabel,
  QItemSection,
  QList,
  QPopupProxy,
  QSeparator,
  QSpace,
  QTooltip,
} from "quasar";
import { useI18n } from "vue-i18n";
import GlobalData from "src/common/GlobalData";
import { HttpProtocol } from "src/entities/HttpProtocol";
import vue3ResizeDrag from "../third_lib/vue3-resize-drag/components/vue3-resize-drag/index.vue";
import itemDrag from "src/third_lib/vue3-resize-drag/components/vue3-resize-drag/func/drag";
import MagicWallConfig from "src/entities/MagicWallConfig";
import { PointF } from "src/entities/RectF";
import { number } from "@intlify/core-base";
import EventBus, { EventNamesDefine } from "src/common/EventBus";
// import VeeValidate from 'vee-validate';
class test_monitor {
  uuid = "";
  active = false;
  start_x = 0;
  start_y = 0;
  InitialW = 0;
  InitialH = 0;
  w = 0.0;
  h = 0.0;
  currentx = 0.0;
  currenty = 0.0;
  centerx = 0;
  centery = 0;
  angle = 0;
  id = 0;
  resize = 0;
  isHide = false;
  isShow = false;
  reset() {
    this.uuid = "";
    this.active = false;
    this.start_x = 0;
    this.start_y = 0;
    this.w = 0.0;
    this.h = 0.0;
    this.currentx = 0.0;
    this.currenty = 0.0;
    this.centerx = 0;
    this.centery = 0;
    this.angle = 0;
    this.id = 0;
    this.isHide = false; //列表隐藏
    this.isShow = false; //墙显示
    this.resize = 0;
    this.InitialW = 0;
    this.InitialW = 0;
  }
  constructor(id: number, uuid: string, w: number, h: number, resize: number) {
    this.reset();
    this.id = id;
    this.uuid = uuid;
    this.w = w;
    this.h = h;
    this.resize = resize;
  }
}

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

    let show_dialog = ref(false);
    let loading = ref(false);
    let show_windows_flag = ref(true); // 用于刷新 window 坐标
    let wall: Ref<HTMLElement | null> = ref(null);
    let current_index = ref(-1);
    let window_rect = reactive({
      x: 0,
      y: 0,
      width: 0,
      height: 0,
      angle: 0,
    });
    let multiple = ref(false);
    const aw = 128;
    const ah = 72;
    const bw = 160;
    const bh = 90;
    //调整与背景的百分比
    const percenter = ref(1);
    const ar = 0.5;
    const br = 0.6;
    let test_monitor_list: Ref<test_monitor[]> = ref([
      new test_monitor(0, "01", aw, ah, ar),
      new test_monitor(1, "02", aw, ah, ar),
      new test_monitor(2, "03", aw, ah, ar),
      new test_monitor(3, "04", aw, ah, ar),
      new test_monitor(4, "05", bw, bh, br),
      new test_monitor(5, "06", bw, bh, br),
      new test_monitor(6, "07", bw, bh, br),
      new test_monitor(7, "08", bw, bh, br),
      // new test_monitor(8, "09", bw, bh, br),
    ]);
    const copy_monitor_list = test_monitor_list.value;
    interface show__Rect {
      width: number;
      height: number;
      x: number;
      y: number;
      left: number;
      top: number;
      angle: number;
    }
    let showMonitor = reactive({
      x: 0,
      y: 0,
      width: 0,
      height: 0,
      active: false,
    });
    const radians = () => {
      const item = test_monitor_wall.value[current_index.value];
      return /*a*/ (item.angle * Math.PI) / 180;
    };
    const calculateCoordinates = (
      px: number,
      py: number,
      cx: number,
      cy: number
    ) => {
      const x =
        cx + (px - cx) * Math.cos(radians()) - (py - cy) * Math.sin(radians());

      const y =
        cy + (px - cx) * Math.sin(radians()) + (py - cy) * Math.cos(radians());

      return { x, y };
    };
    const four_point = () => {
      const item = test_monitor_wall.value[current_index.value];
      item.centerx = parseInt(item.centerx.toString());
      item.centery = parseInt(item.centery.toString());
      const x2: number = item.currentx + item.w;
      const y2: number = item.currenty + item.h;
      if (item.angle != 0) {
        const point_left_top = calculateCoordinates(
          item.currentx,
          item.currenty,
          item.centerx,
          item.centery
        );
        const point_left_bootom = calculateCoordinates(
          item.currentx,
          y2,
          item.centerx,
          item.centery
        );
        const point_right_top = calculateCoordinates(
          x2,
          item.currenty,
          item.centerx,
          item.centery
        );
        const point_right_bottom = calculateCoordinates(
          x2,
          y2,
          item.centerx,
          item.centery
        );
        const point_list = [
          point_left_top,
          point_left_bootom,
          point_right_top,
          point_right_bottom,
        ];
        return point_list;
      }
    };
    let test_monitor_wall: Ref<test_monitor[]> = ref([]);
    let multiple_select: Ref<number[]> = ref([]);
    const set_x = () => {
      const wall_dom = wall.value;
      const item = test_monitor_wall.value[current_index.value];
      const rx: number = item.currentx + item.w;
      if (wall_dom) {
        if (rx > wall_dom.offsetWidth) {
          item.currentx = wall_dom.offsetWidth - item.w;
          return item.currentx;
        } else {
          return item.currentx;
        }
      }
    };
    const min_x = (
      item: test_monitor = test_monitor_wall.value[current_index.value]
    ) => {
      // console.log(item)
      const wall_dom = wall.value;
      const point_list = four_point();
      if (wall_dom) {
        if (item.angle != 0 && point_list) {
          let minx = 10000;
          point_list.forEach((element) => {
            if (minx > element.x) {
              minx = element.x;
            }
          });
          if (minx < 0) {
            return Math.floor(item.w / 2 + item.currentx + Math.abs(minx));
          } else {
            return Math.floor(item.centerx-minx);
          }
        } else {
          return Math.floor(item.w / 2);
        }
      }
    };
    const max_x = (
      item: test_monitor = test_monitor_wall.value[current_index.value]
    ) => {
      const wall_dom = wall.value;
      const point_list = four_point();
      if (wall_dom) {
        if (item.angle != 0 && point_list) {
          let maxx = 0;
          point_list.forEach((element) => {
            if (maxx < element.x) {
              maxx = element.x;
            }
          });
          if (maxx > wall_dom.offsetWidth) {
            return Math.floor(
              item.currentx + item.w / 2 - (maxx - wall_dom.offsetWidth)
            );
          }else {
            return Math.floor(maxx);
          }
        } else {
          return Math.floor(wall_dom.offsetWidth - item.w / 2);
        }
      }
    };
    const set_y = () => {
      //输入框正向溢出
      const wall_dom = wall.value;
      const item = test_monitor_wall.value[current_index.value];
      const ry: number = item.currenty + item.h;
      if (wall_dom) {
        if (ry > wall_dom.offsetHeight) {
          item.currenty = wall_dom.offsetHeight - item.h;
          return item.currenty;
        } else {
          return item.currenty;
        }
      }
    };
    const min_y = (
      item: test_monitor = test_monitor_wall.value[current_index.value]
    ) => {
      const wall_dom = wall.value;
      const point_list = four_point();
      if (wall_dom) {
        if (item.angle != 0 && point_list) {
          let miny = 0;
          point_list.forEach((element) => {
            if (miny > element.y) {
              miny = element.y;
            }
          });
          if (miny < 0) {
            return Math.floor(item.h / 2 + item.currenty + Math.abs(miny));
          } else {
            return Math.floor(miny);
          }
        } else {
          return Math.floor(item.h / 2);
        }
      }
    };
    const max_y = (
      item: test_monitor = test_monitor_wall.value[current_index.value]
    ) => {
      const wall_dom = wall.value;
      const point_list = four_point();
      if (wall_dom) {
        if (item.angle != 0 && point_list) {
          let maxy = 0;
          point_list.forEach((element) => {
            if (maxy < element.y) {
              maxy = element.y;
            }
          });
          if (maxy > wall_dom.offsetHeight) {
            return Math.floor(
              item.currenty + item.h / 2 - (maxy - wall_dom.offsetHeight)
            );
          } else {
            return Math.floor(maxy);
          }
        } else {
          return Math.floor(wall_dom.offsetHeight - item.h / 2);
        }
      }
    };
    const max_angle = () => {};
    let Unchecked = ref(false);
    const moveingMonitor = (
      item: test_monitor,
      rect: show__Rect,
      index: number
    ) => {
      item.active = true;
      if (item.active) {
        test_monitor_wall.value.forEach((element) => {
          element.active = false;
        });
      }
      const wall_dom = wall.value;
      if (wall_dom) {
        item.h = item.InitialH * percenter.value;
        item.w = item.InitialW * percenter.value;
      }
      item.active = true;
      item.currentx = rect.left;
      item.currenty = rect.top;
      item.centerx = Math.floor(item.currentx + item.w / 2);
      item.centery = Math.floor(item.currenty + item.h / 2);
      if (Number.isNaN(rect.left || rect.left < 0)) {
        item.currentx = 0;
      }
    };

    const moveMonitor = (item: test_monitor, rect: show__Rect) => {
      //计算是否超出，然后放回
      const wall_dom = wall.value;
      if (item.angle != 0) {
        exceedrange(item);
      } else {
        if (rect.left < 0) {
          item.currentx = 0;
        } else if (wall_dom && rect.left > wall_dom.offsetWidth - item.w) {
          item.currentx = Number(set_x()) ?? 0;
        } else {
          item.currentx = rect.left;
        }
        if (rect.top < 0) {
          item.currenty = 0;
        } else if (wall_dom && rect.top > wall_dom.offsetHeight - item.h) {
          item.currenty = set_y() ?? 0;
        } else {
          item.currenty = rect.top;
        }
        item.centerx = Math.floor(item.currentx + item.w / 2);
        item.centery = Math.floor(item.currenty + item.h / 2);
      }
    };
    const exceedrange = (item: test_monitor) => {
      const wall_dom = wall.value;
      let a = 0;
      const point_list = four_point();
      if (wall_dom && point_list) {
        let maxx = 0;
        let maxy = 0;
        let minx = 0;
        let miny = 0;
        point_list.forEach((element) => {
          if (minx > element.x) {
            minx = element.x;
          }
          if (maxx < element.x) {
            maxx = element.x;
          }
          if (miny > element.y) {
            miny = element.y;
          }
          if (maxy < element.y) {
            maxy = element.y;
          }
        });
        if (minx < 0) {
          item.currentx += Math.abs(minx);
          item.centerx = item.w / 2 + item.currentx;
        }
        if (maxx > wall_dom.offsetWidth) {
          item.currentx -= maxx - wall_dom.offsetWidth;
          item.centerx = item.currentx + item.w / 2;
        }
        if (miny < 0) {
          item.currenty += Math.abs(miny);
          item.centery = item.h / 2 + item.currenty;
        }
        if (maxy > wall_dom.offsetHeight) {
          item.currenty -= maxy - wall_dom.offsetHeight;
          item.centery = item.currenty + item.h / 2;
        }
      }
    };
    let test_delete_flag = false;
    EventBus.getInstance().on(EventNamesDefine.WindowResize, () => {
      const wall_dom = wall.value;
      if (wall_dom) {
        test_monitor_wall.value.forEach((element) => {
          let teph = element.InitialH;
          let tepw = element.InitialW;
          element.InitialH = wall_dom.offsetHeight * element.resize;
          element.InitialW = wall_dom.offsetWidth * element.resize;
          element.h = element.InitialH * percenter.value;
          element.w = element.InitialW * percenter.value;
          let sizeh = element.InitialH / teph;
          let sizew = element.InitialW / tepw;
          element.currentx = element.currentx * sizew;
          element.currenty = element.currenty * sizeh;
          element.centerx = Math.floor(element.currentx + element.w / 2);
          element.centery = Math.floor(element.currenty + element.h / 2);
        });
      }
    });
    return {
      multiple_select,
      multiple,
      exceedrange,
      max_angle,
      four_point,
      show_dialog,
      loading,
      window_rect,
      Unchecked,
      current_index,
      test_monitor_list,
      test_monitor_wall,
      percenter,
      wall,
      set_x,
      min_x,
      max_x,
      set_y,
      min_y,
      max_y,
      moveMonitor,
      moveingMonitor,
      loga(a: any) {
        console.log(a);
      },
      async showDialog() {
        show_dialog.value = true;
        let client = GlobalData.getInstance().getCurrentClient();

        if (client) {
          const response = await client.getMagicWallConfig();
          const a = response?.config.windows;
          const wall_dom = wall.value;
          if (a && wall_dom) {
            a.forEach((element) => {
              let item: test_monitor = new test_monitor(0, "0", 0, 0, 0);
              extend(true, item, test_monitor_list.value[element.index]);
              let sizeh = wall_dom.offsetHeight / element.background_h;
              let sizew = wall_dom.offsetWidth / element.background_w;
              item.currentx = element.lt.x * wall_dom.offsetWidth;
              item.currenty = element.lt.y * wall_dom.offsetHeight;
              percenter.value = parseFloat(element.percenter.toString());
              item.InitialH = element.initial_h * sizeh;
              item.InitialW = element.initial_w * sizew;
              item.h = item.InitialH * percenter.value;
              item.w = item.InitialW * percenter.value;
              item.centerx = Math.floor(item.currentx + item.w / 2);
              item.centery = Math.floor(item.currenty + item.h / 2);
              item.angle = element.angle;
              item.isShow = true;
              test_monitor_wall.value.push(item);
              test_monitor_list.value.forEach((ele) => {
                if (element.index == ele.id) {
                  ele.isHide = true;
                }
              });
            });
            if (a.length == 1) {
              current_index.value = 0;
            } else {
              current_index.value = -1;
            }
          }
        }
      },
      resetData() {
        test_monitor_wall.value = [];
        current_index.value = -1;
        percenter.value = 1;
        multiple_select.value = [];
        multiple.value = false;
        test_monitor_list.value.forEach((element) => {
          element.isHide = false;
        });
        loading.value = false;
      },
      async onSubmit() {
        loading.value = true;
        let client = GlobalData.getInstance().getCurrentClient();
        const wall_dom = wall.value;
        const settings = await GlobalData.getInstance()
          .getCurrentClient()
          ?.getOutputBoardSetting();
        if (client && wall_dom && settings) {
          const response = await client.getMagicWallConfig();
          const cloud_monitor_list = new MagicWallConfig();
          cloud_monitor_list.magic_wall_enable = true; //response?.config.magic_wall_enable ?? true;
          cloud_monitor_list.col = parseInt(settings.wall_col.toString());
          cloud_monitor_list.row = parseInt(settings.wall_row.toString());
          let tep_width = 0;
          test_monitor_wall.value.forEach((element, index) => {
            if (element.isShow) {
              cloud_monitor_list.windows.push({
                index: element.id,
                lt: new PointF(
                  element.currentx / wall_dom.offsetWidth,
                  element.currenty / wall_dom.offsetHeight
                ),
                h: element.h / wall_dom.offsetHeight,
                w: element.w / wall_dom.offsetWidth,
                angle: parseInt(element.angle.toString()),
                initial_h: element.InitialH,
                initial_w: element.InitialW,
                percenter: percenter.value,
                background_h: wall_dom.offsetHeight,
                background_w: wall_dom.offsetWidth,
              });
            }
          });
          const setMagic = await client.setMagicWallConfig(cloud_monitor_list);
          // console.log(setMagic)
          $q.notify({
            color: setMagic?.success ? "positive" : "negative",
            icon: setMagic?.success ? "done" : "warning",
            message:
              $t.t("set magic wall") +
              (setMagic?.success ? $t.t("success") : $t.t("fail")) +
              "!",
            position: "top",
            timeout: 2500,
          });
          show_dialog.value = false;
        }
        loading.value = false;
      },
      activeMouseDown(item: test_monitor, index: number) {
        item.active = true;
        Unchecked.value = false;
        if (multiple.value) {
          if (multiple_select.value.indexOf(index) != -1) {
            test_monitor_wall.value[index].active = false;
            multiple_select.value[multiple_select.value.indexOf(index)] = -1;
          } else {
            multiple_select.value.push(index);
            test_monitor_wall.value[index].active = true;
            current_index.value = index;
          }
        } else {
          multiple_select.value = [];
          if (item.active) {
            test_monitor_wall.value.forEach((element) => {
              element.active = false;
            });
            multiple_select.value.push(index);
          }
          item.active = true;
        }
        current_index.value = index;
      },
      onDragStart(e: DragEvent, item: test_monitor) {
        item.start_x = e.offsetX;
        item.start_y = e.offsetY;
        item.active = false;
        test_delete_flag = false;
        e.dataTransfer?.setData("item", JSON.stringify(item));
      },
      onDragOver(e: DragEvent) {
        e.preventDefault();
      },
      onDrop(e: DragEvent) {
        if (e.dataTransfer?.getData("item") != "") {
          let item = JSON.parse(e.dataTransfer?.getData("item") + "");
          item.currentx = e.offsetX - item.start_x;
          item.currenty = e.offsetY - item.start_y;
          item.active = true;
          item.angle = 0;
          if (item.active) {
            test_monitor_wall.value.forEach((element) => {
              element.active = false;
            });
          }
          if (item.currentx < 0) {
            item.currentx = 0;
            window_rect.x = 0;
          } else {
            window_rect.x = item.currentx;
          }
          if (item.currenty < 0) {
            item.currenty = 0;
            window_rect.y = 0;
          } else {
            window_rect.y = item.currenty;
          }
          test_delete_flag = false;
          const wall_dom = wall.value;
          item.isShow = true;
          if (wall_dom) {
            item.InitialH = wall_dom?.offsetHeight * item.resize;
            item.InitialW = wall_dom?.offsetWidth * item.resize;
            item.h = item.InitialH * percenter.value;
            item.w = item.InitialW * percenter.value;
            if (item.currentx > wall_dom?.offsetWidth - item.w) {
              item.currentx = wall_dom?.offsetWidth - item.w;
            }
            if (item.currenty > wall_dom?.offsetHeight - item.h) {
              item.currenty = wall_dom?.offsetHeight - item.h;
            }
            item.centerx = Math.floor(item.currentx + item.w / 2);
            item.centery = Math.floor(item.currenty + item.h / 2);
          }
          if (test_monitor_wall.value.indexOf(item) == -1) {
            test_monitor_wall.value.push(item);
            test_delete_flag = true;
          }
          current_index.value = test_monitor_wall.value.length - 1;
        }
      },
      onDragEnter(e: DragEvent, index: string) {
        e.stopPropagation();
        let target: HTMLElement | null = e.target as HTMLElement;
        if (target && target.draggable !== true) {
          while (
            target &&
            !target.classList.contains("window_flag") &&
            !target.classList.contains("wall_item_flag")
          ) {
            target = target.parentElement;
          }
          target?.classList.add("drag-enter");
        }
      },
      onDragend(e: DragEvent, row: number, col: number) {
        let num = (row - 1) * 4 + (col - 1);
        if (test_delete_flag) {
          test_monitor_list.value[num].isHide = true;
        }
      },
      onDragLeave(e: DragEvent) {
        let target: HTMLElement = e.target as HTMLElement;
        target?.classList.remove("drag-enter");
      },
      closeWindow(item: test_monitor, index: number) {
        current_index.value = -1;
        test_monitor_list.value[item.id].isHide = false;
        test_monitor_wall.value[index].isShow = false;
        multiple_select.value=[]
      },
      closeOtherWindows(item: test_monitor, index: number) {
        current_index.value = index;
        let tep = JSON.parse(JSON.stringify(item));
        test_monitor_list.value.forEach((element) => {
          element.isHide = false;
        });
        test_monitor_wall.value.forEach((element) => {
          element.isShow = false;
        });
        test_monitor_list.value[item.id].isHide = true;
        test_monitor_wall.value[index].isShow = true;
      },
      closeAllWindows() {
        current_index.value = -1;
        test_monitor_list.value.forEach((element) => {
          element.isHide = false;
        });
        test_monitor_wall.value.forEach((element) => {
          element.isShow = false;
        });
        multiple_select.value=[]
      },
      box_width(row: number, col: number) {
        let tep = JSON.parse(
          JSON.stringify(test_monitor_list.value[(row - 1) * 4 + (col - 1)])
        );
        return tep.w + "px";
      },
      box_height(row: number, col: number) {
        let tep = JSON.parse(
          JSON.stringify(test_monitor_list.value[(row - 1) * 4 + (col - 1)])
        );
        return tep.h + "px";
      },
      show_box_line_height(height: number) {
        return height * 0.5 + "px";
      },
      center_x() {
        const wall_dom = wall.value;
        const item = test_monitor_wall.value[current_index.value];
        item.currentx = item.centerx - item.w / 2;
      },
      center_y() {
        const wall_dom = wall.value;
        const item = test_monitor_wall.value[current_index.value];
        item.currenty = item.centery - item.h / 2;
      },
      changePercenter() {
        const wall_dom = wall.value;
        let tep = false;
        test_monitor_wall.value.forEach((element) => {
          element.w = element.InitialW * percenter.value;
          element.h = element.InitialH * percenter.value;
          const rx: number = element.currentx + element.w;
          const ry: number = element.currenty + element.h;
          const wall_dom = wall.value;
          if (wall_dom) {
            if (rx > wall_dom.offsetWidth) {
              element.currentx = wall_dom.offsetWidth - element.w;
            }
            if (ry > wall_dom.offsetHeight) {
              element.currenty = wall_dom.offsetHeight - element.h;
            }
          }
          element.centerx = Math.floor(element.currentx + element.w / 2);
          element.centery = Math.floor(element.currenty + element.h / 2);
          if (element.isShow) {
            tep = true;
          }
        });
      },
      canel_active() {
        Unchecked.value = true;
        if (Unchecked) {
          current_index.value = -1;
          test_monitor_wall.value.forEach((element) => {
            element.active = false;
          });
        }
        multiple_select.value = [];
        multiple.value = false;
      },
      changeAngle() {
        const wall_dom = wall.value;
        let item = test_monitor_wall.value[current_index.value];
        exceedrange(item);
      },
      sub_x() {
        let item = test_monitor_wall.value[current_index.value];
        if (multiple_select.value.length > 1) {
          multiple_select.value.forEach((element) => {
            if (element != -1) {
              // console.log("这是第几个"+element)
              let min = min_x(test_monitor_wall.value[element]) ?? 0;
              // console.log("这是最小值"+min)
              // console.log("这是中心点"+test_monitor_wall.value[element].centerx)
              if (test_monitor_wall.value[element].centerx > min) {
                test_monitor_wall.value[element].currentx--;
                test_monitor_wall.value[element].centerx--;
              }
            }
          });
        } else {
          // console.log("美金")
          let min = min_x() ?? 0;
          if (item.centerx > min) {
            item.currentx--;
            item.centerx--;
          }
        }
      },
      sub_y() {
        let item = test_monitor_wall.value[current_index.value];
        if (multiple_select.value.length > 1) {
          multiple_select.value.forEach((element) => {
            if (element != -1) {
              let min = min_y(test_monitor_wall.value[element]) ?? 0;
              if (test_monitor_wall.value[element].centery > min) {
                test_monitor_wall.value[element].currenty--;
                test_monitor_wall.value[element].centery--;
              }
            }
          });
        } else {
          let min = min_y() ?? 0;
          if (item.centery > min) {
            item.currenty--;
            item.centery--;
          }
        }
      },
      add_x() {
        let item = test_monitor_wall.value[current_index.value];
        if (multiple_select.value.length > 1) {
          multiple_select.value.forEach((element) => {
            if (element != -1) {
              let max = max_x(test_monitor_wall.value[element]) ?? 0;
              if (test_monitor_wall.value[element].centerx < max) {
                test_monitor_wall.value[element].currentx++;
                test_monitor_wall.value[element].centerx++;
              }
            }
          });
        } else {
          let max = max_x() ?? 0;
          if (item.centerx < max) {
            item.currentx++;
            item.centerx++;
          }
        }
      },
      add_y() {
        let item = test_monitor_wall.value[current_index.value];
        if (multiple_select.value.length > 1) {
          multiple_select.value.forEach((element) => {
            if (element != -1) {
              let max = max_y(test_monitor_wall.value[element]) ?? 0;
              if (test_monitor_wall.value[element].centery < max) {
                test_monitor_wall.value[element].currenty++;
                test_monitor_wall.value[element].centery++;
              }
            }
          });
        } else {
          let max = max_y() ?? 0;
          if (item.centery < max) {
            item.currenty++;
            item.centery++;
          }
        }
      },
    };
  },
});
</script>
