<template>
  <div style="position: relative">
    <div class="toolbarWrapper">
      <!-- <ViewWindowSetting v-model="viewType" @update:model-value="handleUpdateViewType" /> -->
      <!-- <el-tooltip content="全屏">
        <el-icon class="el-input__icon" :size="18" style="margin-left: 10px; margin-right: 10px">
          <FullscreenExitOutlined role="full" @click="enterFullscreen" />
        </el-icon>
      </el-tooltip> -->
      <!-- <RenderSwitch />
      <FenceAppSetting /> -->
    </div>
    <div class="videoAlgoListWrapper">
      <div class="cameraViewSettingWrapper" :style="{ width: domWidth + 'px', height: domHeight + 'px' }">
        <div class="fenceEditorWrapper" v-if="showFenceTool" key="cameraDetailStore.cameraId">
          <FenceEditor
            ref="fenceEditorRef"
            :dom-width="domWidth"
            :canvas-size="{ width: canvasWidth, height: canvasHeight }"
            :line-points="fenceStore.allFences"
            :fence-id="fenceStore.currentFenceId"
            @save="handleSaveFenceToLocal"
            @select="handleSelectFencePolygon"
          />
        </div>

        <div class="cameraVideo">
          <CameraLiveVideo />
        </div>
      </div>
      <div> <AlgoCanSelect :selected-ids="cameraAlgoIds" @select="handleApplyAlgo" /></div>
    </div>

    <div
      class="presetAddWrapper"
      :class="{ hidePresetControlCls: showFenceTool }"
      v-if="!!cameraDetailStore.detail?.isPtz"
    >
      <CameraViewScale />
      <CameraDirectionControl />
      <ElButton type="primary" @click="handleAddPreset" size="small" style="margin-top: 20px; width: 100px"
        >添加预置位</ElButton
      >
      <AddPresetModal v-if="addPresetModalVisible" @close="handleClose" @ok="handleAddPresetOk" />
    </div>
  </div>
  <div class="presetWrapper" :style="{ display: showFenceTool ? 'block' : 'none' }">
    <FenceToolbar
      :is-edit="showFenceTool"
      @remove="handleRemove"
      @toggle-range="toggleRange"
      @select="handleSelectFenceList"
      @toggle-fence-status="paramsSettingFn.toggleFenceStatus"
      @save="handleSaveFenceToServer"
      @cancel="handleCancelFenceEdit"
    />
  </div>

  <div class="cameraParamsSettingWrapper">
    <div class="algorithmsSetting"> <AlgorithmsSetting /> </div>
  </div>
