<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">
          <Vue3DraggableResizable v-for="(item, index) in config.ver_density.length" :initW="20" :initH="20"
            :resizable="false" :x="0" v-model:y="point_postion[index].y" :disabledX="true"
            @activated="now_index = index" @dragging="dragStartHandle($event, index, 'v')">
            <span>v{{
              index+ 1
            }}</span>
          </Vue3DraggableResizable>
          <Vue3DraggableResizable v-for="(item, index) in config.ver_density.length" :initW="20" :initH="20"
            :resizable="false" :x="max_x_y[0]" v-model:y="point_postion[index].y" @activated="now_index = index"
            @dragging="dragStartHandle($event, index, 'v')">
            <span>v{{
              index+ 1
            }}</span>
          </Vue3DraggableResizable>
          <Vue3DraggableResizable v-for="(item, index) in config.hor_density.length" :initW="20" :initH="20"
            :resizable="false" v-model:x="point_postion[index + 5].x" :y="-20" @activated="now_index = index + 5"
            :disabledY="true" @dragging="dragStartHandle($event, index + 5, 'h')">
            <span>h{{
              index+ 1
            }}</span>
          </Vue3DraggableResizable>
          <Vue3DraggableResizable v-for="(item, index) in config.hor_density.length" :initW="20" :initH="20"
            :resizable="false" v-model:x="point_postion[index + 5].x" @activated="now_index = index + 5"
            :y="max_x_y[1] + 20" @dragging="dragStartHandle($event, index + 5, 'h')">
            <span>h{{
              index+ 1
            }}</span>
          </Vue3DraggableResizable>
        </div>
      </div>
    </div>
    <div class="col-3 q-pt-md">
      <div class="row">
        <div class="col-12" v-for="(item, index) in 5">
          <div class="row">
            <div class="col-2"></div>
            <div class="col-8">
              <q-input filled type="number" class="q-pt-md" :dense="true" v-model="value[index].y"
                @update:model-value="chang(index, $event)" label="y" lazy-rules />
              <q-btn size="sm" color="white" @click="reset(index)" text-color="black"
                :label="$t('reset') + `v${index + 1}`" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-1"></div>
    <div class="col-11">
      <div class="box">
        <div class="box_son" v-for="(item, index) in 5">
          <q-input filled type="number" class="q-pt-md" :dense="true" v-model="value[index + 5].x" label="x"
            @update:model-value="chang(index + 5, $event)" lazy-rules />
          <q-btn size="sm" color="white" @click="reset(index + 5)" text-color="black"
            :label="$t('reset') + `h${index + 1}`" />
        </div>
        <div class="box_son q-pt-xl">
          <q-btn color="white" @click="resetall" text-color="black" :label="$t('resetall')" />
        </div>
      </div>
    </div>
  </div>
  <div>
      <div class="row">
        <div class="col-1"></div>
        <div class="col-2"> <q-select class="q-pt-md" :dense="true" filled v-model="options_model_v" :options="options_v" emit-value
            map-options /></div>
        <div class="col-2"> <q-input filled type="number" class="q-pt-md" :dense="true"
            v-model="value[options_model_v].y" @update:model-value="chang(options_model_v, $event)" lazy-rules />
        </div>
      </div>
      <div class="row">
        <div class="col-1"></div>
        <div class="col-2"> <q-select class="q-pt-md" :dense="true" filled v-model="options_model_h" :options="options_h" emit-value
            map-options /></div>
        <div class="col-2"> <q-input filled type="number" class="q-pt-md" :dense="true"
            v-model="value[options_model_h].x" @update:model-value="chang(options_model_h+5, $event)" lazy-rules />
        </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;
  line-height: 8px;
}

