package cn.com.taiji.beidou.framework.web.service;

import cn.com.taiji.beidou.common.constant.CacheConstants;
import cn.com.taiji.beidou.common.constant.Constants;
import cn.com.taiji.beidou.common.core.domain.R;
import cn.com.taiji.beidou.common.core.domain.entity.SysUser;
import cn.com.taiji.beidou.common.core.domain.model.LoginUser;
import cn.com.taiji.beidou.common.core.redis.RedisCache;
import cn.com.taiji.beidou.common.exception.ServiceException;
import cn.com.taiji.beidou.common.exception.user.CaptchaException;
import cn.com.taiji.beidou.common.exception.user.CaptchaExpireException;
import cn.com.taiji.beidou.common.exception.user.UserPasswordNotMatchException;
import cn.com.taiji.beidou.common.utils.DateUtils;
import cn.com.taiji.beidou.common.utils.MessageUtils;
import cn.com.taiji.beidou.common.utils.ServletUtils;
import cn.com.taiji.beidou.common.utils.StringUtils;
import cn.com.taiji.beidou.common.utils.ip.IpUtils;
import cn.com.taiji.beidou.framework.manager.AsyncManager;
import cn.com.taiji.beidou.framework.manager.factory.AsyncFactory;
import cn.com.taiji.beidou.framework.security.context.AuthenticationContextHolder;
import cn.com.taiji.beidou.framework.web.util.SmsUtil;
import cn.com.taiji.beidou.system.service.ISysConfigService;
import cn.com.taiji.beidou.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private cn.com.taiji.beidou.framework.web.service.TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private UserDetailsServiceImpl userDetailsService ;

    @Autowired
    private ISysConfigService configService;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        // 验证码开关
        if (captchaEnabled)
        {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    /**
     * 手机号+短信验证码登录
     * @param mobile
     * @param code
     * @return
     */
    public R<LoginUser> loginByCode(String mobile, String code)
    {
        //验证短信验证码
        String cacheCode = redisCache.getCacheObject(mobile)+"";
        if(!"".equals(cacheCode)&&!code.equals(cacheCode)){
            return R.fail("验证码错误！");
        }
        SysUser sysUser = userService.selectUserByPhone(mobile);
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) userDetailsService.createLoginUser(sysUser);
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        loginUser.setToken(tokenService.createToken(loginUser));
        return R.ok(loginUser);
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    /**
     * 获取短信验证码
     * @param telephone
     * @return
     */
    public R getCode(String telephone){
        try {
            SysUser user = new SysUser();
            user.setPhonenumber(telephone);
            SysUser sysUser = userService.selectUserByPhone(telephone);

            if(sysUser==null){
                return R.fail("手机号码不存在！请联系管理员");
            }
            String randomCode = SmsUtil.getRandomCode(6);

            String result = SmsUtil.sendSms(telephone, randomCode);
            if(result.contains("success")){
                //todo 此处将验证码存储到数据库
                redisCache.setCacheObject(telephone,randomCode,10, TimeUnit.MINUTES);
            }
            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("短信发送失败，请稍后重试！");
        }
    }
}
