import Taro from '@tarojs/taro';

import { Action } from 'redux';

import { RoleType, PageType } from '@/constants/app';
import { CacheKey } from '@/constants/cache-key';
import { LocationInfo } from '@/types/location';
import { AppState } from '@/types/store';

import { CHANGE_ROLE_TYPE, CHANGE_HOME_PAGE, SET_LOCATION_INFO } from '../constants';

const DEFAULT_LOCATION: LocationInfo = {
  provinceCode: '440000',
  provinceDesc: '广东省',
  cityCode: '440100',
  cityDesc: '广州市',
  latitude: 23.125178,
  longitude: 113.280637,
};

const defaultAppMode = Taro.getStorageSync<RoleType>(CacheKey.APP_MODE_NEW) || RoleType.Anchor;
const INIT_STATE: AppState = {
  roleType: defaultAppMode,
  homePageType: defaultAppMode === RoleType.Anchor ? PageType.JOB : PageType.Anchor,
  location: Taro.getStorageSync<LocationInfo>(CacheKey.CACHE_LOCATION_INFO) || DEFAULT_LOCATION,
};

const appState = (state: AppState = INIT_STATE, action: Action): AppState => {
  const { type, value } = action as BL.Anything;
  switch (type) {
    case CHANGE_ROLE_TYPE:
      Taro.setStorageSync(CacheKey.APP_MODE_NEW, value);
      return { ...state, roleType: value };
    case CHANGE_HOME_PAGE:
      return { ...state, homePageType: value };
    case SET_LOCATION_INFO:
      Taro.setStorageSync(CacheKey.CACHE_LOCATION_INFO, value);
      return { ...state, location: value };
    default:
      return state;
  }
};

export default appState;
