import browser from '/@/utils/browser';
import axios, { AxiosResponse } from 'axios';
import { ref, computed, unref } from 'vue';
import { useRtcStore } from '../store/modules/rtc';

const roomParam = browser.getURLParam('roomId');

interface roomDataType extends SceneItemType {
  sceneData: SceneItemType[];
}
export interface SceneItemType {
  id: number;
  roomId: number;
  buildObjStatus: number;
  createTime: string;
  name: string;
  num: string;
  payStatus: number;
  sceneName: string;
  snCode: string;
  status: number;
  thumb: string;
  title: string;
  viewCount: number;
  isLaser: boolean;
  type: number;
  phone: Nullable<string>;
  bind: boolean;
  takeLookLock: number;
  maxMan: number;
  useEndTime: string;
  useStartTime: string;
}

export const room = ref<Nullable<roomDataType>>(null);
export const roomId = roomParam;
export const sceneList = computed<SceneItemType[]>(() => unref(room)?.sceneData || []);
export const isLeader = browser.getURLParam('role') === 'leader';
export const currentNum = browser.getURLParam('m');
export const firstNum = computed(() => unref(sceneList)[0].num);
export const currentSceneIndex = computed(() =>
  unref(sceneList).findIndex((i) => i.num === browser.getURLParam('m')),
);

interface roomParamsType {
  name: string;
  role: string;
  vruserId: string;
  isTour: number;
  roomId: string;
  avatar: string;
}

interface getSignType {
  expire: number;
  sdkAppId: number;
  sign: string;
}

function createNewURL(params: roomParamsType): string {
  let tempUrl = window.location.href;
  // ['mode', 'name', 'role', 'vruserId']
  Object.keys(params).forEach((item) => {
    tempUrl = browser.replaceQueryString(tempUrl, item, params[item]);
    console.log('tempUrl', tempUrl);
  });
  return tempUrl;
}
function createNewURLEntry(params: roomParamsType) {
  const tempUrl = createNewURL(params);
  history.replaceState(null, '', tempUrl);
}

export function useRoom() {
  return {
    room,
    sceneList,
    currentScene,
    changeScene,
    initialRoom,
    enterRoom,
    leaveRoom,
    createNewURLEntry,
    createNewURL,
    getSign,
    validPassRoom,
    shareRoom,
    currentSceneIndex,
    currentNum,
    firstNum,
  };
}

export const currentScene = computed(() => {
  const num = browser.getURLParam('m');
  return sceneList.value.find((scene) => scene.num === num);
});

export const changeScene = (scene: SceneItemType) => {
  const rtcStore = useRtcStore();
  if (currentScene.value?.num !== scene.num && scene?.num.length) {
    console.log(scene, currentScene.value);
    const params = new URLSearchParams(location.search);
    params.set('m', scene.num);
    const url = new URL(location.href);
    url.search = `?` + params.toString();
    location.replace(url);
    rtcStore.clearMemberList();
  } else {
    // location.reload();
  }
};

const shopAxios = axios.create({
  // baseURL: !import.meta.env.DEV ? import.meta.env.VITE_APP_APIS_URL : '',
  baseURL: import.meta.env.VITE_APP_APIS_URL,
});

export const initialRoom = async () => {
  const res = await shopAxios.get('/takelook/roomInfo', { params: { roomId } });
  room.value = res.data.data;
};

export const enterRoom = async () => {
  // if (!isLeader) return;
  const rtcStore = useRtcStore();
  const userID = rtcStore.userId || browser.getURLParam('vruserId');
  const role = rtcStore.role || browser.getURLParam('role');
  console.log('111', room.value);
  await shopAxios.get('/takelook/inOrOutRoom', {
    params: {
      type: 0,
      role: role,
      roomId,
      userId: userID,
    },
  });
};

export const leaveRoom = async () => {
  // if (!isLeader) return;
  const rtcStore = useRtcStore();
  const userID = rtcStore.userId || browser.getURLParam('vruserId');
  const role = rtcStore.role || browser.getURLParam('role');
  await shopAxios.get('/takelook/inOrOutRoom', {
    params: {
      type: 1,
      role: role,
      roomId,
      userId: userID,
    },
  });
};

export const shareRoom = async (roomId: string, userId: string) => {
  // if (!isLeader) return;
  return shopAxios.get('/takelook/shareRoom', {
    params: {
      userId,
      roomId,
    },
  });
};

// if (roomId) {
//   shopAxios.get('/takelook/roomAddView', { params: { roomId } });
// }

export const getSign = async (userId: string): Promise<getSignType> => {
  const res = await shopAxios.get<AxiosResponse>('/takelook/tencentYun/getSign', {
    params: {
      userId,
    },
  });
  return res.data.data;
};

export const validPassRoom = async (roomId: string, password: string) => {
  const res = await shopAxios.post('/takelook/checkRoomVisitPassword', {
    roomId: roomId,
    password: password,
  });

  return res.data?.data || false;
};
