<template>
  <div class="row">
    <div class="col-1"></div>
    <div class="col-10 q-pt-md">
      <div ref="div" style="width: 100%; background-color: #646464; height: 40vh">
        <div style="position: absolute">
          <Vue3DraggableResizable :class="[options_model == index ? 'action' : 'point']"
            v-for="(item, index) in value_point.length" :initW="point.w" :initH="point.h" :resizable="false"
            v-model:x="value_point[index].x" v-model:y="value_point[index].y" @activated="options_model = index"
            @click="options_model = index" @dragging="dragStartHandle($event, index)">
            <span>{{
              index + 1
            }}</span>
          </Vue3DraggableResizable>
        </div>
      </div>
    </div>
  </div>
  <div v-show="ispad">
    <div class="row  q-md-py-xl">
      <div class="col-1"></div>
      <div class="col-2 q-px-md">
        <div class="col-2"> <q-select class="q-pt-md" :label="$t('point amount')"
            @update:model-value="(val) => { now_amount = val; chang_point_amount(val) }" :dense="true" filled
            v-model="value_point_amount" :options="options_value_point_amount" emit-value map-options />
        </div>
      </div>
      <div class="col-2">
        <div class="col-1 q-pt-md "><q-btn color="white"
            @click="() => { add_dialog = true; value_point_amount_tmp = value_point_amount; now_amount = value_point_amount }"
            text-color="black" :label="$t('add control points')" /></div>
      </div>
      <div class="col-2">

        <div class="col-1 q-pt-md "><q-btn color="white" @click="() => { del_dialog = true }"
            :disable="value_point_amount <= 9" text-color="black" :label="$t('reduce control points')" /></div>

      </div>

      <div class="q-pt-md q-px-md col-4"> <q-btn color="white" @click="resetall_all" text-color="black"
          :label="$t('Reset all program control points')" /></div>
    </div>
    <div class="row">
      <div class="col-1"></div>
      <div class="col-2 q-px-md" @mousewheel="details_selsect"> <q-select class="q-pt-md" :label="$t('point')"
          :dense="true" filled v-model="options_model" @update:model-value="(val) => { options_model = val }"
          :options="options" emit-value map-options /></div>
      <div class="col-2 q-px-md" @mousewheel="details_selsect_val($event, 'x')"> <q-input v-if="value[options_model]"
          filled type="number" class="q-pt-md" :dense="true" v-model="value[options_model].x"
          @update:model-value="chang(options_model, $event, 'h')" label="x" lazy-rules
          @click="() => { url.indexOf('pad') != -1 ? ipad_chang = true : '' }" :readonly="url.indexOf('pad') != -1" />
      </div>
      <div class="col-2 q-px-md" @mousewheel="details_selsect_val($event, 'y')"><q-input v-if="value[options_model]"
          filled type="number" class="q-pt-md" :dense="true" v-model="value[options_model].y"
          @update:model-value="chang(options_model, $event, 'h')" label="y" lazy-rules
          @click="() => { url.indexOf('pad') != -1 ? ipad_chang = true : '' }" :readonly="url.indexOf('pad') != -1" />
      </div>
      <div class="q-pt-md col-2">
        <q-btn color="white" @click="reset(options_model, true, 'h')" text-color="black" :label="$t('reset')" />

      </div>
      <div class="q-pt-md q-px-md col-3"> <q-btn color="white" @click="resetall" text-color="black"
          :label="$t('reset all') + value_point_amount + $t('point')" /></div>
    </div>
  </div>

  <div v-show="!ispad">
    <div style="display: flex;justify-content: space-around;">
      <div style="min-width: 100px;"> <q-select class="q-pt-md" :label="$t('point amount')"
          @update:model-value="(val) => { now_amount = val; chang_point_amount(val) }" :dense="true" filled
          v-model="value_point_amount" :options="options_value_point_amount" emit-value map-options />
      </div>
      <div class=" q-pt-md "><q-btn color="white"
          @click="() => { add_dialog = true; value_point_amount_tmp = value_point_amount; now_amount = value_point_amount }"
          text-color="black" :label="$t('add control points')" /></div>
      <div class="q-pt-md "><q-btn color="white" @click="() => { del_dialog = true }" :disable="value_point_amount <= 9"
          text-color="black" :label="$t('reduce control points')" /></div>

      <div class="q-pt-md q-px-md "> <q-btn color="white" @click="resetall_all" text-color="black"
          :label="$t('Reset all program control points')" /></div>
    </div>

    <div style="display: flex;justify-content: space-around;">
      <div  style="min-width: 100px;" @mousewheel="details_selsect"> <q-select class="q-pt-md" :label="$t('point')" :dense="true"
          filled v-model="options_model" @update:model-value="(val) => { options_model = val }" :options="options"
          emit-value map-options /></div>
      <div class=" q-px-md" @mousewheel="details_selsect_val($event, 'x')"> <q-input v-if="value[options_model]" filled
          type="number" class="q-pt-md" :dense="true" v-model="value[options_model].x"
          @update:model-value="chang(options_model, $event, 'h')" label="x" lazy-rules
          @focus="input_x_focus=true" @blur="input_x_focus=false"
          @click="() => { url.indexOf('pad') != -1 ? ipad_chang = true : '' }" :readonly="url.indexOf('pad') != -1" >
          <template v-if="input_x_focus" v-slot:append>
          <q-icon name="arrow_upward" @mousedown="mousedown('+','x')" @mouseup="mouseup" />
          <q-icon name="arrow_downward"  @mousedown="mousedown('-','x')" @mouseup="mouseup"  />
        </template>
        </q-input>
      </div>
      <div class=" q-px-md" @mousewheel="details_selsect_val($event, 'y')"><q-input v-if="value[options_model]" filled
          type="number" class="q-pt-md" :dense="true" v-model="value[options_model].y"
          @update:model-value="chang(options_model, $event, 'h')" label="y" lazy-rules
          @focus="input_y_focus=true" @blur="input_y_focus=false"
          @click="() => { url.indexOf('pad') != -1 ? ipad_chang = true : '' }" :readonly="url.indexOf('pad') != -1" >
          <template v-if="input_y_focus" v-slot:append>
          <q-icon name="arrow_upward" @mousedown="mousedown('+','y')" @mouseup="mouseup" />
          <q-icon name="arrow_downward"  @mousedown="mousedown('-','y')" @mouseup="mouseup"  />
        </template>
        </q-input>
      </div>
      <div class="q-pt-md ">
        <q-btn color="white" @click="reset(options_model, true, 'h')" text-color="black" :label="$t('reset')" />

      </div>
      <div class="q-pt-md q-px-md "> <q-btn color="white" @click="resetall" text-color="black"
          :label="$t('reset all') + value_point_amount + $t('point')" /></div>
    </div>
  </div>


  <q-dialog v-model="del_dialog">
    <q-card style="width: 500px; max-width: 80vw;">
      <q-card-section>
        <div class="text-h6">{{ $t('confirm delete') }}</div>
      </q-card-section>
      <q-card-section class="q-pt-none">
        {{ $t('OK to delete you will lose the data you adjusted now') }}
      </q-card-section>
      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn flat :label="$t('Cancel')" color="primary" v-close-popup />
        <q-btn flat :label="$t('ok')" @click="del_control_points(value_point_amount)" color="primary" v-close-popup />
      </q-card-actions>
    </q-card>
  </q-dialog>



  <q-dialog position="bottom" v-model="add_dialog">
    <q-card style="width: 500px; max-width: 80vw;">
      <q-card-section>
        <div class="text-h6">{{ $t('Whether to add control points') }}</div>
      </q-card-section>
      <q-card-section class="q-pt-none">
        <div class="row">
          <div class="col-10"><q-input filled v-model="now_amount" min="3" disable type="number"
              :label="$t('Please enter the points you need to add')"
              @update:model-value="(val: any) => { preview(val) }" />
          </div>
          <div class="col-1 q-pa-sm"> <q-btn color="white" text-color="black" label="↑"
              @click="() => { preview(Math.sqrt(now_amount) + 1) }" /> </div>
          <div class="col-1 q-pa-sm"> <q-btn color="white" text-color="black" label="↓"
              @click="() => { preview(Math.sqrt(now_amount) - 1) }" /></div>
        </div>

      </q-card-section>
      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn flat :label="$t('Cancel')" @click="() => { preview(Math.sqrt(value_point_amount_tmp)) }" color="primary"
          v-close-popup />
        <q-btn flat :label="$t('ok')" @click="add" color="primary" v-close-popup />
      </q-card-actions>
    </q-card>
  </q-dialog>


  <q-dialog v-model="ipad_chang">
    <q-card style="width: 40vw; max-width: 80vw;">
      <q-card-section>
        <!-- <div class="text-h6">{{ $t('point') +(options_model+1 )}}</div> -->
        <div class="row">
          <div class="col-4"><q-select class="q-pt-md" :label="$t('point')" :dense="true" filled v-model="options_model"
              @update:model-value="(val) => { options_model = val }" :options="options" emit-value map-options /></div>
        </div>
      </q-card-section>
      <q-card-section class="q-pt-none">
        <div class="row">
          <div class="col-12" style="text-align: center;"><q-btn color="white" text-color="black" icon="keyboard_arrow_up"
              @touchstart="handlerTouchstart('y', '+')" @touchend="handlerTouchend" /></div>
        </div>
        <div class="row">
          <div class="col-6" style="text-align: center;"><q-btn color="white" text-color="black"
              icon="keyboard_arrow_left" @touchstart="handlerTouchstart('x', '-')" @touchend="handlerTouchend" /></div>
          <div class="col-6" style="text-align: center;"><q-btn color="white" text-color="black"
              icon="keyboard_arrow_right" @touchstart="handlerTouchstart('x', '+')" @touchend="handlerTouchend" /></div>
        </div>
        <div class="row">
          <div class="col-12" style="text-align: center;"><q-btn color="white" text-color="black"
              icon="keyboard_arrow_down" @touchstart="handlerTouchstart('y', '-')" @touchend="handlerTouchend" /></div>
        </div>
      </q-card-section>
      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn flat :label="$t('close')" color="primary" @click="ipad_chang = false" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.action {
  background-color: rgb(27, 180, 111);
  border-radius: 50%;
}

