import type { CameraInfo } from '@/api/disaster-overview';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import urlJoin from 'url-join';

const useCameraStore = defineStore('camera', () => {
  //   const curWorkshopCode = ref('');
  const curCamera = ref<CameraInfo | null>(null);

  //   const setCurWorkshopCode = (val: string) => {
  //     curWorkshopCode.value = val;
  //   };

  const setCurCamera = (val: CameraInfo | null) => {
    curCamera.value = val;
  };

  const getCameraUrl = (val: CameraInfo) => {
    if (val.pushStreamDTO && val.pushStreamDTO.videoUrls) {
      const videoUrl = val.pushStreamDTO.videoUrls.pushstreamIp;
      const protocol = window.location.protocol.startsWith('https') ? 'wss' : 'ws';
      // 如果是绝对地址
      if (videoUrl.startsWith('http')) {
        // 如果是https的话，websocket要用wss
        return videoUrl.replace('http', protocol);
      }
      const u = urlJoin(
        `${protocol}://`,
        window.location.host,
        window.location.pathname === '/' ? '' : window.location.pathname,
        videoUrl,
      );
      return u;
    }
    return '';
  };

  const getCameraImg = (val: CameraInfo) => {
    if (val.pushStreamDTO && val.pushStreamDTO.imageUrl) {
      return val.pushStreamDTO.imageUrl;
    }
    return '';
  };

  const getCurCameraUrl = () => {
    return curCamera.value ? getCameraUrl(curCamera.value) : '';
  };

  const getCurCameraImg = () => {
    return curCamera.value ? getCameraImg(curCamera.value) : '';
  };

  const clearCurCamera = () => {
    // curWorkshopCode.value = '';
    curCamera.value = null;
  };

  return {
    // curWorkshopCode,
    curCamera,
    // setCurWorkshopCode,
    setCurCamera,
    getCurCameraUrl,
    getCurCameraImg,
    clearCurCamera,
  };
});

export default useCameraStore;
