<template>
  <q-dialog persistent v-model="show_dialog" @keydown="
    (evt: any) => {
      if (evt.keyCode == 27) {
        show_dialog = false;
      }
      if (evt.keyCode == 17) {
        record_times++
      }
    }
  ">
    <q-card class="" style="max-width: 90vw;padding: 0;">
      <q-form>
        <q-card-section class="q-ma-none q-pa-sm">
          <div class="row">
            <div class="col-auto text-h6">
              {{ $t("fusion settings") }}
            </div>

            <q-space />
            <q-btn size="sm" dense flat round icon="close" color="red" @click="clear()" v-close-popup>
              <q-tooltip>
                {{ $t("close") }}
              </q-tooltip>
            </q-btn>
          </div>
        </q-card-section>

        <q-separator />
        <!-- height: 80vh -->
        <q-card-section class="scroll" style="width: 60vw;padding: 0;">
          <div class="row" style="border: 1px solid #b0bec5; text-align: center">
            <div class="col-2" style="border-right: 1px solid #b0bec5">
              <p class="text-center">{{ $t("Projector") }}</p>
              <!-- row 在前col在后 -->
              <div v-for="(item, index_row) in config.row">
                <projector-item v-for="(item, index_col) in config.col" class="w-100" :llabel="
                  $t('Projector') + (index_row * config.col + index_col + 1)
                " :lvalue="index_row + '/' + index_col"
                  @click="currently_selected_projector(index_row + '-' + index_col)"></projector-item>
              </div>

              <div class="col-12" style="text-align: center">
                {{
                  $t("Whether to enable integration")
                }}<q-checkbox v-model="EnableBlending" />
              </div>
            </div>
            <div class="col-10">
              <div class="q-ta-md">
                <q-btn-toggle :disable="!$store.state.enablefusion" no-caps v-model="options" toggle-color="primary"
                  :options="[
                    { label: $t('FusionLocale'), value: 'FusionLocale' },
                    {
                      label: $t('FourPointCalibration'),
                      value: 'FourPointCalibration',
                    },
                    {
                      label: $t('SurfaceCorrection'),
                      value: 'SurfaceCorrection',
                    },
                    {
                      label: $t('DensityCorrection'),
                      value: 'DensityCorrection',
                    },
                    { label: $t('GridSettings'), value: 'GridSettings' },
                  ]" />
                <q-btn-toggle v-show="isdebug" no-caps v-model="options" toggle-color="primary" :options="[
                  { label: $t('debugging'), value: 'Debugging' }
                ]" />
              </div>
              <div style="min-height: 72vh">
                <component :is="options" />
              </div>
            </div>
          </div>
        </q-card-section>

        <q-separator />

        <q-card-actions align="right">
          <span>{{ $t("disable blending params") }}</span>
          <q-checkbox style="justify-content: flex-start" v-model="disable_blending_params"
            @click="send_disable_blending_params" />
          <span>{{ $t("show blending grids") }}</span>
          <q-checkbox style="justify-content: flex-start" v-model="show_blending_grids"
            @click="send_show_blending_grids" />
          <div class="q-space" data-v-39efcd1f=""></div>
          <div class="q-space" data-v-39efcd1f=""></div>
          <q-btn color="white" @click="resetall" text-color="black" :label="$t('resetall config')" />
          <div class="q-space" data-v-39efcd1f=""></div>
          <q-btn flat :label="$t('Select saved configuration')" no-caps color="primary"
            @click="select_configuration = true; get_scenes()" />
          <q-btn flat :label="$t('Cancel')" no-caps color="primary" v-close-popup
            @click="$store.commit('setSelectedProjector', '0/0');" />
          <q-btn flat :label="$t('save config')" no-caps color="primary" @click="save" />
        </q-card-actions>
      </q-form>
    </q-card>

    <q-dialog v-model="medium">
      <q-card style="width: 700px; max-width: 80vw;">
        <q-card-section>
          <div class="text-h6">{{ $t('Whether to save the configuration') }}</div>
        </q-card-section>
        <q-card-section class="q-pt-none">
          <q-select filled :model-value="save_cover_name" use-input hide-selected fill-input input-debounce="0"
            :options="plan_list_op" @filter="filterFn" @input-value="setModel">
            <template v-slot:option="{ itemProps, opt, selected, toggleOption }">
              <q-item v-bind="itemProps">
                <q-item-section>
                  <q-item-label v-html="opt" />
                </q-item-section>
                <q-item-section side>
                  <q-icon name="clear" @click="del_scenes(opt)"></q-icon>
                </q-item-section>
              </q-item>
            </template>
          </q-select>
        </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('save')" @click="saveconfig" color="primary" v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>


    <q-dialog v-model="select_configuration">
      <q-card style="width: 700px; max-width: 80vw;">
        <q-card-section>
          <div class="text-h6">{{ $t('read saved configuration') }}</div>
        </q-card-section>
        <q-card-section class="q-pt-none">
          <q-select filled v-model="select_configuration_name" :options="plan_list" :label="$t('please choose')">
            <template v-slot:option="{ itemProps, opt, selected, toggleOption }">
              <q-item v-bind="itemProps">
                <q-item-section>
                  <q-item-label v-html="opt" />
                </q-item-section>
                <q-item-section side>
                  <q-icon name="clear" @click="del_scenes(opt)"></q-icon>
                </q-item-section>
              </q-item>
            </template>
          </q-select>
        </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('apply')" @click="apply_the_selected_configuration" color="primary" v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <q-dialog v-model="del_dialog">
      <q-card style="width: 700px; 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('Whether to delete') + name_to_be_deleted }}
        </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="dialog_del_scenes" color="primary" v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>

  </q-dialog>
