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

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

import { setCookie, getCookie } from '@/utils/method';
import { message } from 'antd';

import moment from 'moment';

export interface StateType {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
  token?: string;
  userName?: string;
  password?: string;
  result?: boolean;
}

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

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

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

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

    saveToken(state, { token, userName, password, result }) {
      return { ...state, token, userName, password, result };
    },

    resetPwd(state, { result, userName }) {
      console.log(result, userName);
      return { ...state, result, userName };
    },
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(AccountLogin, payload);
      if (response.status === 'resetPwd') {
        // console.log('跳转到修改密码页面');
        yield put({
          type: 'resetPwd',
          result: true,
          userName: response.userName,
        });
        message.success('Reset your password for your first login!', 3);
        history.push('/user/login2');
      } else if (response.status === 'ok' && response.token != null) {
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        });
        // Login successfully response.status === 'ok'
        message.success('Login Successfully!', 3);
        const userMessage = yield call(AccountCheckLogin, payload); //请求时间网络

        setCookie('token', userMessage.token);
        setCookie('id', userMessage.userModel.id);
        setCookie('name', userMessage.userModel.tosUserName);
        setCookie('phone', userMessage.userModel.tosUserPhone);
        // 更新用户信息
        localStorage.setItem('userInfo', JSON.stringify(userMessage));
        localStorage.setItem('permission', JSON.stringify(userMessage.permission));
        // console.log('获取到Token:' + getCookie('token'));
        // 设置 登录的时间
        localStorage.setItem('loginTime', JSON.stringify(moment().format('YYYY-MM-DD HH:mm:ss')));

        yield put({
          type: 'saveToken',
          token: userMessage.token,
          userName: payload.userName,
          password: payload.password,
          result: false,
        });

        // 路由缓存  再次登录回到上次打开页面
        // 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 || '/');
        // 只跳到首页
        history.replace('/');
      } else {
        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) {
        // 清楚用户信息
        localStorage.removeItem('userInfo');
        localStorage.removeItem('permission');
        setCookie('token', '');
        setCookie('id', '');
        setCookie('name', '');
        setCookie('phone', '');
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },

    *reset({ payload }, { call, put }) {
      const res = yield call(resetPassword, payload);
      console.log(res);
      if (res.error_code === '0000') {
        message.success('Modified successfully, please log in again!', 3);
        history.push('/');
      } else {
        message.error('Change password failed,Please try again!');
      }
    },

    *goResetPwd({ payload }, { call, put }) {
      console.log('跳转到修改密码页面');
      console.log(payload);
      yield put({
        type: 'resetPwd',
        result: false,
        userName: payload,
      });
      history.push('login2');
    },
  },
};

export default Model;
