<template>
  <div class="row">
    <div class="col-12">
      <div style="height: 1rem"></div>
      <div class="row">
        <div class="col-12">
          <div class="row">
            <div class="col-4 offset-4">
              <div class="row">
                <div class="col-3">
                  <q-toggle class="float-right" v-model="array[0].isshow" label="" />
                </div>
                <div class="col-6">
                  <q-input dense filled type="number" :autofocus="group == 0" :bg-color="group == 0 ? 'cyan-1' : ''"
                    @focus="group = 0" v-model="array[0].value" :label="$t('upper fusion zone parameters')" lazy-rules
                    :rules="[
                      (val) =>
                        (val !== null && val !== '') ||
                        $t('Please enter a number'),
                      (val) =>
                        (val >= 0 && val < config.height) || $t('Please enter 0-100'),
                    ]" />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-12">
          <div class="row">
            <div class="col-6">
              <div class="row">
                <div class="col-3">
                  <q-toggle class="float-right" v-model="array[1].isshow" label="" />
                </div>
                <div class="col-6">
                  <q-input dense filled type="number" :autofocus="group == 1" :bg-color="group == 1 ? 'cyan-1' : ''"
                    @focus="group = 1" v-model="array[1].value" :label="$t('Left fusion Band Parameters')" lazy-rules
                    :rules="[
                      (val) =>
                        (val !== null && val !== '') ||
                        $t('Please enter a number'),
                      (val) =>
                        (val >= 0 && val < config.width) || $t('Please enter 0-100'),
                    ]" />
                </div>
              </div>
            </div>
            <div class="col-6">
              <div class="row">
                <div class="col-3">
                  <q-toggle class="float-right" v-model="array[2].isshow" label="" />
                </div>
                <div class="col-6">
                  <q-input dense filled type="number" :autofocus="group == 2" :bg-color="group == 2 ? 'cyan-1' : ''"
                    @focus="group = 2" v-model="array[2].value" :label="$t('Right fusion Band Parameters')" lazy-rules
                    :rules="[
                      (val) =>
                        (val !== null && val !== '') ||
                        $t('Please enter a number'),
                      (val) =>
                        (val >= 0 && val < config.width) || $t('Please enter 0-100'),
                    ]" />
                </div>
                <div class="col-3"><span>{{ $t('Whether to operate synchronously') }}</span><q-checkbox
                    v-model="auto_sync" /></div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-12">
          <div class="row">
            <div class="col-4 offset-4">
              <div class="row">
                <div class="col-3">
                  <q-toggle class="float-right" v-model="array[3].isshow" label="" />
                </div>
                <div class="col-6">
                  <q-input dense filled type="number" :autofocus="group == 3" :bg-color="group == 3 ? 'cyan-1' : ''"
                    @focus="group = 3" v-model="array[3].value" :label="$t('Lower fusion Zone Parameters')" lazy-rules
                    :rules="[
                      (val) =>
                        (val !== null && val !== '') ||
                        $t('Please enter a number'),
                      (val) =>
                        (val >= 0 && val < config.height) || $t('Please enter 0-100'),
                    ]" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-12" v-if="group != 4">
      <p class="text-center" style="margin: 0 0 8;">{{ $t("Set Fusion Band Parameters") }}</p>
      <div style="display: flex; justify-content: space-evenly">
        <div>
          <q-slider v-model="array[group].alpha" :min="0.0" @change="chang('alpha')" :max="1" :step="0.01" color="green"
            vertical reverse label-always />
          <div> <q-input dense filled type="number" max="1" min="0"   step="0.1" v-model="array[group].alpha" label="alpha"
              lazy-rules :rules="[
                (val) =>
                  (val !== null && val !== '') ||
                  $t('Please enter a number'),
                (val) =>
                  (val >= 0 && val <= 1) || $t('Please enter a value within the range'),
              ]" /></div>
          <p class="text-center">alpha</p>
        </div>

        <div>
          <q-slider  v-model="array[group].p" :min="0" @change="chang('p')" :max="16" :step="0.01" color="green"
            vertical reverse label-always />
          <div> <q-input dense filled type="number" max="16" min="0" step="0.1" v-model="array[group].p" label="p"
              lazy-rules :rules="[
                (val) =>
                  (val !== null && val !== '') ||
                  $t('Please enter a number'),
                (val) =>
                  (val >= 0 && val <= 16) || $t('Please enter a value within the range'),
              ]" /></div>
          <p class="text-center">p</p>
        </div>

        <div>
          <q-slider  v-model="array[group].gamma" :min="0" @change="chang('gamma')" :max="16" :step="0.01" color="green" vertical reverse label-always />
          <div> <q-input dense filled type="number" max="16" min="0"  step="0.1" v-model="array[group].gamma" label="gamma"
              lazy-rules :rules="[
                (val) =>
                  (val !== null && val !== '') ||
                  $t('Please enter a number'),
                (val) =>
                  (val >= 0 && val <= 16) || $t('Please enter 0-100'),
              ]" /></div>
          <p class="text-center">gamma</p>
        </div>
      </div>
    </div>
  </div>
  <div>
    <q-btn color="white" @click="resetall" text-color="black" :label="$t('resetall')" />
  </div>