</template>
<script lang="ts" setup>
  import { computed, ref } from 'vue';
  import FenceToolbar from '../FenceToolbar/FenceToolbar.vue';
  import FenceEditor from '../FenceEditorV2/FenceEditor.vue';
  import CameraLiveVideo from '../CameraLiveVideo/CameraLiveVideo.vue';
  import useFenceStore from '../../store/useFenceStore';
  import AddPresetModal from '../AddPresetModal/AddPresetModal.vue';
  import usePresetListStore from '../../store/usePresetListStore';
  import useCameraDetailStore from '../../store/useCameraDetailStore';
  import useCameraAlgoStore from '../../store/useCameraAlgoStore';
  import AlgorithmsSetting from '../AlgorithmsSetting/AlgorithmsSetting.vue';

  import { ElMessage } from 'element-plus';
  import CameraDirectionControl from '../CameraDirectionControl/CameraDirectionControl.vue';
  import CameraViewScale from './CameraViewScale.vue';
  import { canvasHeight, canvasWidth, domHeight, domWidth } from './constants';
  import { createCameraAlgoApi, updateCameraAlgoApi } from '@/api/camera/camera-preview';
  import { RegionJudge } from '../FenceToolbar/constants';
  import AlgoCanSelect from '../AlgoCanSelect/AlgoCanSelect.vue';
  import { FencePolygonPoints } from '../FenceEditorV2/types';
  import useParamsSettingFn from '../../hooks/useParamsSettingFn';

  const emits = defineEmits<{
    (e: 'changeTreeRender', render: number | string): unknown;
  }>();

  const fenceEditorRef = ref<typeof FenceEditor | null>(null);

  const paramsSettingFn = useParamsSettingFn();

  const fenceStore = useFenceStore();

  const presetStore = usePresetListStore();
  const cameraDetailStore = useCameraDetailStore();
  const cameraAlgoStore = useCameraAlgoStore();

  const { getCameraAlgoList } = cameraAlgoStore;

  const addPresetModalVisible = ref(false);

  const cameraAlgoIds = computed(() => {
    return cameraAlgoStore.cameraAlgoList?.map((item) => item.algoId) || [];
  });

  const handleClose = () => {
    addPresetModalVisible.value = false;
  };

  const handleAddPresetOk = () => {
    presetStore.getPresetList(cameraDetailStore.cameraId);
    handleClose();
  };

  const handleRemove = () => {
    fenceEditorRef.value?.remove();
  };

  /** 从图中选中电子围栏多边形 */
  const handleSelectFencePolygon = (nextFenceId: number) => {
    fenceStore.currentFenceId = nextFenceId;
  };

  // 选中电子围栏列表时
  const handleSelectFenceList = (nextFenceId: number) => {
    fenceStore.currentFenceId = nextFenceId;
  };

  const handleSaveFenceToServer = () => {
    paramsSettingFn.saveFenceToServer();
  };

  const handleCancelFenceEdit = () => {
    fenceStore.confirmExitFence().then(() => {
      fenceStore.reset();
      fenceStore.showFenceTool = false;
    });
  };

  /** 将数据保存到前端本地 */
  const handleSaveFenceToLocal = (data: { fenceId?: number; polygon: FencePolygonPoints }) => {
    console.log('提交的fenceId', data);
    const { fenceId, polygon } = data;

    const cameraId = cameraDetailStore.cameraId;
    const algoId = cameraAlgoStore.selectedAlgoId;
    const presetToken = presetStore.currentPresetToken;
    if (!cameraId) {
      ElMessage.error('未选中相机');
      return;
    }
    if (!algoId) {
      ElMessage.error('未选中算法');
      return;
    }
    if (!presetToken) {
      ElMessage.error('未选中预置位');
      return;
    }

    if (!fenceId) {
      // 不存在的话，就新建电子围栏
      paramsSettingFn.createFence(polygon);
    } else {
      // 否则修改电子围栏
      paramsSettingFn.editFence({ polygon, id: fenceId });
    }
  };

  const toggleRange = () => {
    const selectedAlgoDetail = cameraAlgoStore.selectedAlgoDetail;
    const cameraId = cameraDetailStore.cameraId;

    const extraStr = selectedAlgoDetail.extra;
    const extraJSON = JSON.parse(extraStr);
    const nextRegionJudge =
      extraJSON.inferParams?.[0]?.regionJudge === RegionJudge.out ? RegionJudge.in : RegionJudge.out;

    extraJSON.inferParams[0].regionJudge = nextRegionJudge;

    const newParam = {
      cameraId: cameraId,
      algoId: selectedAlgoDetail.algoId,
      extra: JSON.stringify(extraJSON),
      id: selectedAlgoDetail.id!,
    };
    updateCameraAlgoApi(newParam).then(() => {
      ElMessage.success('修改成功');
      getCameraAlgoList(cameraId);
    });
  };

  const showFenceTool = computed(() => {
    return fenceStore.showFenceTool;
  });

  const handleAddPreset = () => {
    addPresetModalVisible.value = true;
  };

  const handleApplyAlgo = (id: number) => {
    createCameraAlgoApi({
      algoIds: [id],
      cameraId: cameraDetailStore.cameraId,
    }).then((res) => {
      getCameraAlgoList(cameraDetailStore.cameraId);
      ElMessage.success('添加成功，开启后算法生效');
    });
  };
</script>
<style scoped>
  .cameraViewSettingWrapper {
    position: relative;
    flex-shrink: 0;
    flex-grow: 0;
    /* border: 1px solid #ccc; */
  }
  .cameraViewOverflow {
    overflow: hidden;
    position: relative;
  }

  .cameraVideo {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 8;
    background: #ccc;
    width: 100%;
    height: 100%;
  }

  .toolbarWrapper {
    display: flex;
    align-items: center;
    /* margin-left: 25px; */
    position: relative;
  }

  .presetAddWrapper {
    position: absolute;
    bottom: 50px;
    right: 280px;
    flex-direction: column;
    display: flex;
    align-items: center;
    z-index: 10;
  }

  .cameraParamsSettingWrapper {
    display: flex;
    margin-top: 10px;
  }
  .algorithmsSetting {
    flex: 1;
    min-height: 300px;
    /* margin-left: 15px; */
    /* border-left: 1px solid #ccc; */
    /* padding-left: 15px; */
  }
  .cameraParamsSetting {
    flex-basis: 330px;
    flex-shrink: 0;
  }
  .hidePresetControlCls {
    display: none;
  }
  .fenceEditorWrapper {
    position: relative;
    z-index: 9;
  }

  .presetWrapper {
    position: absolute;
    right: 0;
    top: 0;
    width: 260px;
    height: 540px;
    box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1);
    background: #fff;
    /* width: 962px; */
    /* padding: 20px;
    padding-left: 15px;
    border-bottom: 1px solid #ccc;
    padding-bottom: 10px;
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between; */
    transform: scale(1);
  }
  .videoAlgoListWrapper {
    display: flex;
  }
</style>
