package com.qs.mp.framework.web.service;

import com.alibaba.fastjson.JSONObject;
import com.qs.mp.channel.domain.Channel;
import com.qs.mp.channel.service.IChannelService;
import com.qs.mp.common.constant.Constants;
import com.qs.mp.common.core.redis.RedisCache;
import com.qs.mp.common.enums.ChannelRoleEnum;
import com.qs.mp.common.enums.ChannelStatusEnum;
import com.qs.mp.common.enums.UserIdentityEnum;
import com.qs.mp.common.exception.ServiceException;
import com.qs.mp.common.exception.user.CaptchaException;
import com.qs.mp.common.exception.user.CaptchaExpireException;
import com.qs.mp.common.exception.user.UserPasswordNotMatchException;
import com.qs.mp.common.utils.DateUtils;
import com.qs.mp.common.utils.MessageUtils;
import com.qs.mp.common.utils.ServletUtils;
import com.qs.mp.common.utils.ip.IpUtils;
import com.qs.mp.core.domain.LoginUser;
import com.qs.mp.framework.manager.AsyncManager;
import com.qs.mp.framework.manager.factory.AsyncFactory;
import com.qs.mp.framework.security.mobile.auth.SmsCodeAuthenticationToken;
import com.qs.mp.sms.domain.SmsCode;
import com.qs.mp.system.domain.SysUser;
import com.qs.mp.system.service.ISysConfigService;
import com.qs.mp.system.service.ISysUserService;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

/**
 * 登录校验方法
 *
 * @author ygp
 */
@Component
public class SysLoginService
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());


    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IChannelService channelService;

    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @param identity 唯一标识
     * @return 结果
     */
    public Map<String, String> login(String username, String password, String code, String uuid, int identity)
    {
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        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());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return buildUserToken(identity, loginUser);
    }

    private Map<String, String> buildUserToken(int identity, LoginUser loginUser) {
        recordLoginInfo(loginUser.getUser());
        HashMap<String, String> result = new HashMap<>();

        loginUser.setIdentity(UserIdentityEnum.valueOf(identity));
        if (!loginUser.getUsername().equals("admin") && UserIdentityEnum.isChannel(
            loginUser.getIdentity().ordinal())) {
            ChannelRoleEnum roleEnum = fillChannelInfo(loginUser);
            result.put(Constants.CHANNEL_ROLE, roleEnum.getValue());
        }

        // 生成token
        String token = tokenService.createToken(loginUser);
        result.put(Constants.TOKEN, token);

        return result;
    }

    public Map<String, String> wxAuthLogin(String username, int identity)
    {
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) userDetailsService.loadUserByUsername(username);
        return buildUserToken(identity, loginUser);
    }

    public Map<String, String> login(SmsCode smsCode)
    {
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            logger.info("短信验证码登录...");
            authentication = authenticationManager
                .authenticate(new SmsCodeAuthenticationToken(smsCode.getMobile(),
                    smsCode.getMessageId(), smsCode.getCode()));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(smsCode.getMobile(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(smsCode.getMobile(), Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(smsCode.getMobile(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return buildUserToken(smsCode.getIdentity(), loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + 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();
        }
    }

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(SysUser user)
    {
        user.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        user.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(user);
    }

    /**
     * 填充注入Channel 渠道/经销商  信息
     * @param loginUser
     */
    public ChannelRoleEnum fillChannelInfo(LoginUser loginUser){
    	Channel channel = channelService.getChannelByUserId(loginUser.getUserId());
        if (null != channel && ChannelStatusEnum.OFF != channel.getStatus()){
          loginUser.setChannelId(channel.getChannelId());
          loginUser.setChannelNo(channel.getChannelNo());
          if (channel.getLevel() == 0) {
              return ChannelRoleEnum.SALESITE;
          } else {
              return ChannelRoleEnum.CHANNEL;
          }
        } else {
            throw new ServiceException("登录账号不存在");
        }
    }


}
