package com.younike.admin.service;

import com.younike.admin.manager.AsyncManager;
import com.younike.admin.manager.factory.AsyncFactory;
import com.younike.admin.utils.ShiroUtils;
import com.younike.common.constant.Constants;
import com.younike.common.constant.ShiroConstants;
import com.younike.common.constant.UserConstants;
import com.younike.common.constant.UserStatus;
import com.younike.common.exception.*;
import com.younike.common.redis.ICached;
import com.younike.common.spring.SpringContextHolder;
import com.younike.common.utils.i18n.MessageUtils;
import com.younike.common.utils.servlet.ServletUtils;
import com.younike.common.utils.string.StringUtils;
import com.younike.service.pojo.SysUser;
import com.younike.service.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 登录校验方法
 */
@Component
public class SysLoginService {

    @Autowired
    ICached iCached;

    @Autowired
    SysPasswordService sysPasswordService;
    /**
     * 登录
     */
    public SysUser login(String username, String password) {
        // 验证码校验
        String captcha = (String) ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA);
        String verifyKey = Constants.CAPTCHA_CODE_KEY + ServletUtils.getRequest().getAttribute(ShiroConstants.UUID);
        if (StringUtils.isEmpty(captcha) || !captcha.equals(iCached.get(verifyKey))) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }

        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        ISysUserService iSysUserService = SpringContextHolder.getBean(ISysUserService.class);
        // 查询用户信息
        SysUser user = iSysUserService.selectUserByLoginName(username);

        if (user == null && maybeMobilePhoneNumber(username)) {
            user = iSysUserService.selectUserByPhoneNumber(username);
        }

        if (user == null && maybeEmail(username)) {
            user = iSysUserService.selectUserByEmail(username);
        }

        if (user == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.not.exists")));
            throw new UserNotExistsException();
        }

        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.delete")));
            throw new UserDeleteException();
        }

        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.blocked", user.getRemark())));
            throw new UserBlockedException();
        }

        sysPasswordService.validate(user, password);

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        recordLoginInfo(user);
        return user;
    }

    /**
     * 短信登录
     *
     * @Param phoneNumber 手机号
     * @Param code 验证码
     */
    public SysUser smsLogin(String phoneNumber, String code) {

//        // 验证码校验
//        if (!StringUtils.isEmpty(ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA))) {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
//            throw new CaptchaException();
//        }
//        // 用户名或密码为空 错误
//        if (StringUtils.isEmpty(phoneNumber) || StringUtils.isEmpty(code)) {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
//            throw new UserNotExistsException();
//        }
//
//        // 查询用户信息
//        SysUser user = userService.selectUserByPhoneNumber(phoneNumber);
//
//        if (user == null) {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, Constants.LOGIN_FAIL, MessageUtils.message("user.not.exists")));
//            throw new UserNotExistsException();
//        }
//
//        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, Constants.LOGIN_FAIL, MessageUtils.message("user.password.delete")));
//            throw new UserDeleteException();
//        }
//
//        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, Constants.LOGIN_FAIL, MessageUtils.message("user.blocked", user.getRemark())));
//            throw new UserBlockedException();
//        }
//
//        if (!Convert.toStr(CacheUtils.get(Constants.SMS_LOGIN_CODE, phoneNumber)).equals(code)) {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, Constants.LOGIN_FAIL, MessageUtils.message("user.blocked", user.getRemark())));
//            throw new VerificationCodeErrorException();
//        }
//
//        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
//        recordLoginInfo(user);
        return null;
    }


    private boolean maybeEmail(String username) {
        return username.matches(UserConstants.EMAIL_PATTERN);
    }

    private boolean maybeMobilePhoneNumber(String username) {
        return username.matches(UserConstants.MOBILE_PHONE_NUMBER_PATTERN);
    }

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(SysUser user) {
        user.setLoginIp(ShiroUtils.getIp());
        user.setLoginDate(new Date());
        ISysUserService iSysUserService = SpringContextHolder.getBean( ISysUserService.class);
        iSysUserService.updateUserInfo(user);
    }
}
