import AsyncStorage from '@react-native-community/async-storage';
import axios from 'axios';
import * as api from '../services/admin';

export default {
  namespace: 'admin',
  state: {
    auth: {},
    socket: '',
    autoClick: true,
  },
  reducers: {
    setAuth(state, {id, auth, login}) {
      state.id = id;
      state.auth = auth;
      window.auth = auth;
      if (window.socket) {
        if (window.socket.io) {
          window.socket.io.opts.query = {
            token: auth.token,
          };
        } else {
          // 使用原生SocketIO
          window.socket = window.socket.initialize({
            query: `token=${window.auth.token}`,
          });
        }
      }
      AsyncStorage.setItem('auth', JSON.stringify(auth));
      if (login) {
        AsyncStorage.setItem('login', login);
      }
      return {...state};
    },
    setSocket(state, {socket}) {
      state.socket = socket;
      return {...state};
    },
    autoClick(state, {autoClick}) {
      state.autoClick = autoClick;
      return {...state};
    },
  },
  effects: {
    *auth(action, {put, call}) {
      let login = action.login;
      action.device = login;
      delete action.login;
      if (action.host) {
        axios.defaults.baseURL = action.host;
      }
      const {data} = action.key
        ? yield call(api.token, action)
        : yield call(api.refreshToken);
      if (data && data.code === 1) {
        if (data.data && data.data.contact) {
          yield call(AsyncStorage.setItem, 'CONTACT', data.data.contact);
        }
        if (data.data && data.data.name) {
          yield call(AsyncStorage.setItem, 'NAME', data.data.name);
        }
        if (action.key) {
          yield call(AsyncStorage.setItem, 'KEY', action.key);
        }
        if (action.host) {
          yield call(AsyncStorage.setItem, 'HOST', action.host);
        }
        yield put({type: 'setAuth', id: data.id, auth: data.data, login});
      }
      return data;
    },
    *logout(action, {put, call}) {
      yield call(AsyncStorage.removeItem, 'auth');
      yield put({type: 'app/replace', route: 'home'});
    },
    *version(action, {call}) {
      yield call(api.version);
    },
  },
};
