<template>
  <div class="fenceWrapper">
    <div>
      <div>电子围栏</div>
      <ElSwitch size="small" class="fenceSwitchBtn" />
    </div>
    <PresetSelect />

    <div style="display: flex">
      <ElCheckbox label="检测围栏外部" v-model="isFenceRegionOut" @update:modelValue="handleUpdateRegion" />
      <ElCheckbox label="前台画面显示" v-model="isDisplayFenceInVideo" @update:modelValue="handleUpdateDisplay" />
      <a :href="previewUrl" target="_blank" style="margin-left: 20px" v-if="previewUrl && false">平台相机预览</a>
    </div>
    <div class="fenceListWrapper">
      <FenceNameItem
        :active="item.id === fenceStore.currentFenceId"
        v-for="item in fenceStore.allFences"
        :detail="item"
        :key="item.id"
        @click="handleSelectFence(item.id)"
        @delete="handleDeleteFence"
        @edit="handleEditFenceInfo(item)"
      />
    </div>
    <div>
      <EditFenceDialog
        v-if="showEditFenceDialog"
        @cancel="handleEditCancel"
        @submit="handleEditSubmit"
        :detail="selectedDetail"
      />
    </div>

    <!-- <div class="toolbar"> -->
    <!-- <div class="fenceDrawingTip" v-if="isEdit">
        {{ cameraAlgoStore.selectedAlgoDetail?.algoInfo?.name }}算法电子围栏绘制中
      </div> -->
    <!-- <template v-if="props.isEdit"> -->
    <!-- <ToolbarIcon
        :src="deleteIcon"
        :active="false"
        @click="emits('toggleFence')"
        tip="检测范围反选"
      /> -->
    <!-- <ToggleFenceStatus @click="emits('toggleRange')" />
        <ToolbarIcon :src="deleteIcon" :active="false" @click="emits('remove')" tip="删除电子围栏" />
        <ToolbarIcon :src="saveIcon" :active="false" @click="emits('save')" tip="保存电子围栏" />
      </template> -->

    <!-- <ElButton type="primary" size="small" @click="toggleEdit">{{
        props.isEdit ? '退出编辑' : '编辑电子围栏'
      }}</ElButton> -->
    <!-- </div> -->
  </div>