.point {
  background-color: rgb(186, 245, 245);
  border-radius: 50%;
}
</style>

 <!-- 取消浏览器自带的input箭头 使用q-input的图标实现  -->
<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
}
</style>


<script lang="ts">
import {
  defineComponent,
  onMounted,
  ref,
  computed,
  watch,
  nextTick,
  onBeforeUnmount,
  defineExpose
} from "vue";
import { useStore } from "src/store";
import { useI18n } from "vue-i18n";
import Vue3DraggableResizable from 'vue3-draggable-resizable'
import 'vue3-draggable-resizable/dist/Vue3DraggableResizable.css'


import DensityCorrection from "src/entities/DensityCorrection";
import DensityCorrectionPoint from "src/entities/DensityCorrectionPoint";
import { config } from "process";
import { QSelect, QInput, QBtn } from "quasar";
import { div } from "zrender/lib/core/vector";
import GlobalData from "src/common/GlobalData";
import { number } from "@intlify/core-base";

export default defineComponent({
  name: "ComponentDensityCorrection",
  components: {
    Vue3DraggableResizable
  },
  setup() {
    let set = GlobalData.getInstance().getCurrentClient();
    let $store = useStore();
    let $t = useI18n();
    const ste_status = ref(0);
    let allconfig = JSON.parse($store.state.fusion_configuration);

    const configselsect = computed(() => {
      return $store.state.selected_projector;
    });

    /**
     * 平板弹窗修改
     */
    const ipad_chang = ref(false)
    /**
     * 当前url路径
     */
    let url = window.location.href;

    //用于计算当前投影仪的索引
    let serverconfig = JSON.parse($store.state.fusion_configuration);
    const selectedprojector = computed(() => {
      return (
        $store.getters.GetTheCurrentlySelectedCamera[0] * serverconfig.col +
        $store.getters.GetTheCurrentlySelectedCamera[1]
      );
    });
    let config = JSON.parse($store.state.fusion_configuration).projectors[selectedprojector.value];
    const value_point_amount = ref(9)
    const del_dialog = ref(false)
    const add_dialog = ref(false)
    const now_amount = ref(9)
    const options_value_point_amount = ref(<string[]>[])

    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 use_server_config = () => {
      value_point_amount.value = Number(Object.keys(config.multi_curved_surface)[0])
      let a = value_point_amount.value
      value.value = []
      value_point.value = []
      for (let index = 0; index < config.multi_curved_surface[a].length; index++) {
        let tmp: DensityCorrectionPoint = config.multi_curved_surface[a][index];
        value.value.push(tmp)
        let x_y = coordinate_transformation_value_to_xy(tmp.x, tmp.y)
        let def_x_f = coordinate_transformation_value_to_xy(tmp.def_x, tmp.def_y)
        let tmp_point: DensityCorrectionPoint = {
          control_point: tmp.control_point,
          x: x_y.x,
          y: x_y.y,
          def_x: def_x_f.x,
          def_y: def_x_f.y
        }
        value_point.value.push(tmp_point)
      }
    }

    const use_set_cache = () => {
      if (set_cache.value[selectedprojector.value] != null) {
        let tmp = JSON.parse(set_cache.value[selectedprojector.value]);
        value_point_amount.value = tmp.value_point_amount
        deepcopy(value.value, tmp.value)
        deepcopy(value_point.value, tmp.value_point)
        recalculate_coordinates()
      }
    }

    const save_set_cache = () => {
      let tmp = { value: value.value, value_point_amount: value_point_amount.value, value_point: value_point.value }
      set_cache.value[selectedprojector.value] = JSON.stringify(tmp);
    }


    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();
        options_value_point_amount.value = Object.keys(config.multi_curved_surface)
        setTimeout(() => {
          set?.SetBlendingOption("blending_grids_control_point_count", `${value_point_amount.value}`)
        }, 100);
        setTimeout(() => {
          ste_status.value = 0;
        }, 120);
      },
      { deep: true }
    );


    const set_cache: any = ref([]);
    //值
    let value = ref(<DensityCorrection[]>[]);
    //位置
    let value_point = ref(<DensityCorrectionPoint[]>[]);
    /**
     * 当前选中的点的索引
     */
    const options_model = ref(0)

    const div = ref();
    const max = ref({ x: 0, y: 0 })
    const point = ref({ w: 20, h: 20 })

    watch(() => options_model, (newval, oldval) => {
      set?.SetBlendingOption("blending_grids_select_point", `9:${newval.value + 1}`)
    }, { deep: true })

    watch(() => value_point_amount, (newval, oldval) => {
      if (ste_status.value == 0) set?.SetBlendingOption("blending_grids_control_point_count", `${newval.value}`)
      options_model.value = 0
      save_set_cache()
    }, { deep: true })

    /**
     * 分辨率和页面的比例
     */
    let Proportion = ref({ x: 100, y: 1000 });
    nextTick(() => {
      max.value.x = div.value.offsetWidth
      max.value.y = div.value.offsetHeight
    })


    const chang_point_amount = (val: number) => {
      start_point(val)
      //use_set_cache()
    }

    const dragStartHandle = ($event: any, index: number) => {
      let obj_x = $event.x
      let obj_y = $event.y
      let tmp = coordinate_transformation_xy_to_value(obj_x, obj_y)
      value.value[index].x = Math.trunc(tmp.x)
      value.value[index].y = Math.trunc(tmp.y)
      send_value(index, Math.trunc(tmp.x), Math.trunc(tmp.y))
      save_set_cache()
    }

    const chang = (index: number, $event: any, type: string) => {
      index = Number(index)
      let tmp = coordinate_transformation_value_to_xy(value.value[index].x, value.value[index].y)
      value_point.value[index].y = Math.trunc(tmp.y)
      value_point.value[index].x = Math.trunc(tmp.x)
      send_value(index, Math.trunc(value.value[index].x), Math.trunc(value.value[index].y))

      save_set_cache()
    }
    const options = computed(() => {
      let tmp = []
      for (let index = 0; index < value_point.value.length; index++) {
        tmp.push({
          label: `${index + 1}`,
          value: index,
        })
      }
      return tmp
    })


    /**
     * 将分辨率的坐标转换为 页面的坐标
     * @param x x坐标
     * @param y y坐标
     */
    const coordinate_transformation_value_to_xy = (x: number, y: number): { x: number, y: number } => {
      x = x / Proportion.value.x
      y = (allconfig.projector_height - y) / Proportion.value.y
      return { x, y }
    }


    /**
     * 将页面的坐标转换为 分辨率的坐标
     * @param x x坐标
     * @param y y坐标
     */
    const coordinate_transformation_xy_to_value = (x: number, y: number): { x: number, y: number } => {
      x = x * Proportion.value.x
      y = (max.value.y - (y + point.value.h)) * Proportion.value.y
      return { x, y }
    }

    const start_point = (a: number) => {
      value.value = []
      value_point.value = []
      for (let index = 0; index < config.multi_curved_surface[a].length; index++) {
        let tmp: DensityCorrectionPoint = config.multi_curved_surface[a][index];
        value.value.push(tmp)
        let x_y = coordinate_transformation_value_to_xy(tmp.x, tmp.y)
        let def_x_f = coordinate_transformation_value_to_xy(tmp.def_x, tmp.def_y)
        let tmp_point: DensityCorrectionPoint = {
          control_point: tmp.control_point,
          x: x_y.x,
          y: x_y.y,
          def_x: def_x_f.x,
          def_y: def_x_f.y
        }
        value_point.value.push(tmp_point)
      }
      save_set_cache()
    }


    const start = () => {
      let tmp: DensityCorrectionPoint = { control_point: 0, x: 0, y: 0, def_x: 0, def_y: 0 };
      value.value.push(tmp)
      value_point.value.push(tmp)
    }
    start()
    onMounted(() => {
      Proportion.value.x = allconfig.projector_width / (div.value.offsetWidth - point.value.w)
      Proportion.value.y = allconfig.projector_height / (div.value.offsetHeight - point.value.h)

      start()
      use_server_config()
      options_value_point_amount.value = Object.keys(config.multi_curved_surface)
      start_point(Number(options_value_point_amount.value[0]))
      if (
        sessionStorage.SurfaceCorrection &&
        sessionStorage.SurfaceCorrection.length > 0
      ) {
        set_cache.value = JSON.parse(sessionStorage.SurfaceCorrection);
        use_set_cache();
      }
      keyDown()
      window.onresize = () => {
        return (() => {
          if (div != null) {
            recalculate_coordinates()
          }
        })();
      };
    })

    onBeforeUnmount(() => {
      sessionStorage.SurfaceCorrection = JSON.stringify(set_cache.value);
    });

    const reset = (index: number, send: boolean, type: string) => {
      value.value[index].x = value.value[index].def_x
      value.value[index].y = value.value[index].def_y
      chang(index, value.value[index].def_y, type)
      save_set_cache()
    }
    const send_value = (index: number, x: number, y: number) => {
      let row = $store.getters.GetTheCurrentlySelectedCamera[0]
      let col = $store.getters.GetTheCurrentlySelectedCamera[1]
      set?.setBlendingCorrection(row, col, 9, value_point.value.length, index + 1, Number(x), Number(y));
    }
    const resetall = () => {
      for (let index = 0; index < value_point.value.length; index++) {
        value.value[index].x = value.value[index].def_x
        value.value[index].y = value.value[index].def_y
        let tmp = coordinate_transformation_value_to_xy(value.value[index].x, value.value[index].y)
        value_point.value[index].y = Math.trunc(tmp.y)
        value_point.value[index].x = Math.trunc(tmp.x)
      }
      send_value(-1, 0, 0)
      save_set_cache()
    }
    const resetall_all = () => {
      let amount_tmp = value_point_amount.value
      for (let index = 0; index < value_point.value.length; index++) {
        value.value[index].x = value.value[index].def_x
        value.value[index].y = value.value[index].def_y
        let tmp = coordinate_transformation_value_to_xy(value.value[index].x, value.value[index].y)
        value_point.value[index].y = Math.trunc(tmp.y)
        value_point.value[index].x = Math.trunc(tmp.x)
      }
      send_value(-2, 0, 0)

      for (let key in config.multi_curved_surface) {
        for (let index = 0; index < config.multi_curved_surface[key].length; index++) {
          config.multi_curved_surface[key][index].x = config.multi_curved_surface[key][index].def_x
          config.multi_curved_surface[key][index].y = config.multi_curved_surface[key][index].def_y
        }
        start_point(Number(key))
      }
      value_point_amount.value = amount_tmp
      start_point(Number(value_point_amount.value))

    }
    const recalculate_coordinates = () => {
      try {
        Proportion.value.x = allconfig.projector_width / (div.value.offsetWidth - point.value.w)
        Proportion.value.y = allconfig.projector_height / (div.value.offsetHeight - point.value.h)
        max.value.x = div.value.offsetWidth
        max.value.y = div.value.offsetHeight
        for (let index = 0; index < value.value.length; index++) {
          let x_y = coordinate_transformation_value_to_xy(value.value[index].x, value.value[index].y)
          let def_x_y = coordinate_transformation_value_to_xy(value.value[index].def_x, value.value[index].def_y)
          value_point.value[index].x = x_y.x
          value_point.value[index].y = x_y.y
          value_point.value[index].def_x = def_x_y.x
          value_point.value[index].def_y = def_x_y.y
        }
      } catch (error) {

      }
    }
    const add_control_points = (amount: number) => {
      if (amount < 9) return
      let cardinality = Math.sqrt(amount)
      amount = (cardinality + 1) ** 2
      let tmpconfig: any = null
      let row = $store.getters.GetTheCurrentlySelectedCamera[0]
      let col = $store.getters.GetTheCurrentlySelectedCamera[1]

      set?.AddBlendingCtrlPoint('9', row, col, amount).then((res) => {
        if (res == null || typeof (res) == "undefined") return
        let tmp = JSON.parse(res?.config);
        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;
        tmpconfig = JSON.parse(JSON.stringify(fortmp));
        config = fortmp
        options_value_point_amount.value = []
        for (let key in tmpconfig.multi_curved_surface) {
          options_value_point_amount.value.push(key)
        }
        value_point_amount.value = amount
        config = tmpconfig
        $store.commit("setfusion_configuration", res?.config);
        value.value = []
        value_point.value = []
        for (let index = 0; index < tmpconfig.multi_curved_surface[amount].length; index++) {
          let tmp: DensityCorrectionPoint = tmpconfig.multi_curved_surface[amount][index];
          value.value.push(tmp)
          let x_y = coordinate_transformation_value_to_xy(tmp.x, tmp.y)
          let def_x_f = coordinate_transformation_value_to_xy(tmp.def_x, tmp.def_y)
          let tmp_point: DensityCorrectionPoint = {
            control_point: tmp.control_point,
            x: x_y.x,
            y: x_y.y,
            def_x: def_x_f.x,
            def_y: def_x_f.y
          }
          value_point.value.push(tmp_point)
        }
      });
      save_set_cache()
    }
    const del_control_points = (amount: number) => {
      let tmp = amount
      if (amount <= 9) return
      let cardinality = Math.sqrt(amount)
      amount = (cardinality + -1) ** 2
      let tmpconfig: any = null
      let row = $store.getters.GetTheCurrentlySelectedCamera[0]
      let col = $store.getters.GetTheCurrentlySelectedCamera[1]

      set?.DelBlendingCtrlPoint('9', row, col, Number(tmp)).then((res) => {
        if (res == null || typeof (res) == "undefined") return
        let tmp = JSON.parse(res?.config);
        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;
        tmpconfig = JSON.parse(JSON.stringify(fortmp));
        config = JSON.parse(JSON.stringify(fortmp));
        options_value_point_amount.value = []
        for (let key in tmpconfig.multi_curved_surface) {
          options_value_point_amount.value.push(key)
        }
        value_point_amount.value = Number(options_value_point_amount.value[0])
        amount = Number(options_value_point_amount.value[0])
        now_amount.value = Number(options_value_point_amount.value[0])
        $store.commit("setfusion_configuration", res?.config);
        value.value = []
        value_point.value = []
        for (let index = 0; index < tmpconfig.multi_curved_surface[amount].length; index++) {
          let tmp: DensityCorrectionPoint = tmpconfig.multi_curved_surface[amount][index];
          value.value.push(tmp)
          let x_y = coordinate_transformation_value_to_xy(tmp.x, tmp.y)
          let def_x_f = coordinate_transformation_value_to_xy(tmp.def_x, tmp.def_y)
          let tmp_point: DensityCorrectionPoint = {
            control_point: tmp.control_point,
            x: x_y.x,
            y: x_y.y,
            def_x: def_x_f.x,
            def_y: def_x_f.y
          }
          value_point.value.push(tmp_point)
        }

      });
      save_set_cache()
    }
    const add = () => {
      let tmpconfig: any = null
      let row = $store.getters.GetTheCurrentlySelectedCamera[0]
      let col = $store.getters.GetTheCurrentlySelectedCamera[1]
      let amount = now_amount.value
      set?.AddBlendingCtrlPoint('9', row, col, Number(amount)).then((res) => {
        if (res == null || typeof (res) == "undefined") return
        let tmp = JSON.parse(res?.config);
        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;
        tmpconfig = JSON.parse(JSON.stringify(fortmp));
        config = JSON.parse(JSON.stringify(fortmp));
        options_value_point_amount.value = []
        for (let key in tmpconfig.multi_curved_surface) {
          options_value_point_amount.value.push(key)
        }

        value_point_amount.value = amount
        $store.commit("setfusion_configuration", res?.config);
        value.value = []
        value_point.value = []
        for (let index = 0; index < tmpconfig.multi_curved_surface[amount].length; index++) {
          let tmp: DensityCorrectionPoint = tmpconfig.multi_curved_surface[amount][index];
          value.value.push(tmp)
          let x_y = coordinate_transformation_value_to_xy(tmp.x, tmp.y)
          let def_x_f = coordinate_transformation_value_to_xy(tmp.def_x, tmp.def_y)
          let tmp_point: DensityCorrectionPoint = {
            control_point: tmp.control_point,
            x: x_y.x,
            y: x_y.y,
            def_x: def_x_f.x,
            def_y: def_x_f.y
          }
          value_point.value.push(tmp_point)
        }
      });
      set?.SetBlendingOption("blending_grids_control_point_count", `${value_point_amount.value}`)
      save_set_cache()
    }
    const preview = (val: number) => {
      val = Number(val)
      if (val < 3) return
      let width = allconfig.projector_width / (val - 1)
      let height = allconfig.projector_height / (val - 1)
      value.value = []
      value_point.value = []
      for (let index = 0; index < val; index++) {
        for (let indexx = 0; indexx < val; indexx++) {
          let y = allconfig.projector_height - height * index
          let x = width * indexx
          let tmp: DensityCorrectionPoint = { x, y, def_x: x, def_y: y, control_point: index + indexx + 1 };
          value.value.push(tmp)
          let x_y = coordinate_transformation_value_to_xy(tmp.x, tmp.y)
          let def_x_f = coordinate_transformation_value_to_xy(tmp.def_x, tmp.def_y)
          let tmp_point: DensityCorrectionPoint = {
            control_point: tmp.control_point,
            x: x_y.x,
            y: x_y.y,
            def_x: def_x_f.x,
            def_y: def_x_f.y
          }
          value_point.value.push(tmp_point)
        }
      }
      now_amount.value = val ** 2
      value_point_amount.value = val ** 2
      options_model.value = 1
      save_set_cache()
    }

    /**
     *  滚轮切换
     * @param details 鼠标返回对象
     */
    const details_selsect = (details: any) => {
      let spt = details.deltaY / 100
      if (spt > 0) {
        if (options_model.value >= value_point.value.length - 1) {
          options_model.value = 0
        } else {
          options_model.value++
        }
      } else {
        if (options_model.value <= 1) {
          options_model.value = value_point.value.length - 1
        } else {
          options_model.value--
        }

      }
    }

    /**
     * 滚轮改变数据
     */
    const details_selsect_val = (details: any, type: string) => {
      let spt = details.deltaY / 100
      switch (type) {
        case 'x':
          if (spt < 0) {
            value.value[options_model.value].x++
          } else {
            value.value[options_model.value].x--
          }
          break;
        default:
          if (spt < 0) {
            value.value[options_model.value].y++
          } else {
            value.value[options_model.value].y--
          }
          break;
      }
      chang(options_model.value, "", "")
    }
    /**
     * 在增加时 实现回退
     */
    const value_point_amount_tmp = ref(0)
    /**
    * 长按实现
    */
    let loop: NodeJS.Timeout
    let loop_end: NodeJS.Timeout
    const handlerTouchstart = (type: string, fun: string) => {
      loop_end = setTimeout(() => {
        loop = setInterval(() => {
          if (type == 'x') {
            if (fun == '+') {
              value.value[options_model.value].x++
            } else {
              value.value[options_model.value].x--
            }

          } else {
            if (fun == '+') {
              value.value[options_model.value].y++
            } else {
              value.value[options_model.value].y--
            }
          }
          chang(options_model.value, 0, '')
        }, 30)
      }, 1000);
      if (type == 'x') {
            if (fun == '+') {
              value.value[options_model.value].x++
            } else {
              value.value[options_model.value].x--
            }

          } else {
            if (fun == '+') {
              value.value[options_model.value].y++
            } else {
              value.value[options_model.value].y--
            }
          }
          chang(options_model.value, 0, '')
    }
    const handlerTouchend = () => {
      clearTimeout(loop_end)
      clearInterval(loop)
    }
    /**
     * 键盘监听
     */
    const keyDown = () => {
      document.onkeydown = (e) => {
        let lock = 0;
        let e1 = e || window.event || arguments.callee.caller.arguments[0]
        switch (e.code) {
          case "KeyW":
            value.value[options_model.value].y++
            break;
          case "KeyA":
            value.value[options_model.value].x--
            break;
          case "KeyS":
            value.value[options_model.value].y--
            break;
          case "KeyD":
            value.value[options_model.value].x++
            break;
          default:
            lock = 1
            break;
        }
        if (lock == 0) chang(options_model.value, "h", 'h')
      }
    }


    const ispad = computed(() => {
      let url = window.location.href;
      return url.indexOf("pad") != -1
    })


    let loop_start: NodeJS.Timeout
    let loop_finish: NodeJS.Timeout

    const mousedown = (fun: string, type: string) => {
      loop_start = setTimeout(() => {
        loop_finish = setInterval(() => {
          switch (type) {
            case 'x':
              if (fun == '+') {
                value.value[options_model.value].x++
              } else {
                value.value[options_model.value].x--
              }
              break;

            default:
              if (fun == '+') {
                value.value[options_model.value].y++
              } else {
                value.value[options_model.value].y--
              }
              break;
          }
          chang(options_model.value, 0, '')
        }, 30)
      }, 1000);
      switch (type) {
        case 'x':
          if (fun == '+') {
            value.value[options_model.value].x++
          } else {
            value.value[options_model.value].x--
          }
          break;

        default:
          if (fun == '+') {
            value.value[options_model.value].y++
          } else {
            value.value[options_model.value].y--
          }
          break;
      }
      chang(options_model.value, 0, '')
    }

    const mouseup = () => {
      clearTimeout(loop_start)
      clearInterval(loop_finish)
    }


    const input_x_focus=ref(false)
    const input_y_focus=ref(false)










    defineExpose({
      options_model,
    });
    return {
       input_x_focus,
     input_y_focus,
      ispad,
      mousedown,
      mouseup,
      value_point_amount_tmp,
      details_selsect,
      resetall_all,
      resetall,
      div,
      max,
      point,
      options_model,
      value,
      value_point,
      dragStartHandle,
      chang,
      options,
      reset,
      options_value_point_amount,
      value_point_amount,
      chang_point_amount,
      del_dialog,
      add_control_points,
      del_control_points,
      add_dialog,
      add,
      now_amount,
      preview,
      details_selsect_val,
      ipad_chang,
      url,
      handlerTouchstart,
      handlerTouchend
    }
  }
})

</script>
