<template>
  <div class="fenceWrapper">
    <div>
      <div class="fenceTitle">电子围栏</div>
      <ElSwitch
        size="small"
        class="fenceSwitchBtn"
        v-model="selectedAlgoDetail.electronicFenceBool"
        @update:modelValue="handleUpdateFenceStatus"
      />
    </div>
    <div class="algoName">
      {{ selectedAlgoDetail?.algoInfo?.name }}
    </div>
    <PresetSelect />
    <Description :is-simple="Boolean(!cameraDetailStore.detail?.isPtz)" v-if="fenceStore.allFences.length === 0" />
    <div v-if="fenceStore.allFences.length > 0">
      <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 style="text-align: right">
        <ElButton size="small" @click="handleCancelFence">取消</ElButton>
        <ElButton type="primary" size="small" @click="handleSaveFence">保存</ElButton>
      </div>
    </div>
    <div>
      <EditFenceDialog
        v-if="showEditFenceDialog"
        @cancel="handleEditCancel"
        @submit="handleEditSubmit"
        :detail="selectedDetail"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
  import { computed, defineEmits, ref, watch } from 'vue';
  import { ElMessage, ElSwitch } from 'element-plus';
  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';
  import useParamsSettingFn from '../../hooks/useParamsSettingFn';
  import Description from './Description.vue';
  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 paramsSettingFn = useParamsSettingFn();

  const { selectedAlgoDetail } = storeToRefs(cameraAlgoStore);

  const emits = defineEmits<{
    (e: 'toggleRange'): unknown;
    (e: 'remove'): unknown;
    (e: 'cancel'): unknown;
    (e: 'save'): unknown;
    (e: 'select', fenceId: number): unknown;
    /** 切换电子围栏打开关闭状态 */
    (e: 'toggleFenceStatus', nextStatus: boolean): 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.isDisplayFence,
    (isDisplayFence) => {
      isDisplayFenceInVideo.value = isDisplayFence;
    },
    {
      immediate: true,
    },
  );

  const handleSaveFence = () => {
    emits('save');
  };
  const handleCancelFence = () => {
    emits('cancel');
  };

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

  const handleUpdateRegion = (val: string) => {
    emits('toggleRange');
  };

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

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

  const handleDeleteFence = (fenceId: number) => {
    paramsSettingFn.deleteFence(fenceId);
  };

  const handleEditSubmit = (data: { label: string; name: string }) => {
    const fenceId = selectedDetail.value?.id;
    if (!fenceId) return;
    paramsSettingFn.editFence({
      id: fenceId,
      label: data.label,
      name: data.name,
    });

    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).then((res) => {
        ElMessage.success('修改成功');
      });
    }
  };

  const handleUpdateFenceStatus = (nextStatus: boolean) => {
    console.log('nextFenceStatus', nextStatus);
    emits('toggleFenceStatus', nextStatus);
  };
</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;
  }

  .algoName {
    color: #ccc;
    margin-top: 10px;
    font-size: 12px;
  }

  .fenceWrapper {
    padding: 10px;
  }
  .fenceListWrapper {
    height: 365px;
    overflow-y: auto;
    margin-bottom: 10px;
  }

  .fenceTitle {
    font-weight: bold;
    font-size: 16px;
    position: relative;
    margin-left: 10px;
    &::before {
      content: '';
      width: 4px;
      position: absolute;
      left: -8px;
      height: 20px;
      top: 2px;
      background-color: #1890ff;
    }
  }
</style>
