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

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;
  roomInfo: string;
  useEndTime: string;
  useStartTime: string;
  video?: string[];
  image?: string[];
  head?: 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;
  operatorType?: number;
}

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();
    // if (browser.isMobile()) {
    //   if (browser.detectIOS()) {
    //     location.replace(url);
    //   } else {
    //     console.warn('安卓跳转减少内存');
    //     history.replaceState(null, document.title, url);
    //     history.go(0);
    //   }
    // } else {
    // location.replace(url);
    // }
    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,
});
const wxToken = browser.getURLParam('wxToken') || '';

if (wxToken) {
  shopAxios.defaults.headers['wxToken'] = wxToken;
}

export const initialRoom = async () => {
  shopAxios.defaults.headers.platform = browser.getURLParam('platform') || '';
  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');
  shopAxios.defaults.headers.platform = browser.getURLParam('platform') || '';

  // overRide测试人数

  if (Number(import.meta.env.VITE_ROOM_MEMBER_DEBUG) === 1) {
    if (room.value) {
      room.value.maxMan = Number(import.meta.env.VITE_ROOM_MEMBER);
      console.warn('测试设置人数: ' + Number(import.meta.env.VITE_ROOM_MEMBER));
    }
  }

  return 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');
  shopAxios.defaults.headers.platform = browser.getURLParam('platform') || '';
  await shopAxios.get('/takelook/inOrOutRoom', {
    params: {
      type: 1,
      role: role,
      roomId,
      userId: userID,
    },
  });
};

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

// if (roomId) {
//   shopAxios.get('/takelook/roomAddView', { params: { roomId } });
// }
export const GET_COMMON_SIG = '/takelook/rtcMedia/getToken';

export const getSign = async (
  userId: string,
  channelName: string,
  roleId: string,
  platform?: string,
): Promise<getSignType> => {
  let role = 1;
  if (roleId === 'leader') {
    role = 1;
  }
  const res = await shopAxios.get<AxiosResponse>(GET_COMMON_SIG, {
    params: {
      userId,
      roleId: role,
      channelName,
      platform,
    },
  });
  return res.data.data;
};

export const validPassRoom = async (roomId: string, password: string) => {
  shopAxios.defaults.headers.platform = browser.getURLParam('platform') || '';

  const res = await shopAxios.post('/takelook/checkRoomVisitPassword', {
    roomId: roomId,
    password: password,
    // wxToken: wxToken,
  });

  return res.data?.data || false;
};
//h5端模拟
export const webLogin = async (nickName: string) => {
  shopAxios.defaults.headers.platform = browser.getURLParam('platform') || '';

  const res = await shopAxios.post('/takelook/webApi/webLogin', {
    nickName: nickName,
  });

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