import { DebugConfigType } from '@/containers/screen-preview-debug/config-container';
import qs from 'qs';
import { getTopScreenId } from './screen';

export const dispatchDebugScreenEvent = <T extends DebugType, K extends DispatchFrom>(
  dispatchData: DebugDataType<T, K>,
) => {
  if (!isOpenEasyVDebugFromUrl()) return;
  document.dispatchEvent(new CustomEvent('debugScreenEvent', { detail: dispatchData }));
};

/**
 *
 * @returns 从缓存中读取大屏调试模式配置
 */
export const getDebugConfigFromSessionStorage = () => {
  let data = JSON.parse(sessionStorage.getItem(`${getTopScreenId()}_debugConfigSession`) || 'null');
  return (data || {
    autoUpdate: false,
    dataRequest: true,
    filterExecute: true,
    callbackSend: true,
    debugListenStatus: 'initialState',
  }) as DebugConfigType;
};

/**
 *
 * @returns  从路径中截取easyvDebug判断是否是开启了调试模式
 */
export const isOpenEasyVDebugFromUrl = () => {
  const { easyvDebug = 'false' } = qs.parse(window.location.search.split('?')[1]) || {};
  return easyvDebug === 'true' && /\/bigscreen\/[0-9]/i.test(window.location.pathname);
};

/**
 * 是否是大屏调试模式且关闭了自动更新
 */
export const isCloseAutoUpdateOnEasyDebugPage = () => {
  const { autoUpdate } = getDebugConfigFromSessionStorage();
  return isOpenEasyVDebugFromUrl() && !autoUpdate;
};

export type DebugType = 'info' | 'error';
export type DispatchFrom = 'dataRequest' | 'filter' | 'callBack';

export type InfoMsg<T extends DispatchFrom> = T extends 'dataRequest'
  ? { callbackValues: any; data: any }
  : T extends 'filter'
  ? { callbackValues: any; data: any; id: number; name: string }
  : { callbackValues: any };

export type ErrorMsg<T extends DispatchFrom> = T extends 'callBack'
  ? { message: string }
  : T extends 'dataRequest'
  ? { message: string; callbackValues: any; data: any }
  : { callbackValues: any; data: any; id: number; name: string; message: string };

export type DebugMsgType<T extends DebugType, K extends DispatchFrom> = T extends 'info'
  ? InfoMsg<K>
  : ErrorMsg<K>;

export type DebugDataType<
  T extends DebugType = DebugType,
  K extends DispatchFrom = DispatchFrom,
> = {
  type: T;
  name: string;
  id: number;
  dispatchFrom: K;
  debugMsg: DebugMsgType<T, K>;
};