.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";
import Vue3DraggableResizable from 'vue3-draggable-resizable'
import 'vue3-draggable-resizable/dist/Vue3DraggableResizable.css'
import { type } from "os";
import { number } from "@intlify/core-base";
export default defineComponent({
  name: "ComponentDensityCorrection",
  components: {
    vue3ResizeDrag,
    Vue3DraggableResizable
  },
  setup() {
    let $store = useStore();
    let $t = useI18n();
    const now_index = ref(0);
    const max_x_y = reactive([0, 0]);
    const now_adjust = ref("v")
    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 },
    ]);
    //为动态添加做准备
    const value_h = reactive([]);
    const value_v = reactive([]);
    const default_location_v = reactive([]);
    const default_location_h = reactive([]);
    let model = ref(null);
    const div = ref();
    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 },
    ]);
    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 chang = (index: number, $event: any) => {
      let x = 0
      let y = 0
      if (index < 5) {
        x = default_location[9].y;
        y = Math.ceil((config.height - $event) / Proportion.value.y);
        send_configuration(index, $event)
      } else {
        x = Math.ceil($event / Proportion.value.x);
        y = default_location[0].x;
        send_configuration(index, $event)
      }
      point_postion[index].x = Number(x)
      point_postion[index].y = Number(y)
      now_index.value = index
    }

    const asyncpoint = (index: number, $event: any) => {
      let x = 0
      let y = 0
      if (index < 5) {
        x = default_location[9].y;
        y = Math.ceil((config.height - $event) / Proportion.value.y);
      } else {
        x = Math.ceil($event / Proportion.value.x);
        y = default_location[0].x;
      }
      point_postion[index].x = Number(x)
      point_postion[index].y = Number(y)
    }

    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);
      },
      { 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].control_point;
        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].control_point;
      }
      if (
        sessionStorage.DensityCorrection &&
        sessionStorage.DensityCorrection.length > 0
      ) {
        set_cache.value = JSON.parse(sessionStorage.DensityCorrection);
        use_set_cache();
      } else {
      }
      setTimeout(() => {
        ste_status.value = 0;
      }, 100);
    };

    const use_set_cache = () => {
      if (set_cache.value[selectedprojector.value] != null) {
        let tmp = JSON.parse(set_cache.value[selectedprojector.value]);
        deepcopy(value, tmp);
      }
      for (let index = 0; index < 10; index++) {
        asyncpoint(index, index < 5 ? value[index].y : value[index].x)
      }
    };
    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;
      save_set_cache()
    };
    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 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;
      }
      for (let index = 0; index < 10; index++) {
        asyncpoint(index, index < 5 ? value[index].y : value[index].x)

      }
    };


    onMounted(() => {
      initialization();
      Proportion.value.x = config.width / (div.value.offsetWidth - 20);
      Proportion.value.y = config.height / (div.value.offsetHeight - 20);
      let Width = (div.value.offsetWidth - 20) / 4;
      let Height = (div.value.offsetHeight - 20) / 4;

      max_x_y[0] = div.value.offsetWidth - 20
      max_x_y[1] = div.value.offsetHeight - 20
      for (let index = 0; index < 10; index++) {
        if (index < 5) {
          point_postion[index].y = default_location[index].y = Height * index;
          point_postion[index].x = default_location[index].x = 0;
        } else {
          point_postion[index].y = default_location[index].y = 0;
          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 {
      }



    });

    //窗口变动重新渲染
    onMounted(() => {
      window.onresize = () => {
        return (() => {
          if (div != null) {
            initialization();
            Proportion.value.x = config.width / (div.value.offsetWidth - 20);
            Proportion.value.y = config.height / (div.value.offsetHeight - 30);
            let Width = (div.value.offsetWidth - 20) / 4;
            let Height = (div.value.offsetHeight - 20) / 4;

            max_x_y[0] = div.value.offsetWidth - 20
            max_x_y[1] = div.value.offsetHeight - 20
            for (let index = 0; index < 10; index++) {
              if (index < 5) {
                point_postion[index].y = default_location[index].y = Height * index;
                point_postion[index].x = default_location[index].x = 0;
              } else {
                point_postion[index].y = default_location[index].y = 0;
                point_postion[index].x = default_location[index].x = Width * (index - 5);
              }
            }
          }
        })();
      };
    });
    const send_configuration = (
      index: number,
      value: number,
    ) => {
      if (ste_status.value == 0) {
        if (index <= 5) {
          set?.SetBlendingVerDensity(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            index + 1,
            Number(value)
          );
        } else {
          set?.SetBlendingHorDensity(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            index - 4,
            Number(value)
          );
        }
      }
      save_set_cache();
    };
    initialization();
    const dragStartHandle = ($event: any, index: number, type: string) => {
      let obj_x = $event.x
      let obj_y = $event.y
      if (type == 'h') {
        let x =
          config.width / 4 * (index - 5) +
          Math.ceil(
            (obj_x - default_location[index].x) * Proportion.value.x
          );
        let y =
          config.height -
          (config.height / 4) * index -
          Math.ceil(
            (obj_y - default_location[index].y) * Proportion.value.y
          );
        value[index].x = x > config.width ? config.width : x && x < 0 ? 0 : x;
        send_configuration(index, x)
      }
      if (type == 'v') {
        let x = Math.ceil(obj_x * Proportion.value.x);
        let y =
          config.height -
          (config.height / 4) * index -
          Math.ceil(
            (obj_y - default_location[index].y) * Proportion.value.y
          );
        value[index].y = y > config.height ? config.height : y && y < 0 ? 0 : y;
        send_configuration(index, y)
      }
    }
    const options_v: any = reactive([]);
    const options_h: any = reactive([]);
    const options_model_v = ref(0)
    const options_model_h = ref(5)
    for (let index = 0; index < 5; index++) {
      options_v.push({ "label": `v${index + 1}`, value: index })
      options_h.push({ "label": `h${index + 1}`, value: index + 5 })
    }
    return {
      options_model_v,
      options_model_h,
      options_v,
      options_h,
      config,
      now_adjust,
      set_cache,
      chang,
      max_x_y,
      dragStartHandle,
      now_index,
      model,
      value,
      reset,
      resetall,
      point_postion,
      div,
      save,
    };
  },
});
</script>