</template>

<style scoped>
.header_label {
  width: 20%;
}

.w100 {
  width: 100%;
}
</style>

<script lang="ts">
import {
  defineComponent,
  ref,
  Ref,
  watch,
  computed,
  onMounted,
  onBeforeMount,
} from "vue";
import { useStore } from "src/store";
import { useQuasar, copyToClipboard } from "quasar";
import { useI18n } from "vue-i18n";
import GlobalData from "src/common/GlobalData";
import { Protocol } from "src/entities/WSProtocol";
import { EDeviceAttribute } from "src/entities/EDeviceAttribute";

import ProjectorItem from "src/components/FusionSettings/ProjectorItem.vue";

import FusionLocale from "src/components/FusionSettings/FusionLocale.vue";
import FourPointCalibration from "src/components/FusionSettings/FourPointCalibration.vue";
import GridSettings from "src/components/FusionSettings/GridSettings.vue";
import SurfaceCorrection from "src/components/FusionSettings/SurfaceCorrection.vue";
import DensityCorrection from "src/components/FusionSettings/DensityCorrection.vue";
import Debugging from "src/components/FusionSettings/Debugging.vue";

export default defineComponent({
  name: "ComponentFusionSettingsDialog",
  components: {
    ProjectorItem,
    FusionLocale,
    FourPointCalibration,
    GridSettings,
    SurfaceCorrection,
    DensityCorrection,
    Debugging
  },
  setup() {
    let set = GlobalData.getInstance().getCurrentClient();
    let $store = useStore();
    let $q = useQuasar();
    let $t = useI18n();
    let show_dialog = ref(false);
    const save_name = ref("")
    const showDialog = async () => {
      show_dialog.value = true;
    };
    const select_configuration = ref(false)
    const del_dialog = ref(false)
    const select_configuration_name = ref("")
    const send_disable_blending_params = () => {
      set?.SetBlendingOption(disable_blending_params_id.value, disable_blending_params.value ? "1" : "0");
    };
    const send_show_blending_grids = () => {
      let tmp = ""
        switch (optionsstr.value) {
          case 'FusionLocale':
            tmp = '0'
            break;
          case 'FourPointCalibration':
            tmp = '4'
            break;
          case 'SurfaceCorrection':
            tmp = '9'
            break;
          case 'DensityCorrection':
            tmp = 'density'
            break;
          default:
            break;
        }
      set?.SetBlendingOption("blending_grids_select_ui", tmp)
      set?.SetBlendingOption('blending_grids_select_projector', now_selsect_projector.value);
      set?.SetBlendingOption(show_blending_grids_id.value, show_blending_grids.value ? "1" : "0");
    };
    const resetall = () => {
      set?.ResetBlendingConfig().then((res) => {
        let tmp = JSON.parse(res ? res.config : "");
        EnableBlending.value = tmp.enable;
        $store.commit("setEnablefusion", tmp.enable);
        config.value.col = tmp.col;
        config.value.row = tmp.row;
        $store.commit("setfusion_configuration", res?.config);
      });
      let tmp = options.value
      options.value = ""
      $store.commit("setSelectedProjector", "0/0");
      setTimeout(() => {
        clear_sessionStorage()
        options.value = tmp
      }, 300);
    }
    const clear_sessionStorage = () => {
      sessionStorage.removeItem("FusionLocale");
      sessionStorage.removeItem("SurfaceCorrection");
      sessionStorage.removeItem("DensityCorrection");
      sessionStorage.removeItem("FourPointCalibration");
      sessionStorage.removeItem("GridSettings");
      sessionStorage.removeItem("Debugging");
    }

    const config = ref({ col: 0, row: 0 });
    const EnableBlending = ref(false);
    let optionsstr = ref();
    optionsstr.value = "FusionLocale";
    const disable_blending_params_id = ref("1");
    const disable_blending_params = ref(false);
    const show_blending_grids_id = ref("blending_grids_show");
    const show_blending_grids = ref(false);
    const medium = ref(false);
    const options = computed({
      get() {
        return optionsstr.value;
      },
      set(newValue) {
        optionsstr.value = newValue;
      },
    });
    watch(
      () => EnableBlending,
      (newVal, oldVal) => {
        $store.commit("setEnablefusion", newVal.value);
        set?.EnableBlending(newVal.value);
      },
      { deep: true }
    );

    watch(() => optionsstr,
      (newVal) => {
        let tmp = ""
        switch (newVal.value) {
          case 'FusionLocale':
            tmp = '0'
            break;
          case 'FourPointCalibration':
            tmp = '4'
            break;
          case 'SurfaceCorrection':
            tmp = '9'
            break;
          case 'DensityCorrection':
            tmp = 'density'
            break;
          default:
            break;
        }
        set?.SetBlendingOption("blending_grids_select_ui", tmp)
      },
      { deep: true })



    const save = () => {
      medium.value = true
      //读取场景
      get_scenes()
    };
    const getconfig = () => {
      try {
        set?.GetBlendingConfig("").then((res) => {
          let tmp = JSON.parse(res ? res.config : "");
          $store.commit("setEnablefusion", tmp.enable);
          $store.commit("setfusion_configuration", res?.config);
        });
      } catch (error) { }
    };
    const clear = () => {
      record_times.value = 0
      show_blending_grids.value = false;
      send_show_blending_grids();
      $store.commit("setSelectedProjector", "0/0");
      setTimeout(() => {
        clear_sessionStorage()
      }, 500);
      getconfig()
      options.value = "FusionLocale"
    };


    const get_scenes = () => {
      set?.EnumBlendingScene().then((res) => {
        if (res == null || res.scenes.length == 0) return
        plan_list.splice(0, plan_list.length);
        for (let index = 0; index < res.scenes.length; index++) {
          plan_list[index] = (res.scenes[index]);
        }
      })
    }

    onMounted(() => {
      setTimeout(() => {
        set?.GetBlendingConfig("").then((res) => {
          let tmp = JSON.parse(res ? res.config : "");
          let local_options = [
            [disable_blending_params_id, disable_blending_params],
            [show_blending_grids_id, show_blending_grids]
          ];
          let k: any;
          for (k in local_options) {
            let local_opt = local_options[k];
            let opt = tmp.options[(<any>local_opt[0].value)];
            if (opt) {
              local_opt[1].value = ("0" == opt || "false" == opt.toLowerCase() ? false : true);
            }
          }
          EnableBlending.value = tmp.enable;
          $store.commit("setEnablefusion", tmp.enable);
          config.value.col = tmp.col;
          config.value.row = tmp.row;
          $store.commit("setfusion_configuration", res?.config);

        });
        get_scenes()
        set?.SetBlendingOption("blending_grids_select_ui", '0')
      }, 1000);
    });
    const save_cover_name = ref("")
    const plan_list = [
      ''
    ]
    const apply_the_selected_configuration = () => {
      set?.ApplyBlendingScene(select_configuration_name.value).then((res) => {
        let tmp = JSON.parse(res ? res.config : "{}");
        EnableBlending.value = tmp.enable;
        $store.commit("setEnablefusion", tmp.enable);
        config.value.col = tmp.col;
        config.value.row = tmp.row;
        $store.commit("setfusion_configuration", res?.config);
      });

      let tmp = options.value
      options.value = ""
      $store.commit("setSelectedProjector", "0/0");
      setTimeout(() => {
        clear_sessionStorage()
        options.value = tmp
      }, 800);
      getconfig()
    }
    const plan_list_op = ref(plan_list)
    const filterFn = (val: any, update: any, abort: any) => {
      update(() => {
        const needle = val.toLocaleLowerCase()
        plan_list_op.value = plan_list.filter(v => v.toLocaleLowerCase().indexOf(needle) > -1)
      })
    }
    const record_times = ref(0)
    const setModel = (val: string) => {
      save_cover_name.value = val
    }

    const saveconfig = () => {
      set?.SaveBlendingConfig(save_cover_name.value);
    }

    const isdebug = computed(() => {
      try {
        let tmp = JSON.parse($store.state.fusion_configuration)
        return record_times.value > 2
      } catch (error) {

      }

    })
    const name_to_be_deleted = ref("");
    const del_scenes = (name: string) => {
      del_dialog.value = true;
      name_to_be_deleted.value = name;
    }
    const dialog_del_scenes = () => {
      set?.DeleteBlendingScene(name_to_be_deleted.value);
      plan_list.splice(plan_list.findIndex(item => item === name_to_be_deleted.value), 1)
    }
    const now_selsect_projector=ref("0-0")
    const currently_selected_projector = (value: string) => {
      set?.SetBlendingOption('blending_grids_select_projector', value);
      now_selsect_projector.value=value
    }
    return {
      currently_selected_projector,
      name_to_be_deleted,
      dialog_del_scenes,
      get_scenes,
      del_scenes,
      filterFn,
      setModel,
      send_disable_blending_params,
      disable_blending_params,
      send_show_blending_grids,
      show_blending_grids,
      clear,
      show_dialog,
      options,
      copyToClipboard,
      showDialog,
      EnableBlending,
      config,
      save,
      resetall,
      medium,
      save_name,
      save_cover_name,
      plan_list,
      select_configuration,
      select_configuration_name,
      apply_the_selected_configuration,
      plan_list_op,
      record_times,
      saveconfig,
      isdebug,
      del_dialog
    };
  },
});
</script>