</template>
<script setup lang="ts">
  import { computed, defineEmits, ref, watch } from 'vue';
  import { ElButton, ElSwitch } from 'element-plus';
  import ToolbarIcon from '../ToolbarIcon/ToolbarIcon.vue';
  import saveIcon from '@/assets/images/camera/save.png';
  import deleteIcon from '@/assets/images/camera/delete.png';
  import ToggleFenceStatus from './ToggleFenceStatus.vue';
  import useCameraAlgoStore from '../../store/useCameraAlgoStore';
  import PresetSelect from '../PresetSelect/PresetSelect.vue';
  import FenceNameItem from './FenceNameItem.vue';
  import useFenceStore from '../../store/useFenceStore';
  import useCameraDetailStore from '../../store/useCameraDetailStore';
  import usePresetListStore from '../../store/usePresetListStore';
  import EditFenceDialog from './EditFenceDialog.vue';
  import { ServerLineInfo } from '../FenceEditor/constants';
  import { storeToRefs } from 'pinia';
  import { RegionJudge } from './constants';
  import { choosePreset, updateFenceDisplayStatus } from '@/api/camera/camera-preview';
  import { FenceDisplayStatus } from '@/types/camera/constant';
  import { useGlobSetting } from '@/hooks/setting';
  const cameraAlgoStore = useCameraAlgoStore();

  const fenceStore = useFenceStore();
  const cameraDetailStore = useCameraDetailStore();
  const presetStore = usePresetListStore();
  const props = defineProps<{ isEdit: boolean }>();

  const showEditFenceDialog = ref(false);
  const selectedDetail = ref<ServerLineInfo | null>(null);

  const { selectedAlgoDetail } = storeToRefs(cameraAlgoStore);

  const emits = defineEmits<{
    (e: 'toggleEditable', editState: boolean): unknown;
    (e: 'toggleRange'): unknown;
    (e: 'remove'): unknown;
    (e: 'save'): unknown;
    (e: 'select', fenceId: number): unknown;
  }>();

  const isFenceRegionOut = ref(false);
  const isDisplayFenceInVideo = ref(false);

  const { detail } = storeToRefs(cameraDetailStore);

  const { appPCUrl } = useGlobSetting();

  const previewUrl = computed(() => {
    const firstSceneId = detail.value?.sceneTemplateList[0]?.sceneId;
    if (!detail.value?.workshopId || !detail.value?.code || !firstSceneId) return '';
    return appPCUrl + `#/shop?id=${detail.value?.workshopId}&cameraCode=${detail.value?.code!}&sceneId=${firstSceneId}`;
  });

  watch(
    () => selectedAlgoDetail.value?.regionJudge,
    (newVal) => {
      isFenceRegionOut.value = newVal === RegionJudge.out;
    },
    {
      immediate: true,
    },
  );
  watch(
    () => cameraDetailStore.isShowFence,
    (isShowFence) => {
      isDisplayFenceInVideo.value = isShowFence;
    },
    {
      immediate: true,
    },
  );

  const toggleEdit = () => {
    emits('toggleEditable', !props.isEdit);
  };

  const handleSelectFence = (nextFenceId: number) => {
    emits('select', nextFenceId);
  };

  const handleUpdateRegion = (val: string) => {
    console.log('isFenceRegionOut', isFenceRegionOut.value);
    console.log('region', val);
    emits('toggleRange');
  };

  const handleEditFenceInfo = (detail) => {
    showEditFenceDialog.value = true;
    selectedDetail.value = detail;
  };

  const handleEditCancel = () => {
    showEditFenceDialog.value = false;
    selectedDetail.value = null;
  };

  const handleDeleteFence = (fenceId: number) => {
    const cameraId = cameraDetailStore.cameraId;
    const algoId = cameraAlgoStore.selectedAlgoId!;
    const presetToken = presetStore.currentPresetToken;
    fenceStore.deleteFence({ cameraId, algoId, presetToken, fenceId });
  };

  const handleEditSubmit = (data: { label: string; name: string }) => {
    const cameraId = cameraDetailStore.cameraId;
    const algoId = cameraAlgoStore.selectedAlgoId!;
    const presetToken = presetStore.currentPresetToken;
    const fenceId = selectedDetail.value?.id;
    if (!fenceId) return;
    fenceStore
      .editFence({
        cameraId,
        algoId,
        presetToken,
        fenceId: fenceId,
        fenceLabel: data.label,
        fenceName: data.name,
      })
      .then(() => {
        handleEditCancel();
      });
  };

  const handleUpdateDisplay = (nextStatus: boolean) => {
    const params = {
      cameraCode: cameraDetailStore.detail?.code!,
      isDisplayFence: nextStatus ? FenceDisplayStatus.enabled : FenceDisplayStatus.disabled,
    };

    updateFenceDisplayStatus(params);
    if (nextStatus) {
      // 由于历史原因，需要调用两次接口
      const cameraId = cameraDetailStore.cameraId;
      const algoId = cameraAlgoStore.selectedAlgoId!;
      const presetToken = presetStore.currentPresetToken;
      const params = {
        algoId,
        cameraId,
        presetToken,
      };
      choosePreset(params);
    }
  };
</script>

<style scoped>
  .toolbar {
    display: flex;

    align-items: center;
    z-index: 10;
    padding: 5px;
    border-radius: 50px;
  }
  .fenceDrawingTip {
    background: #e8f5ff;
    border-radius: 6px;
    border: 1px solid #bae0ff;
    text-align: center;
    font-size: 12px;
    padding: 2px 20px;
    margin-right: 30px;
    color: #1890ff;
  }

  .fenceSwitchBtn {
    position: absolute;
    right: 10px;
    top: 10px;
  }

  .fenceWrapper {
    padding: 10px;
  }
  .fenceListWrapper {
    max-height: 435px;
    overflow-y: auto;
  }
</style>
