<template>
  <!-- 电子围栏显示在前台的控制开关 -->
  <div class="wrapper">
    <el-checkbox
      label="平台是否显示电子围栏"
      v-model="isShowFence"
      @change="changeShowFence"
      class="checkbox"
    />
    <el-cascader
      v-model="valuePreset"
      :options="options"
      size="small"
      @change="changePreset"
      v-if="isShowFence"
    />
    <a :href="previewUrl" target="_blank" style="margin-left: 20px" v-if="previewUrl"
      >平台相机预览</a
    >
  </div>
</template>
<script lang="ts" setup>
  import {
    updateFenceDisplayStatus,
    getCameraAlgoPresetList,
    choosePreset,
    getAppCameraAlgoPreset,
    CameraAlgoPresetResp,
  } from '@/api/camera/camera-preview';
  import { computed, onMounted, ref, watch } from 'vue';
  import useCameraDetailStore from '../../store/useCameraDetailStore';
  import { storeToRefs } from 'pinia';
  import { OptionType } from './constants';
  import { useGlobSetting } from '@/hooks/setting';
  import { FenceDisplayStatus } from '@/types/camera/constant';
  const valuePreset = ref<[string, string]>();
  const cameraDetailStore = useCameraDetailStore();
  const { isShowFence, detail } = storeToRefs(cameraDetailStore);

  const options = ref([]);

  const { appPCUrl } = useGlobSetting();

  const previewUrl = computed(() => {
    if (!detail.value?.workshopId || !detail.value?.code) return '';
    return appPCUrl + `#/shop?id=${detail.value?.workshopId}&cameraId=${detail.value?.code!}`;
  });

  watch(
    () => detail.value?.id,
    (newId) => {
      if (!newId) return;
      getCameraAlgoPresetList(newId).then((res) => {
        options.value = renameKeys(res.algoInfoVOList);
      });

      getAppCameraAlgoPreset(newId).then((res) => {
        valuePreset.value = [res.algoId, res.presetToken];
      });
    },
  );

  const renameKeys = (data: any) => {
    return data.map((item) => {
      const newItem: OptionType = {
        label: item.name,
        value: item.id,
      };

      if (item.presetInfoList) {
        newItem.children = item.presetInfoList.map((child) => ({
          label: child.presetName,
          value: child.presetToken,
        }));
      }

      return newItem;
    });
  };

  const changeShowFence = async () => {
    const params = {
      cameraCode: cameraDetailStore.detail?.code!,
      isDisplayFence: isShowFence.value ? FenceDisplayStatus.enabled : FenceDisplayStatus.disabled,
    };

    updateFenceDisplayStatus(params);
  };

  const changePreset = (value) => {
    console.log('value', value);
    const params = {
      algoId: value[0],
      cameraId: cameraDetailStore.detail?.id!,
      presetToken: value[1],
    };
    choosePreset(params);
  };
</script>
<style scoped>
  .wrapper {
    display: flex;
    align-items: center;
    margin-left: 20px;
  }

  .checkbox {
    margin-right: 10px;
  }
</style>
