<template>
  <div>
    <div class="cameraMain">
      <div class="cameraTree">
        <CameraTreeCom
          :loading="presetListStore.loading"
          :camera-tree="cameraTree || []"
          :total="codeShowList.length"
          :no-integration-num="noIntegrationNum"
          :no-networking-num="noNetworkingNum"
        />
      </div>
      <div class="cameraSettingWrapper">
        <div class="cameraView">
          <CameraViewSetting v-if="cameraDetailStore.cameraId" @change-tree-render="changeRender" />
          <div class="cameraPlaceholder" v-else>请选择左侧相机</div>
        </div>
      </div>
    </div>
  </div>
</template>

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

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

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

  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 updateRender(data, targetData, targetVal) {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      if (node.id === targetData) {
        node.render = targetVal;
      }
      if (node.children && node.children.length > 0) {
        updateRender(node.children, targetData, targetVal);
      }
    }
  }

  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;
  }

  const changeRender = (render: string | number) => {
    updateRender(cameraTree.value, cameraDetailStore.cameraId, render);
  };

  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 = getCameraDetail(cameraTree.value, cameraDetailStore.cameraId);
        if (detail) {
          cameraDetailStore.setDetail(detail);
          if (detail?.isPtz === IsPtz.disabled) {
            presetListStore.currentPresetToken = presetList?.[0].token;
          }
        }

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

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

  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>
  .cameraParamsSetting {
    width: 350px;
    min-height: 300px;
    // border: 1px solid #ccc;
  }

  .cameraParamsSetting {
    width: 350px;
    min-height: 300px;
    // border: 1px solid #ccc;
  }

  .algorithmsSetting {
    flex: 1;
    border-left: 1px solid #ccc;
    padding-left: 20px;
  }
  .cameraMain {
    display: flex;
    background: #fff;
    height: calc(100vh - 90px);
  }
  .cameraTree {
    width: 250px;
    flex-shrink: 0;
    // height: 800px;
    // border: 1px solid #ccc;
    border: 1px solid #f0f2f5;
    margin: 5px;
  }

  .cameraPlaceholder {
    color: #333;
    text-align: center;
    margin-top: 100px;
    margin-left: 100px;
  }
</style>