</template>

<style>
.boder {
  border: 2px solid #0000;
}
.btn_bottom{
  margin-bottom: 0.5rem;
}
.btn_top{
  margin-top: 0.3rem;
}

</style>

<script lang="ts">
import {
  defineComponent,
  ref,
  watch,
  computed,
  defineProps,
  withDefaults,
  onBeforeUnmount,
  reactive,
onMounted,
} from "vue";
import { useStore } from "src/store";
import { useI18n } from "vue-i18n";
import GlobalData from "src/common/GlobalData";
import { number } from "@intlify/core-base";
import { switchCase } from "@babel/types";

export default defineComponent({
  name: "ComponentFusionLocale",
  setup() {
    let set = GlobalData.getInstance().getCurrentClient();
    let $store = useStore();
    let $t = useI18n();
    const group = ref(4);
    const set_cache: any = ref([]);
    const enablefusion = ref(false);
    let array: any = reactive([
      { alpha: 0, p: 0, gamma: 0, isshow: false, value: 0 },
      { alpha: 0, p: 0, gamma: 0, isshow: false, value: 0 },
      { alpha: 0, p: 0, gamma: 0, isshow: false, value: 0 },
      { alpha: 0, p: 0, gamma: 0, isshow: false, value: 0 },
      { alpha: 0, p: 0, gamma: 0, isshow: false, value: 0 },
    ]);
    const auto_sync = ref(false)
    //正确的 索引编号
    let arr = [1, 0, 2, 3];
    let serverconfig = JSON.parse($store.state.fusion_configuration);
    const selectedprojector = computed(() => {
      return (
        $store.getters.GetTheCurrentlySelectedCamera[0] * serverconfig.col +
        $store.getters.GetTheCurrentlySelectedCamera[1]
      );
    });
    const add = (type: string) => {
      let tmp: Number;
      tmp = 0.01;
      switch (type) {
        case "alpha":
          array[group.value].alpha = Number((array[group.value].alpha += tmp).toFixed(2))
          break;
        case "p":
          array[group.value].p = Number((array[group.value].p += tmp).toFixed(2))
          break;
        case "gamma":
          array[group.value].gamma = Number((array[group.value].gamma += tmp).toFixed(2))
          break;
        default:
          break;
      }
      chang(type)
      save_set_cache()
    }
    const reduce = (type: string) => {
      let tmp: Number;
      tmp = -0.01;
      switch (type) {
        case "alpha":
          array[group.value].alpha = Number((array[group.value].alpha += tmp).toFixed(2))
          break;
        case "p":
          array[group.value].p = Number((array[group.value].p += tmp).toFixed(2))
          break;
        case "gamma":
          array[group.value].gamma = Number((array[group.value].gamma += tmp).toFixed(2))
          break;
        default:
          break;
      }
      chang(type)
      save_set_cache()
    }
    const ste_status = ref(0);
    const use_set_cache = () => {
      if (set_cache.value[selectedprojector.value] != null) {
        let tmp = JSON.parse(set_cache.value[selectedprojector.value]);
        deepcopy(array, tmp);
      }
    };
    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(array);
    };
    let config = JSON.parse($store.state.fusion_configuration).projectors[0];
    const configselsect = computed(() => {
      return $store.state.selected_projector;
    });
    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);
        setnowindex();
      },
      { deep: true }
    );

    const chang = (type: string) => {
      if (type == "alpha") {
        if ($store.state.enablefusion)
          set?.setBlendingAlphaParam(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            arr[group.value],
            Number(array[group.value].alpha)
          );
      }
      if (type == "p") {
        if ($store.state.enablefusion)
          set?.setBlendingPowerParam(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            arr[group.value],
            Number(array[group.value].p)
          );
      }
      if (type == "gamma") {
        if ($store.state.enablefusion)
          set?.setBlendingGammaParam(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            arr[group.value],
            Number(array[group.value].gamma)
          );
      }
      save_set_cache();
    };
    //左上右下
    const setnowindex = () => {
      let sum = 0;
      let indexx = 4;
      for (let index = 0; index < array.length - 1; index++) {
        if (array[index].isshow && Number(array[index].value) > 0) {
          sum++;
          indexx = index;
        }
      }
      if (sum == 1) {
        group.value = indexx;
      } else {
        group.value = 4;
      }
    };

    const setconfig = (config: any) => {
      let tmp = JSON.parse(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;
      config = JSON.parse(JSON.stringify(fortmp));
      for (let index = 0; index < array.length - 1; index++) {
        array[arr[index]].gamma = Number(config.params[index].gamma.toFixed(2));
        array[arr[index]].alpha = Number(config.params[index].alpha.toFixed(2));
        array[arr[index]].p = Number(config.params[index].power.toFixed(2));
        array[arr[index]].isshow = config.params[index].enable;
        array[arr[index]].value = Number(config.params[index].size);
      }

      setTimeout(() => {
        ste_status.value = 0;
      }, 100);
      setnowindex();
    };
    const startconfig = () => {
      for (let index = 0; index < array.length - 1; index++) {
        array[arr[index]].gamma = Number(config.params[index].gamma.toFixed(2));
        array[arr[index]].alpha = Number(config.params[index].alpha.toFixed(2));
        array[arr[index]].p = Number(config.params[index].power.toFixed(2));
        array[arr[index]].isshow = config.params[index].enable;
        array[arr[index]].value = Number(config.params[index].size);
      }
      if (sessionStorage.FusionLocale)set_cache.value = JSON.parse(sessionStorage.FusionLocale);
      use_set_cache();
      setnowindex();
    };
    const use_server_config = () => {
      for (let index = 0; index < array.length - 1; index++) {
        array[arr[index]].gamma = Number(config.params[index].gamma.toFixed(2));
        array[arr[index]].alpha = Number(config.params[index].alpha.toFixed(2));
        array[arr[index]].p = Number(config.params[index].power.toFixed(2));
        array[arr[index]].isshow = config.params[index].enable;
        array[arr[index]].value = Number(config.params[index].size);
      }
    };
    onMounted(() => {
      startconfig();
    }),
    onBeforeUnmount(() => {
      sessionStorage.FusionLocale = JSON.stringify(set_cache.value);
    });

    watch(
      () => array[0].value,
      (newVal, oldVal) => {
        if ($store.state.enablefusion)
          set?.SetBlendingOverlap(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            1,
            array[0].isshow,
            Number(array[0].value)
          );

        save_set_cache();
      },
      { deep: true }
    );
    watch(
      () => array[1].value,
      (newVal, oldVal) => {
        if ($store.state.enablefusion)
          set?.SetBlendingOverlap(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            0,
            array[1].isshow,
            Number(array[1].value)
          );
        if (auto_sync.value) left_right_auto_add(newVal);
        save_set_cache();
      },
      { deep: true }
    );
    watch(
      () => array[2].value,
      (newVal, oldVal) => {
        if ($store.state.enablefusion)
          set?.SetBlendingOverlap(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            2,
            array[2].isshow,
            Number(array[2].value)
          );
        if (auto_sync.value) left_right_auto_add(newVal);
        save_set_cache();
      },
      { deep: true }
    );
    watch(
      () => array[3].value,
      (newVal, oldVal) => {
        if ($store.state.enablefusion)
          set?.SetBlendingOverlap(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            3,
            array[3].isshow,
            Number(array[3].value)
          );
        save_set_cache();
      },
      { deep: true }
    );


    watch(
      () => array[0].isshow,
      (newVal, oldVal) => {
        if ($store.state.enablefusion)
          set?.SetBlendingOverlap(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            1,
            array[0].isshow,
            Number(array[0].value)
          );
        save_set_cache();
      },
      { deep: true }
    );
    watch(
      () => array[1].isshow,
      (newVal, oldVal) => {
        if ($store.state.enablefusion)
          set?.SetBlendingOverlap(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            0,
            array[1].isshow,
            Number(array[1].value)
          );
        if (auto_sync.value) left_right_auto_add(-1);
        save_set_cache();
      },
      { deep: true }
    );
    watch(
      () => array[2].isshow,
      (newVal, oldVal) => {
        if ($store.state.enablefusion)
          set?.SetBlendingOverlap(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            2,
            array[2].isshow,
            Number(array[2].value)
          );
        if (auto_sync.value) left_right_auto_add(-1);
        save_set_cache();
      },
      { deep: true }
    );
    watch(
      () => array[3].isshow,
      (newVal, oldVal) => {
        if ($store.state.enablefusion)
          set?.SetBlendingOverlap(
            $store.getters.GetTheCurrentlySelectedCamera[0],
            $store.getters.GetTheCurrentlySelectedCamera[1],
            3,
            array[3].isshow,
            Number(array[3].value)
          );
        save_set_cache();
      },
      { deep: true }
    );


    watch(
      () => enablefusion,
      (newVal, oldVal) => {
        $store.commit("setenablefusion", newVal.value);
        set?.EnableBlending(newVal.value);
      },
      { deep: true }
    );
    const changenablefusion = () => {
      $store.commit("setenablefusion", enablefusion.value);
    };
    let resnewdata = null;
    const resetall = () => {
      try {
        set?.GetBlendingConfig("").then((res) => {
          resnewdata = res?.config;
          setconfig(resnewdata);
        });
      } catch (error) {
        console.log("ResetBlendingConfig error");
      }
    };
    const left_right_auto_add = (difference: number) => {

      let tmpobjall = JSON.parse($store.state.fusion_configuration)
      if ($store.getters.GetTheCurrentlySelectedCamera[1] == 0) {

        let tmp = set_cache.value[1] == null ? tmpobjall.projectors[1].params : JSON.parse(set_cache.value[1]);
        let set_cache_tmp: any = []
        if (tmp[1].hasOwnProperty("power")) {
          for (let index = 0; index < 4; index++) {
            let tmpobj = { alpha: Number(tmp[arr[index]].alpha.toFixed(2)), p: Number(tmp[arr[index]].power.toFixed(2)), gamma: Number(tmp[arr[index]].gamma.toFixed(2)), isshow: tmp[arr[index]].enable, value: Number(tmp[arr[index]].size) }
            set_cache_tmp.push(tmpobj)
          }
        } else {
          set_cache_tmp = tmp
        }
        if (ste_status.value == 0) {
          //set_cache_tmp[1].value = Number(set_cache_tmp[1].value) + difference

          if(difference==-1){
            set_cache_tmp[1].isshow = array[2].isshow
          }else{
            set_cache_tmp[1].value = difference
          }
          set?.SetBlendingOverlap(0, 1, 0, set_cache_tmp[1].isshow, Number(set_cache_tmp[1].value));
          set_cache.value[1] = JSON.stringify(set_cache_tmp);
        }
      }
      if ($store.getters.GetTheCurrentlySelectedCamera[1] == 1) {

        let tmp = set_cache.value[0] == null ? tmpobjall.projectors[0].params : JSON.parse(set_cache.value[0]);
        let set_cache_tmp: any = []
        if (tmp[0].hasOwnProperty("power")) {
          for (let index = 0; index < 4; index++) {
            let tmpobj = { alpha: Number(tmp[arr[index]].alpha.toFixed(2)), p: Number(tmp[arr[index]].power.toFixed(2)), gamma: Number(tmp[arr[index]].gamma.toFixed(2)), isshow: tmp[arr[index]].enable, value: Number(tmp[arr[index]].size) }
            set_cache_tmp.push(tmpobj)
          }
        } else {
          set_cache_tmp = tmp
        }
        if (ste_status.value == 0) {
          //set_cache_tmp[2].value = Number(set_cache_tmp[2].value) + difference

          if(difference==-1){
            set_cache_tmp[2].isshow = array[1].isshow
          }else{
            set_cache_tmp[2].value = difference
          }
          set?.SetBlendingOverlap(0, 0, 2, set_cache_tmp[2].isshow, Number(set_cache_tmp[2].value));
          set_cache.value[0] = JSON.stringify(set_cache_tmp);
        }
      }
    }
    return {
      group,
      array,
      chang,
      enablefusion,
      changenablefusion,
      selectedprojector,
      resetall,
      set_cache,
      reduce,
      add,
      auto_sync,
      config
    };
  },
});
</script>
