import { Model } from 'dva';
import { delay } from 'dva/saga';
import _ from 'lodash';
import { getLocale, setLocale } from 'umi-plugin-locale'
import { loadUser, storeUser, clearUser, clearMineList, clearCoins, clearDrawCoins } from '@/utils/storage';
import { User } from '@/types/common';
import { isApp, restart } from '@/utils/h5plus';

const initState = () => {
  const user = loadUser();
  return {
    user,
    isLogin: Boolean(user && user.id),
    lang: getLocale(),
  };
}

export interface UserModelState {
  user?: User;
  isLogin: boolean;
  lang: string;
}

const model: Model = {
  namespace: 'user',

  state: initState() as UserModelState,

  effects: {
    *updateUser({ payload }, { put, select }) {
      if (!payload) return;
      const { user }: UserModelState = yield select((state: any) => state.user);
      if (!_.isEqual(payload, user)) {
        const allNew = { ...(user || {}), ...payload };
        yield put({ type: 'onSaveUser', payload: allNew });
        storeUser(allNew);
      }
    },

    *clearUser(_, { put }) {
      yield put({ type: 'onSaveUser' });
      clearUser();
    },

    *updateToken({ payload: token }, { put }) {
      yield put({ type: 'updateUser', payload: { token } });
    },

    *logout(_, { put, all }) {
      clearMineList();
      clearCoins();
      clearDrawCoins();
      yield all([
        put({ type: 'clearUser' }),
        put({ type: 'home/clear' }),
      ]);
    },

    *changeLang({ payload: lang }, { put }) {
      setLocale(lang, false);
      yield put({ type: 'onUpdateState', payload: { lang } });
    },

    *getKycInfo (_, { get }) {
//      const data = await http.post('/user/verify', formData);
//      yield get({type: 'user/verifyInfo'})
      console.info('inside getKycInfo')

    },
  },

  reducers: {
    onUpdateState(state, { payload }: any) {
      return {
        ...state,
        ...payload,
      };
    },

    onSaveUser(state, { payload }: any) {
      return {
        ...state,
        user: payload,
        isLogin: Boolean(payload && payload.id),
      };
    }
  },
};

export default model;
