import { createContext } from "react";

export const Context = createContext({});

// Map 页面唯一状态源：页面组件只读取这些状态，通过 actions 修改，避免再用 mitt 同步 React 状态。
export const initialMapState = {
  coverMaskVisible: false,
  currentPort: "",
  currentBranchOffice: "",
  portArea: "",
  bottomUtilsCurrentIndex: "",
  pureMap: false,
  headerTitle: "秦港股份安全监管平台",
  bottomUtilsResetVersion: 0,
  rightUtilsResetVersion: 0,
  modalVisible: false,
  modalData: {},
};

export const MAP_ACTION = {
  SELECT_PORT: "selectPort",
  SELECT_BRANCH_OFFICE: "selectBranchOffice",
  SELECT_MARK: "selectMark",
  RESET_MARK: "resetMark",
  SET_PORT_AREA: "setPortArea",
  SET_BOTTOM_UTILS_INDEX: "setBottomUtilsIndex",
  RESET_BOTTOM_UTILS: "resetBottomUtils",
  RESET_RIGHT_UTILS: "resetRightUtils",
  SET_PURE_MAP: "setPureMap",
  SET_COVER_MASK_VISIBLE: "setCoverMaskVisible",
};

export function mapReducer(state, action) {
  switch (action.type) {
    case MAP_ACTION.SELECT_PORT: {
      const data = action.payload;
      return {
        ...state,
        currentPort: data.id,
        currentBranchOffice: data.id === "00003" ? "" : data.corpinfoId || state.currentBranchOffice,
        headerTitle: data.id === "00003"
          ? "秦港股份安全监管平台"
          : `${data.name}安全监管平台`,
      };
    }
    case MAP_ACTION.SELECT_BRANCH_OFFICE: {
      const data = action.payload;
      return {
        ...state,
        currentBranchOffice: data.id,
        headerTitle: `${data.corpName || data.name}安全监管平台`,
      };
    }
    case MAP_ACTION.SELECT_MARK: {
      const data = action.payload;
      return {
        ...state,
        modalVisible: true,
        modalData: data,
      };
    }
    case MAP_ACTION.RESET_MARK: {
      return {
        ...state,
        modalVisible: false,
        modalData: {},
      };
    }
    case MAP_ACTION.SET_PORT_AREA:
      return { ...state, portArea: action.payload };
    case MAP_ACTION.SET_BOTTOM_UTILS_INDEX:
      return { ...state, bottomUtilsCurrentIndex: action.payload };
    case MAP_ACTION.RESET_BOTTOM_UTILS:
      return {
        ...state,
        bottomUtilsCurrentIndex: -1,
        bottomUtilsResetVersion: state.bottomUtilsResetVersion + 1,
      };
    case MAP_ACTION.RESET_RIGHT_UTILS:
      return { ...state, rightUtilsResetVersion: state.rightUtilsResetVersion + 1 };
    case MAP_ACTION.SET_PURE_MAP:
      return { ...state, pureMap: action.payload };
    case MAP_ACTION.SET_COVER_MASK_VISIBLE:
      return { ...state, coverMaskVisible: action.payload };
    default:
      return state;
  }
}
