<template>
  <div>
    <div class="camera-main">
      <div class="camera-tree">
        <CameraTreeCom
          :loading="presetListStore.loading"
          :camera-tree="cameraTree || []"
          :total="codeShowList.length"
          :no-integration-num="noIntegrationNum"
          :no-networking-num="noNetworkingNum"
        />
      </div>
      <div class="camera-placeholder" v-if="!cameraDetailStore.cameraId">请选择左侧相机</div>
      <div v-else class="camera-setting-wrapper">
        <NvrCameraView ref="nvrCameraViewRef" :camera-id="cameraDetailStore.cameraId" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import NvrCameraView from './components/NvrCameraView.vue';
  import CameraTreeCom from '@/views/cameras/preview/components/CameraTree/CameraTree.vue';
  import { onUnmounted, onBeforeUnmount, ref, watch } from 'vue';
  import useCameraDetail from '@/views/cameras/preview/store/useCameraDetailStore';
  import usePresetListStore from '@/views/cameras/preview/store/usePresetListStore';
  import useFenceStore from '@/views/cameras/preview/store/useFenceStore';
  import useCameraAlgoStore from '@/views/cameras/preview/store/useCameraAlgoStore';
  import { onMounted } from 'vue';
  import { CameraDetailServer, IsPtz } from '@/api/camera/camera-overview';
  import { CameraTree, getCameraTree } from '@/api/camera/camera-preview';
  import useCameraStatus from '@/views/cameras/preview/store/useCameraStatus';

  const cameraStatus = useCameraStatus();
  const { noNetworkingNum, openInterval, closeInterval } = cameraStatus;

  const cameraDetailStore = useCameraDetail();
  const fenceStore = useFenceStore();
  const presetListStore = usePresetListStore();
  const cameraAlgoStore = useCameraAlgoStore();
  const cameraTree = ref<CameraTree[]>([]);
  const codeShowList = ref<string[]>([]);
  const noIntegrationNum = ref<number>(0);
  const nvrCameraViewRef = ref();

  // const { allAlgoList } = storeToRefs(cameraAlgoStore);

  function updateNetworkingState(data, targetData) {
    let integrationCount = 0;
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const matchedNode = targetData.find((item) => item.cameraCode === node.code);
      if (matchedNode) {
        node.networkingState = matchedNode.status;
        node.integrationState = matchedNode.integrationState;
      }
      if (node.integrationState === 1) {
        integrationCount++;
      }
      if (node.children && node.children.length > 0) {
        const childIntegrationCount = updateNetworkingState(node.children, targetData);
        integrationCount += childIntegrationCount;
      }
    }
    noIntegrationNum.value = integrationCount;
    return integrationCount;
  }

  function getCameraList(data) {
    let cameraList = [] as string[];
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      if (node.nodeType === 'camera') {
        cameraList.push(node.code);
      }
      if (node.children && node.children.length > 0) {
        const childCameraList = getCameraList(node.children);
        cameraList.push(...childCameraList);
      }
    }
    return cameraList;
  }

  watch(
    () => cameraDetailStore.cameraId,
    async (cameraId) => {
      fenceStore.clear();
      if (cameraId) {
        const presetList = await presetListStore.getPresetList(cameraId);

        if (cameraTree.value.length === 0) {
          /** 如果当前树为空，那么切换相机的时候，要重新请求树结构 */
          const tree = await getCameraTree();
          cameraTree.value = tree as unknown as CameraTree[];
        }

        const detail: CameraDetailServer = getCameraDetail(
          cameraTree.value,
          cameraDetailStore.cameraId,
        ) as unknown as CameraDetailServer;
        if (detail) {
          cameraDetailStore.setDetail(detail);
          if (detail?.isPtz === IsPtz.disabled) {
            presetListStore.currentPresetToken = presetList?.[0].token;
          }
        }
        // cameraAlgoStore.getCameraAlgoList(cameraId);
        // cameraAlgoStore.selectedAlgoId = null;

        cameraAlgoStore.selectedAlgoList = [];
        cameraAlgoStore.getCameraAlgoList(cameraId).then();
        nvrCameraViewRef.value.clearNvrUrl();
      } else {
        /** 没有相机的时候也要请求相机树 */
        const tree = await getCameraTree();
        cameraTree.value = tree as unknown as CameraTree[];
      }
    },
    {
      immediate: true,
    },
  );

  onMounted(() => {
    getCameraTree().then((res) => {
      cameraTree.value = res;
      codeShowList.value = getCameraList(res);
      openInterval(codeShowList.value, (targetData) => {
        updateNetworkingState(cameraTree.value, targetData);
      });
    });
  });

  onBeforeUnmount(() => {
    if (nvrCameraViewRef.value) {
      nvrCameraViewRef.value.clearNvrUrl();
    }
  });

  onUnmounted(() => {
    /** 离开页面要清理掉所有的store */
    cameraDetailStore.clear();
    cameraAlgoStore.clear();
    fenceStore.clear();
    presetListStore.clear();
    closeInterval();
  });

  function getCameraDetail(tree: CameraTree[], cameraId: number): CameraTree | null {
    let detail: CameraTree | null = null;

    function getDetail(t: CameraTree[]) {
      t.forEach((x) => {
        if (x.nodeType === 'camera' && x.id === cameraId) {
          detail = x;
        } else if (x.children && x.children.length > 0) {
          getDetail(x.children);
        }
      });
    }

    getDetail(tree);

    return detail;
  }
</script>
<style lang="scss" scoped>
  .camera-main {
    display: flex;
    background: #fff;

    .camera-tree {
      width: 250px;
      flex-shrink: 0;
      border: 1px solid #f0f2f5;
      margin: 5px;
    }
    .camera-placeholder {
      color: #333;
      text-align: center;
      margin-top: 100px;
      margin-left: 100px;
    }
    .camera-setting-wrapper {
      width: 960px;
    }
  }
</style>
