<template>
  <div>
    <div class="toolbarWrapper">
      <ViewWindowSetting v-model="viewType" @update:model-value="handleUpdateViewType" />
      <FenceToolbar
        :style="{ visibility: drawable ? 'visible' : 'hidden' }"
        @remove="handleRemove"
        @save="handleSave"
        @toggle-editable="toggleEditable"
        :is-edit="isEdit"
      />
      <PresetSelect />
    </div>

    <div class="cameraViewSettingWrapper">
      <FenceEditor ref="fenceEditorRef" />

      <div class="cameraVideo"><CameraLiveVideo /></div>
      <div class="presetAddWrapper">
        <CameraDirectionControl />
        <ElButton type="primary" @click="handleAddPreset" size="small">添加预置位</ElButton>
        <AddPresetModal
          v-if="addPresetModalVisible"
          @close="handleClose"
          @ok="handleAddPresetOk"
        /> </div
    ></div>
  </div>
  <div class="cameraParamsSettingWrapper">
    <div class="cameraParamsSetting">
      <CameraParams :detail="cameraParamsDetail" />
    </div>
    <div class="algorithmsSetting"> <AlgorithmsSetting /> </div>
  </div>
</template>
<script lang="ts" setup>
  import { computed, ref, watch } from 'vue';
  import FenceToolbar from '../FenceToolbar/FenceToolbar.vue';
  import FenceEditor from '../FenceEditor/FenceEditor.vue';
  import CameraLiveVideo from '../CameraLiveVideo/CameraLiveVideo.vue';
  import ViewWindowSetting from '../ViewWindowSetting/ViewWindowSetting.vue';
  import PresetSelect from '../PresetSelect/PresetSelect.vue';
  import { ViewType } from '../ViewWindowSetting/types';
  import useFenceStore from '../../store/useFenceStore';
  import AddPresetModal from '../AddPresetModal/AddPresetModal.vue';
  import { onMounted } from 'vue';
  import usePresetListStore from '../../store/usePresetListStore';
  import useCameraDetailStore from '../../store/useCameraDetailStore';
  import useCameraAlgoStore from '../../store/useCameraAlgoStore';
  import AlgorithmsSetting from '../AlgorithmsSetting/AlgorithmsSetting.vue';
  import CameraParams from '../CameraParams/CameraParams.vue';
  import { ElMessage } from 'element-plus';

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

  const fenceStore = useFenceStore();

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

  const viewType = ref<ViewType>(ViewType.window1);

  const addPresetModalVisible = ref(false);

  const cameraParamsDetail = ref({});

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

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

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

  const isEdit = ref(false);

  /** 退出编辑模式 */
  const toggleEditable = (val: boolean) => {
    isEdit.value = val;
    if (val) {
      fenceEditorRef.value?.setEditMode();
    } else {
      fenceEditorRef.value?.exitEditMode();
    }
  };

  const handleSave = () => {
    const json = fenceEditorRef.value?.toObject();
    console.log('save json', json);
    const cameraId = cameraDetailStore.cameraId;
    if (!cameraId) {
      ElMessage.error('未选中相机');
      return;
    }
    const algoId = cameraAlgoStore.selectedAlgoId;
    if (!algoId) {
      ElMessage.error('未选中算法');
      return;
    }
    const presetToken = presetStore.currentPresetToken;
    if (!presetToken) {
      ElMessage.error('未选中预置位');
      return;
    }

    fenceStore
      .saveFence({
        cameraId: cameraId,
        algoId: algoId,
        presetToken,
        electronicFencePolygon: JSON.stringify(json),
      })
      ?.then((res) => {
        ElMessage.success('更新成功');
      });
  };

  const handleUpdateViewType = (t: ViewType) => {
    console.log('viewType', t);
  };

  const handleUpdatePreset = (val: string) => {
    console.log('val', val);
  };
  watch(
    () => fenceStore.serverFencePoints,
    (newVal) => {
      console.log('newVal', newVal);
      if (!newVal) {
        fenceEditorRef.value?.clear();
        return;
      }
      // const rawLinePoints = newVal[0];

      const rawLinePoints = newVal.map((x) => {
        const points: number[] = [];
        x.forEach((line) => {
          points.push(line[0], line[1]);
        });
        return points;
      });
      if (!rawLinePoints) return;
      /** 先清空原有的 */
      fenceEditorRef.value?.clear();
      fenceEditorRef.value?.createLines(rawLinePoints);
    },
    { immediate: true },
  );

  watch(
    () => cameraAlgoStore.selectedAlgoDetail?.status,
    (newVal) => {
      if (newVal) {
        fenceEditorRef.value?.setEditMode();
      } else {
        fenceEditorRef.value?.exitEditMode();
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );

  const drawable = computed(() => {
    if (!presetStore.currentPresetToken) return false;
    if (!cameraAlgoStore.selectedAlgoId) return false;
    if (!cameraAlgoStore.selectedAlgoDetail?.electronicFenceBool) return false;
    return true;
  });

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

  onMounted(() => {
    const cameraId = cameraDetailStore.cameraId;
    if (cameraId) {
      presetStore.getPresetList(cameraId);
    }
  });
</script>
<style scoped>
  .cameraViewSettingWrapper {
    position: relative;
    width: 720px;
    height: 405px;
    border: 1px solid #ccc;
  }

  .cameraVideo {
    position: absolute;
    background: #ccc;
    width: 100%;
    height: 100%;
  }

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

  .presetAddWrapper {
    position: absolute;
    bottom: 50px;
    right: 50px;
    z-index: 10;
  }

  .cameraParamsSettingWrapper {
    display: flex;
    margin-top: 10px;
  }
  .algorithmsSetting {
    flex: 1;
    min-height: 300px;
    margin-left: 10px;
    border-left: 1px solid #ccc;
    padding-left: 15px;
  }
  .cameraParamsSetting {
    flex-basis: 330px;
    flex-shrink: 0;
  }
</style>
