<template>
  <div class="row">
    <div class="col-1"></div>
    <div class="col-8 q-pt-md">
      <div ref="div" style="width: 100%; background-color: #646464; height: 100%">
        <div style="position: absolute">
          <vue3ResizeDrag  style="border: 0;"  :class="[now_index==0?'action':'']" :isActive="isactivearray[0]" v-if="isshowarray[0]" :w="30" :h="30" :x="point_postion[0].x"
            :y="point_postion[0].y" @mousedown="activeMouseDown(0)" :isResizable="false"
            @moveHandler="moveHandler($event, 0)"><p class="vcolro p0">V1</p>
          </vue3ResizeDrag>
          <vue3ResizeDrag  style="border: 0;"  :class="[now_index==1?'action':'']" :isActive="isactivearray[1]" v-if="isshowarray[1]" :w="30" :h="30" :x="point_postion[1].x"
            :y="point_postion[1].y" @mousedown="activeMouseDown(1)" :isResizable="false"
            @moveHandler="moveHandler($event, 1)"><p class="vcolro p0">V2</p>
          </vue3ResizeDrag>
          <vue3ResizeDrag  style="border: 0;"  :class="[now_index==2?'action':'']" :isActive="isactivearray[2]" v-if="isshowarray[2]" :w="30" :h="30" :x="point_postion[2].x"
            :y="point_postion[2].y" @mousedown="activeMouseDown(2)" :isResizable="false"
            @moveHandler="moveHandler($event, 2)"><p class="vcolro p0">V3</p>
          </vue3ResizeDrag>
          <vue3ResizeDrag  style="border: 0;"  :class="[now_index==3?'action':'']" :isActive="isactivearray[3]" v-if="isshowarray[3]" :w="30" :h="30" :x="point_postion[3].x"
            :y="point_postion[3].y" @mousedown="activeMouseDown(3)" :isResizable="false"
            @moveHandler="moveHandler($event, 3)"><p class="vcolro p0">V4</p>
          </vue3ResizeDrag>
          <vue3ResizeDrag  style="border: 0;"  :class="[now_index==4?'action':'']" :isActive="isactivearray[4]" v-if="isshowarray[4]" :w="30" :h="30" :x="point_postion[4].x"
            :y="point_postion[4].y" @mousedown="activeMouseDown(4)" :isResizable="false"
            @moveHandler="moveHandler($event, 4)"><p class="vcolro p0">V5</p>
          </vue3ResizeDrag>
          <vue3ResizeDrag  style="border: 0;"  :class="[now_index==5?'action':'']" :isActive="isactivearray[5]" v-if="isshowarray[5]" :w="40" :h="20" :x="point_postion[5].x"
            :y="point_postion[5].y" @mousedown="activeMouseDown(5)" :isResizable="false"
            @moveHandler="moveHandler($event, 5)"><span class="hcolro">H1</span>
          </vue3ResizeDrag>
          <vue3ResizeDrag  style="border: 0;"  :class="[now_index==6?'action':'']" :isActive="isactivearray[6]" v-if="isshowarray[6]" :w="40" :h="20" :x="point_postion[6].x"
            :y="point_postion[6].y" @mousedown="activeMouseDown(6)" :isResizable="false"
            @moveHandler="moveHandler($event, 6)"><span class="hcolro">H2</span>
          </vue3ResizeDrag>
          <vue3ResizeDrag  style="border: 0;"  :class="[now_index==7?'action':'']" :isActive="isactivearray[7]" v-if="isshowarray[7]" :w="40" :h="20" :x="point_postion[7].x"
            :y="point_postion[7].y" @mousedown="activeMouseDown(7)" :isResizable="false"
            @moveHandler="moveHandler($event, 7)"><span class="hcolro">H3</span>
          </vue3ResizeDrag>
          <vue3ResizeDrag  style="border: 0;"  :class="[now_index==8?'action':'']" :isActive="isactivearray[8]" v-if="isshowarray[8]" :w="40" :h="20" :x="point_postion[8].x"
            :y="point_postion[8].y" @mousedown="activeMouseDown(8)" :isResizable="false"
            @moveHandler="moveHandler($event, 8)"><span class="hcolro">H4</span>
          </vue3ResizeDrag>
          <vue3ResizeDrag  style="border: 0;"  :class="[now_index==9?'action':'']" :isActive="isactivearray[9]" v-if="isshowarray[9]" :w="40" :h="20" :x="point_postion[9].x"
            :y="point_postion[9].y" @mousedown="activeMouseDown(9)" :isResizable="false"
            @moveHandler="moveHandler($event, 9)"><span class="hcolro">H5</span>
          </vue3ResizeDrag>
        </div>
      </div>
    </div>
    <div class="col-3 q-pt-md">
      <div class="row">
        <div class="col-12">
          <div class="row">
            <div class="col-2"></div>
            <div class="col-8">
              <q-input @focus="isactivearray[0] = false" filled type="number" class="q-pt-md" :dense="true"
                v-model="value[0].y" label="y" lazy-rules />
              <q-btn  size="sm" color="white" @click="reset(0)" text-color="black" :label="$t('reset') + ' v1'" />
            </div>
          </div>
        </div>
        <div class="col-12">
          <div class="row">
            <div class="col-2"></div>
            <div class="col-8">
              <q-input @focus="isactivearray[1] = false" filled type="number" class="q-pt-md" :dense="true"
                v-model="value[1].y" label="y" lazy-rules />
              <q-btn  size="sm" color="white" @click="reset(1)" text-color="black" :label="$t('reset') + ' v2'" />
            </div>
          </div>
        </div>
        <div class="col-12">
          <div class="row">
            <div class="col-2"></div>
            <div class="col-8">
              <q-input @focus="isactivearray[2] = false" filled type="number" class="q-pt-md" :dense="true"
                v-model="value[2].y" label="y" lazy-rules />
              <q-btn  size="sm" color="white" @click="reset(2)" text-color="black" :label="$t('reset') + ' v3'" />
            </div>
          </div>
        </div>
        <div class="col-12">
          <div class="row">
            <div class="col-2"></div>
            <div class="col-8">
              <q-input @focus="isactivearray[3] = false" filled type="number" class="q-pt-md" :dense="true"
                v-model="value[3].y" label="y" lazy-rules />
              <q-btn  size="sm" color="white" @click="reset(3)" text-color="black" :label="$t('reset') + ' v4'" />
            </div>
          </div>
        </div>
        <div class="col-12">
          <div class="row">
            <div class="col-2"></div>
            <div class="col-8">
              <q-input @focus="isactivearray[4] = false" filled type="number" class="q-pt-md" :dense="true"
                v-model="value[4].y" label="y" lazy-rules />
              <q-btn  size="sm" color="white" @click="reset(4)" text-color="black" :label="$t('reset') + ' v5'" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-1"></div>
    <div class="col-11">
      <div class="box">
        <div class="box_son">
          <q-input filled @focus="isactivearray[5] = false" type="number" class="q-pt-md" :dense="true"
            v-model="value[5].x" label="x" lazy-rules />
          <q-btn  size="sm" color="white" @click="reset(5)" text-color="black" :label="$t('reset') + ' h1'" />
        </div>

        <div class="box_son">
          <q-input filled @focus="isactivearray[6] = false" type="number" class="q-pt-md" :dense="true"
            v-model="value[6].x" label="x" lazy-rules />
          <q-btn  size="sm" color="white" @click="reset(6)" text-color="black" :label="$t('reset') + ' h2'" />
        </div>

        <div class="box_son">
          <q-input filled @focus="isactivearray[7] = false" type="number" class="q-pt-md" :dense="true"
            v-model="value[7].x" label="x" lazy-rules />
          <q-btn  size="sm" color="white" @click="reset(7)" text-color="black" :label="$t('reset') + ' h3'" />
        </div>

        <div class="box_son">
          <q-input filled @focus="isactivearray[8] = false" type="number" class="q-pt-md" :dense="true"
            v-model="value[8].x" label="x" lazy-rules />
          <q-btn  size="sm" color="white" @click="reset(8)" text-color="black" :label="$t('reset') + ' h4'" />
        </div>

        <div class="box_son">
          <q-input filled @focus="isactivearray[9] = false" type="number" class="q-pt-md" :dense="true"
            v-model="value[9].x" label="x" lazy-rules />
          <q-btn  size="sm" color="white" @click="reset(9)" text-color="black" :label="$t('reset') + ' h5'" />
        </div>

        <div class="box_son q-pt-xl">
          <q-btn
            color="white"
            @click="resetall"
            text-color="black"
            :label="$t('resetall')"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.box{
  display: flex;
  justify-content:space-between;
}
.box_son{
  width: 10rem;
  padding-right: 1rem;
}
.vcolro{
  color: #d50000;
}
.hcolro{
  color: #00c853;
  font-size: 5px;
}
.p0{
  margin: 0;
  padding: 0;
}
.action{
  background-color: aqua;
}
</style>
<script lang="ts">
import {
  defineComponent,
  ref,
  watch,
  computed,
  defineProps,
  withDefaults,
  reactive,
  onMounted,
  onBeforeUnmount,
} from "vue";
import { useStore } from "src/store";
import { useI18n } from "vue-i18n";
import vue3ResizeDrag from "/src/third_lib/vue3-resize-drag/components/vue3-resize-drag/index.vue";
import GlobalData from "src/common/GlobalData";
export default defineComponent({
  name: "ComponentDensityCorrection",
  components: {
    vue3ResizeDrag,
  },
  setup() {
    let $store = useStore();
    let $t = useI18n();
    const now_index = ref(0);
    const value = reactive([
      { x: 0, y: 0, number: 0 },
      { x: 0, y: 0, number: 0 },
      { x: 0, y: 0, number: 0 },
      { x: 0, y: 0, number: 0 },
      { x: 0, y: 0, number: 0 },
      { x: 0, y: 0, number: 0 },
      { x: 0, y: 0, number: 0 },
      { x: 0, y: 0, number: 0 },
      { x: 0, y: 0, number: 0 },
      { x: 0, y: 0, number: 0 },
    ]);
    let model = ref(null);
    const div = ref();
    const isshowarray = ref([
      true,
      true,
      true,
      true,
      true,
      true,
      true,
      true,
      true,
      true,
    ]);
    const isactivearray = ref([
      true,
      true,
      true,
      true,
      true,
      true,
      true,
      true,
      true,
      true,
    ]);
    const default_location: any = reactive([
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
    ]);
     const max_x_y=reactive([0,0])
    let options = ref(["10", "20", "30", "40", "50"]);
    let config = JSON.parse($store.state.fusion_configuration).projectors[0];
    let Proportion = ref({ x: 0, y: 0 });
    const configselsect = computed(() => {
      return $store.state.selected_projector;
    });
    //用于计算当前投影仪的索引
    let serverconfig = JSON.parse($store.state.fusion_configuration);
    const selectedprojector = computed(() => {
      return (
        $store.getters.GetTheCurrentlySelectedCamera[0] * serverconfig.col +
        $store.getters.GetTheCurrentlySelectedCamera[1]
      );
    });
    const set_cache: any = ref([]);
    const ste_status = ref(0);
    //为了加载 缓存的配置时 同步点的位置
    const syncpoint = () => {
      let x = 0
      let y = 0
      for (let index = 0; index < 5; index++) {
        x = default_location[index].x;
        y = Math.ceil((config.height - value[index].y) / Proportion.value.y);
        setdianposin(index, x, y);
      }

      for (let index = 5; index < 10; index++) {
        x = Math.ceil(value[index].x / Proportion.value.x);
        y = default_location[5].y;
        setdianposin(index, x, y);
      }

      for (let index = 0; index < value.length; index++) {
        isactivearray.value[index] = false;
      }
    };

    const use_set_cache = () => {
      if (set_cache.value[selectedprojector.value] != null) {
        let tmp = JSON.parse(set_cache.value[selectedprojector.value]);
        deepcopy(value, tmp);
        syncpoint();
      }
    };
    const deepcopy = (o1: any, o2: any) => {
      for (let k in o2) {
        if (typeof o2[k] === "object") {
          o1[k] = {};
          deepcopy(o1[k], o2[k]);
        } else {
          o1[k] = o2[k];
        }
      }
    };
    const save_set_cache = () => {
      set_cache.value[selectedprojector.value] = JSON.stringify(value);
    };
    onBeforeUnmount(() => {
      sessionStorage.DensityCorrection = JSON.stringify(set_cache.value);
    });
    watch(()=>now_index,(newval,oldval)=>{
      now_index.value>5?set?.SetBlendingOption("blending_grids_select_point",`density_h:${now_index.value-4}`):set?.SetBlendingOption("blending_grids_select_point",`density_v:${now_index.value+1}`)
    },{ deep: true })
    watch(
      () => configselsect,
      (newVal, oldVal) => {
        let tmp = JSON.parse($store.state.fusion_configuration);
        let fortmp = null;
        let i;
        for (i of tmp.projectors) {
          if (
            i.col === $store.getters.GetTheCurrentlySelectedCamera[1] &&
            i.row === $store.getters.GetTheCurrentlySelectedCamera[0]
          ) {
            fortmp = JSON.parse(JSON.stringify(i));
          }
        }
        ste_status.value = 1;
        config = JSON.parse(JSON.stringify(fortmp));
        use_server_config();
        use_set_cache();
        setTimeout(() => {
          ste_status.value = 0;
        }, 100);
        syncpoint();
      },
      { deep: true }
    );
    const initialization = () => {
      ste_status.value = 1;
      for (let index = 0; index < config.hor_density.length; index++) {
        value[index].x = config.ver_density[index].x;
        value[index].y = config.ver_density[index].y;
        value[index].number = config.ver_density[index].number;
        value[index + 5].x = config.hor_density[index].x;
        value[index + 5].y = config.hor_density[index].y;
        value[index + 5].number = config.hor_density[index].number;
      }
      if (
        sessionStorage.DensityCorrection &&
        sessionStorage.DensityCorrection.length > 0
      ) {
        set_cache.value = JSON.parse(sessionStorage.DensityCorrection);
        use_set_cache();
      } else {
      }
      syncpoint();
      setTimeout(() => {
        ste_status.value = 0;
      }, 100);
    };

    const resetall = () => {
      for (
        let index = 0;
        index < config.hor_density.length + config.ver_density.length;
        index++
      ) {
        reset(index);
      }
    };
    const reset = (index: number) => {
      if (index > 4) {
        value[index].x = config.hor_density[index - 5].def_x;
        value[index].y = config.hor_density[index - 5].def_y;

        set?.SetBlendingHorDensity(
          $store.getters.GetTheCurrentlySelectedCamera[0],
          $store.getters.GetTheCurrentlySelectedCamera[1],
          index - 5 + 1,
          Number(value[index].x)
        );
      } else {
        value[index].x = config.ver_density[index].def_x;
        value[index].y = config.ver_density[index].def_y;
        set?.SetBlendingVerDensity(
          $store.getters.GetTheCurrentlySelectedCamera[0],
          $store.getters.GetTheCurrentlySelectedCamera[1],
          index + 1,
          Number(value[index].y)
        );
      }

      point_postion[index].y = default_location[index].y;
      point_postion[index].x = default_location[index].x;
      isshowarray.value[index] = false;
      setTimeout(() => {
        isshowarray.value[index] = true;
      }, 100);
    };
    const point_postion: any = reactive([
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
      { x: 0, y: 0 },
    ]);
    let set = GlobalData.getInstance().getCurrentClient();
    const save = () => {
      set?.SaveBlendingConfig("");
      setTimeout(() => {
        set?.GetBlendingConfig("").then((res) => {
          $store.commit("setfusion_configuration", res?.config);
        });
      }, 1000);
    };

    const moveHandler = ($event: any, index: number) => {
      let x = 0;
      let y = 0;
      switch (index) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
          x =
            config.width / 2 +
            Math.ceil(
              ($event.left - default_location[index].x) * Proportion.value.x
            );
          y =
            config.height -
            (config.height / 4) * index -
            Math.ceil(
              ($event.top - default_location[index].y) * Proportion.value.y
            );
          break;
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
          x = Math.ceil($event.left * Proportion.value.x);
          y =
            config.height / 2 -
            Math.ceil(
              ($event.top - default_location[index].y) * Proportion.value.y
            );

          break;
        default:
      }
      value[index].x = x > config.width ? config.width : x && x < 0 ? 0 : x;
      value[index].y = y > config.height ? config.height : y && y < 0 ? 0 : y;
      save_set_cache();
    };

    const use_server_config = () => {
      for (let index = 0; index < config.hor_density.length; index++) {
        value[index].x = config.ver_density[index].x;
        value[index].y = config.ver_density[index].y;
        value[index].number = config.ver_density[index].number;
        value[index + 5].x = config.hor_density[index].x;
        value[index + 5].y = config.hor_density[index].y;
        value[index + 5].number = config.hor_density[index].number;
      }
    };


    onMounted(() => {
      initialization();
      max_x_y[0]=div.value.offsetWidth-25
      max_x_y[1]=div.value.offsetHeight-15
      Proportion.value.x = config.width / (div.value.offsetWidth - 40);
      Proportion.value.y = config.height / (div.value.offsetHeight - 30);
      let Width = (div.value.offsetWidth - 40) / 4;
      let Height = (div.value.offsetHeight - 30) / 4;
      for (
        let index = 0;
        index < config.hor_density.length + config.ver_density.length;
        index++
      ) {
        if (index < 5) {
          point_postion[index].y = default_location[index].y = Height * index;
          point_postion[index].x = default_location[index].x = Width * 2;
        } else {
          point_postion[index].y = default_location[index].y = Height * 2;
          point_postion[index].x = default_location[index].x =
            Width * (index - 5);
        }
      }
      use_server_config();
      if (
        sessionStorage.DensityCorrection &&
        sessionStorage.DensityCorrection.length > 0
      ) {
        set_cache.value = JSON.parse(sessionStorage.DensityCorrection);
        use_set_cache();
      } else {
      }
      syncpoint();
    });

    //窗口变动重新渲染
    onMounted(() => {
      window.onresize = () => {
        return (() => {
          if (div != null) {
            initialization();
            Proportion.value.x = config.width / (div.value.offsetWidth - 40);
            Proportion.value.y = config.height / (div.value.offsetHeight - 30);
            let Width = (div.value.offsetWidth - 40) / 4;
            let Height = (div.value.offsetHeight - 30) / 4;
            for (
              let index = 0;
              index < config.hor_density.length + config.ver_density.length;
              index++
            ) {
              if (index < 5) {
                point_postion[index].y = default_location[index].y =
                  Height * index;
                point_postion[index].x = default_location[index].x = Width * 2;
              } else {
                point_postion[index].y = default_location[index].y = Height * 2;
                point_postion[index].x = default_location[index].x =
                  Width * (index - 5);
              }
            }
          }
        })();
      };
    });

    const setdianposin = (index: number, x: number, y: number) => {
      point_postion[index].x = x;
      point_postion[index].y = y;
      isshowarray.value[index] = false;
      isactivearray.value[index] = false;
      setTimeout(() => {
        isshowarray.value[index] = true;
      }, 100);
      if(ste_status.value == 0)now_index.value=index
    };
    watch(
      () => value[0],
      (newVal, oldVal) => {
        send_configuration(1, newVal.y, newVal.number);
        if (!isactivearray.value[0]) {
          let x = default_location[0].x;
          let y = Math.ceil((config.height - newVal.y) / Proportion.value.y);
          setdianposin(0, x, y);
        }
        now_index.value=0
        save_set_cache();
      },
      { deep: true }
    );

    watch(
      () => value[1],
      (newVal, oldVal) => {
        send_configuration(2, newVal.y, newVal.number);
        if (!isactivearray.value[1]) {
          let x = default_location[1].x;
          let y = Math.ceil((config.height - newVal.y) / Proportion.value.y);
          setdianposin(1, x, y);
        }
        save_set_cache();
      },
      { deep: true }
    );

    watch(
      () => value[2],
      (newVal, oldVal) => {
        send_configuration(3, newVal.y, newVal.number);
        if (!isactivearray.value[2]) {
          let x = Math.ceil(newVal.x / Proportion.value.x);
          let y = Math.ceil((config.height - newVal.y) / Proportion.value.y);
          setdianposin(2, x, y);
        }
        save_set_cache();
      },
      { deep: true }
    );

    watch(
      () => value[3],
      (newVal, oldVal) => {
        send_configuration(4, newVal.y, newVal.number);
        if (!isactivearray.value[3]) {
          let x = default_location[3].x;
          let y = Math.ceil((config.height - newVal.y) / Proportion.value.y);
          setdianposin(3, x, y);
        }
        save_set_cache();
      },
      { deep: true }
    );

    watch(
      () => value[4],
      (newVal, oldVal) => {
        send_configuration(5, newVal.y, newVal.number);
        if (!isactivearray.value[4]) {
          let x = default_location[4].x;
          let y = Math.ceil((config.height - newVal.y) / Proportion.value.y);
          setdianposin(4, x, y);
        }
        save_set_cache();
      },
      { deep: true }
    );


    watch(
      () => value[5],
      (newVal, oldVal) => {
        send_configuration(6, newVal.x, newVal.number);
        if (!isactivearray.value[5]) {
          let x = Math.ceil(newVal.x / Proportion.value.x);
          let y = default_location[5].y;
          setdianposin(5, x, y);
        }
        save_set_cache();
      },
      { deep: true }
    );

    watch(
      () => value[6],
      (newVal, oldVal) => {
        send_configuration(7, newVal.x, newVal.number);
        if (!isactivearray.value[6]) {
          let x = Math.ceil(newVal.x / Proportion.value.x);
          let y = default_location[6].y;
          setdianposin(6, x, y);
        }
        save_set_cache();
      },
      { deep: true }
    );

    watch(
      () => value[7],
      (newVal, oldVal) => {
        send_configuration(8, newVal.x, newVal.number);
        if (!isactivearray.value[7]) {
          let x = Math.ceil(newVal.x / Proportion.value.x);
          let y = default_location[7].y;
          setdianposin(7, x, y);
        }
        save_set_cache();
      },
      { deep: true }
    );

    watch(
      () => value[8],
      (newVal, oldVal) => {
        send_configuration(9, newVal.x, newVal.number);
        if (!isactivearray.value[8]) {
          let x = Math.ceil(newVal.x / Proportion.value.x);
          let y = default_location[8].y;
          setdianposin(8, x, y);
        }
        save_set_cache();
      },
      { deep: true }
    );

    watch(
      () => value[9],
      (newVal, oldVal) => {
        send_configuration(10, newVal.x, newVal.number);
        if (!isactivearray.value[9]) {
          let x = Math.ceil(newVal.x / Proportion.value.x);
          let y = default_location[9].y;
          setdianposin(9, x, y);
        }
        save_set_cache();
      },
      { deep: true }
    );

    const send_configuration = (
      index: number,
      value: number,
      number: number
    ) => {
      if (ste_status.value == 0) {
        if (index <= 5) {
          set?.SetBlendingVerDensity(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            index,
            Number(value)
          );
        } else {
          set?.SetBlendingHorDensity(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            index - 5,
            Number(value)
          );
        }
      }
      save_set_cache();
    };
    const activeMouseDown = (index: number) => {
      isactivearray.value[index] = true;
      // if(index>=5){
      //   set?.SetBlendingOption("blending_grids_select_point",`density_h:${index-4}`)
      // }else{
      //   set?.SetBlendingOption("blending_grids_select_point",`density_v:${index+1}`)
      // }
      now_index.value=index
    };
    initialization();
    return {
      now_index,
      activeMouseDown,
      model,
      options,
      value,
      reset,
      resetall,
      point_postion,
      moveHandler,
      div,
      isshowarray,
      isactivearray,
      save,
    };
  },
});
</script>
