import { request } from 'utils/fetch';
import { api } from 'constants/config';
import { actionTypes } from 'constants/action-types';
import { getScreenInfo } from 'models/screen';
import { getFonts } from './font';
import { getPanelsFromLayers } from 'utils/layer';
import { getId } from 'utils/interaction';
import { getPanelInfoForScreenPreview } from './panel';
import { urlCacheReplace, isEasyvCache } from 'utils/utils';
import { dispatchUpdateScreenStatus } from './screensStatus';

export function getScreenDetail(id: number, signal?: AbortSignal) {
  return async (dispatch) => {
    dispatch({
      type: actionTypes.SCREEN_DETAIL_GET_START,
      payload: {
        id,
      },
    });

    const result = await dispatch(getNecessaryScreens(id, signal));

    if (!result) {
      dispatch({
        type: actionTypes.SCREEN_DETAIL_GET_FAILURE,
      });
      return;
    } else {

      if (result === ScreenType.NOT_FOUND) {
        // 不存在
        dispatch({
          type: actionTypes.SCREEN_DETAIL_GET_DELETE,
        });
        return;
      } else if (result === ScreenType.PASSWORD) {
        //  表示大屏需要分享密码
        dispatch({
          type: actionTypes.SCREEN_DETAIL_NEED_PASSWORD,
        });
        return;
      } else if (result === ScreenType.TOKEN) {
        // 表示token
        dispatch({
          type: actionTypes.SCREEN_DETAIL_NEED_TOKEN,
        });
        return;
      } else if (result === ScreenType.USER_EXPIRED) {
        // 用户过期
        dispatch({
          type: actionTypes.SCREEN_DETAIL_NEED_USER_EXPIRED,
        });
        return;
      } else {
        // 正常状态
        // 拉大屏水印
        !isEasyvCache() && (await dispatch(getScreenPermission(id)));
        await dispatch(getFonts());
        dispatch({
          type: actionTypes.SCREEN_DETAIL_GET_SUCCESS,
          payload: {
            tenantId: result.tenantId,
          },
        });
      }
    }
    return result;

  };
}

export function getNecessaryScreens(id: number, signal?: AbortSignal) {
  return async (dispatch) => {
    const result = await dispatch(getScreenInfo(id, signal));
    if (result && typeof result === 'object') {
      const { layers } = result;
      const panels = getPanelsFromLayers(layers);
      await Promise.all(
        panels
          .filter((d) => d.show && d.hideDefault !== true)
          .map(async (d) => {
            const panelResult = await dispatch(getPanelInfoForScreenPreview(getId(d.id), signal));
            if (panelResult && typeof panelResult === 'object') {
              await dispatch(getNecessaryScreens(panelResult.states[0], signal));
            }
          }),
      );
    }
    return result;
  };
}

export function getAllScreens(id: number, signal: AbortSignal) {
  return async (dispatch) => {
    const result = await dispatch(getScreenInfo(id, signal));
    if (result && typeof result === 'object') {
      const { layers } = result;
      const panels = getPanelsFromLayers(layers);
      await Promise.all(
        panels
          .filter((d) => d?.show)
          .map(async (d) => {
            const panelResult = await dispatch(getPanelInfoForScreenPreview(getId(d.id), signal));
            if (panelResult && typeof panelResult === 'object') {
              await Promise.all(panelResult.states.map((o) => dispatch(getAllScreens(o, signal))));
            }
          }),
      );
    }
    return result;
  };
}

export function getScreenPermission(id: number) {
  // 获取大屏许可

  return async (dispatch) => {
    if (!window.appConfig.LOCAL) {
      const result = await request(api.screenWatermark, { id }, undefined, undefined, {
        error: () => {
          //
        },
      });
      // TODO水印开关
      dispatch({
        type: actionTypes.SCREEN_DETAIL_PERMISSION,
        payload: {
          permission: result ? !result?.watermark : true,
          authKey: result.edition,
        },
      });
    }
  };
}

/**
 * @description 根据大屏ID和密码获取大屏数据,用在大屏发布页
 * @param password
 * @param screenId
 * @param isMainScreen 是否是主屏，如果是则需要reload
 * @param errorCallBack 初次加载的时候密码错误不提示，后续用户输入密码获取大屏时错误则抛错
 * @returns
 */
