import '@babel/polyfill';
import { message } from 'antd';
import dva from 'dva';
import createLoading from 'dva-loading';
import createHistory from 'history/createBrowserHistory';
import appModel from './models/app';
import './raven';
import routers from './router';
// import Raven from 'raven-js';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { config } from './utils';

const { prefix } = config;


moment.locale('zh-cn');

message.config({
  // duration: 2,
  top: 100,
});

// 1. Initialize
const initialState = {
  app: {
    user: null,
    msgCnt: { warn: 0, info: 0, todo: 0 },
    menuPopoverVisible: false,
    menu: null,
    perms: null,
    siderFold: false,
    darkTheme: true,
    isNavbar: document.body.clientWidth < 769,
    // navOpenKeys: ['h'],
    navOpenKeys: ['home'],
  },
  dashboard: {
    todoList: [],
    anncList: [],
  },
};

const handleReducer = (combination) => (state, action) => {
  const newState = combination(state, action);
  if (action.type === 'app/logout/@@end') {
    sessionStorage.removeItem('user');
    return {
      routing: newState.routing,
      loading: newState.loading,
      ...initialState,

      // ...state,
      // dashboard: null,
    };
  } else if (action.type === 'app/query') {
    const storedUser = JSON.parse(sessionStorage.getItem('user'));

    console.log(state);
    console.log(newState);

    return {
      ...newState,
      app: {
        ...newState.app,
        user: storedUser,
      },
    };
  } else if (action.type === 'app/query/@@end') {
    sessionStorage.setItem('user', JSON.stringify(state.app.user));
    return newState;
  } else {
    return newState;
  }
};


const app = dva({
  ...createLoading({
    // global: false,
    effects: true,
  }),
  onReducer: handleReducer,
  onStateChange: (state) => {
    // console.log(state);
  },
  history: createHistory(),
  onError(error) {
    // Raven.captureException(error);
    // if (error.message) {
    //   message.error(error.data ? `${error.message} ${error.data.toString()}` : error.message, 5);
    // }
    if (error.status === 401) return;
    console.error('[EL-SYS]', error);
    message.error(error.message || '[EL-SYS] 未知错误，请联系开发人员');
  },
});

// 2. Plugins
app.use({});

// 3. Model
app.model(appModel);

// 4. Router
app.router(routers);

// 5. Start
app.start('#root');
