import { stringify } from 'querystring';
import { history, Reducer, Effect } from 'umi';

import { AccountLogin, AccountCheckLogin, AccountOut } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';

import { setCookie, getCookie } from '@/utils/method';
import { message } from 'antd';
export interface StateType {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
  token?: string;
  userName?: string;
  password?: string;
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
    token: '',
    userName: '',
    password: '',
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
    saveToken(state, { token, userName, password }) {
      return { ...state, token, userName, password };
    },
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(AccountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully response.status === 'ok'
      if (response.token != null) {
        console.log('用户名密码登录成功');
        console.log(response);
        const userMessage = yield call(AccountCheckLogin, payload); //请求时间网络
        console.log(userMessage);
        console.log(userMessage.token);
        setCookie('token', userMessage.token);
        // tosUserName: "admin"
        // tosUserPhone: "18818881888"
        setCookie('name', response.token.tosUserName);
        setCookie('phone', response.token.tosUserPhone);
        setCookie('id', response.token.id);
        console.log('获取到Token:' + getCookie('token'));
        yield put({
          type: 'saveToken',
          token: userMessage.token,
          userName: payload.userName,
          password: payload.password,
        });
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params as { redirect: string };
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }
        history.replace(redirect || '/');
      } else {
        console.error(response);
        message.error('Login Error! Username or Password is wrong!', 3);
      }
    },

    *logout({}, { call, put }) {
      const { redirect } = getPageQuery();
      // Note: There may be security issues, please note
      // const response = yield call(AccountOut, payload);
      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },
};

export default Model;