export function getScreenDataByPasswordAndId(
  password: string,
  screenId: number,
  isMainScreen: boolean,
  errorCallBack?: () => void,
) {
  return async (dispatch) => {
    const result = await request(
      urlCacheReplace(api.screenSharedGet),
      { screenId },
      { password },
      undefined,
    );
    const screenResult = await dispatch(getScreenInfo(screenId));

    if (result && screenResult && screenResult !== -1) {
      isMainScreen && window.location.reload();
    } else {
      errorCallBack?.();
    }

    dispatchUpdateScreenStatus(dispatch, {
      screenId,
      statusCode: result,
    });
    dispatch({
      type: actionTypes.SCREEN_DETAIL_GET_RESULT,
      payload: result,
    });
  };
}

export function setScreenResult(result) {
  return async (dispatch) => {
    if (result === -2 && !window.location.search.includes('_easyv_token')) {
      dispatch({
        type: actionTypes.SCREEN_DETAIL_GET_RESULT,
        payload: 0,
      });
      return false;
    }
    typeof result === 'object' &&
      dispatch({
        type: actionTypes.SCREEN_DETAIL_GET_RESULT,
        payload: result,
      });
  };
}

export function setScreenState(text) {
  return async (dispatch) => {
    dispatch({
      type: actionTypes.SCREEN_DETAIL_SET_ACTIVATED,
      payload: text,
    });
  };
}

export function setCenterActivatedState(text) {
  return async (dispatch) => {
    dispatch({
      type: actionTypes.SCREEN_DETAIL_SET_CENTER_ACTIVATED,
      payload: text,
    });
  };
}

export interface screenDetailType {
  loading: boolean;
  id: null | number | string;
  needPassword: boolean;
  screenDelete: boolean;
  userExpired: boolean;
  tenantId: null | number | string;
  needToken: boolean;
  result: ScreenType;
  activatedState: string; //操作面板
  centerActivatedState: string;
  permission: boolean;
  authKey: string;
}

export enum ScreenType {
  'NORMAL' = 0, // 默认，正常
  'PASSWORD' = -1, // 需要密码
  'NOT_FOUND' = -404, // 404 找不到
  'TOKEN' = -2, // 需要token或者token校验未过
  'USER_EXPIRED' = -3, // 大屏所属用户已过期
}

const initialState: screenDetailType = {
  loading: true,
  id: null,
  needPassword: false,
  tenantId: null,
  needToken: false,
  screenDelete: false,
  userExpired: false,
  result: ScreenType.NORMAL,
  activatedState: '', //操作面板
  centerActivatedState: '', // 中控面板
  permission: true,
  authKey: '',
};

export default function reducer(state = initialState, { type, payload }) {
  switch (type) {
    case actionTypes.SCREEN_DETAIL_GET_START: {
      return {
        ...state,
        loading: true,
        id: payload.id,
        screenDelete: false,
        needPassword: false,
        needToken: false,
      }; // 初始化大屏状态
    }

    case actionTypes.SCREEN_DETAIL_GET_SUCCESS: {
      const { tenantId = state.tenantId } = payload;
      return { ...state, loading: false, tenantId };
    }

    case actionTypes.SCREEN_DETAIL_PERMISSION: {
      const { permission, authKey } = payload;
      return { ...state, permission, authKey };
    }

    case actionTypes.SCREEN_DETAIL_SET_CENTER_ACTIVATED: {
      return { ...state, centerActivatedState: payload };
    }

    case actionTypes.SCREEN_DETAIL_GET_FAILURE: {
      return { ...state, loading: false };
    }

    case actionTypes.SCREEN_DETAIL_GET_DELETE: {
      return { ...state, loading: false, screenDelete: true };
    }

    case actionTypes.SCREEN_DETAIL_SET_ACTIVATED: {
      return { ...state, activatedState: payload };
    }

    case actionTypes.SCREEN_DETAIL_NEED_PASSWORD: {
      return { ...state, loading: false, needPassword: true };
    }

    case actionTypes.SCREEN_DETAIL_NEED_TOKEN: {
      return { ...state, loading: false, needToken: true };
    }

    case actionTypes.SCREEN_DETAIL_NEED_USER_EXPIRED: {
      return { ...state, loading: false, userExpired: true };
    }

    case actionTypes.SCREEN_DETAIL_GET_RESULT: {
      return { ...state, result: payload };
    }

    default:
      return state;
  }
}
