<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="isShowFence">平台预览</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';
  const valuePreset = ref<[string, string]>();
  const cameraDetailStore = useCameraDetailStore();
  const { isShowFence, detail } = storeToRefs(cameraDetailStore);

  const appFenceCameraDetail = ref<CameraAlgoPresetResp | null>(null);

  const options = ref([]);

  const { appPCUrl } = useGlobSetting();

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

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

      getAppCameraAlgoPreset(newCode).then((res) => {
        appFenceCameraDetail.value = res;
        valuePreset.value = [res.algoCode, res.presetToken];
      });
    },
  );

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

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

      return newItem;
    });
  };

  const changeShowFence = async () => {
    if (isShowFence.value) {
      const params = {
        cameraCode: cameraDetailStore.detail?.code!,
        status: 0,
      };
      await updateFenceDisplayStatus(params);
    } else {
      const params = {
        cameraCode: cameraDetailStore.detail?.code!,
        status: 1,
      };
      updateFenceDisplayStatus(params);
    }
  };

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

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