package com.fdkankan.platform.user.service.sso;

import com.fdkankan.common.constant.*;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.user.SSOLoginHelper;
import com.fdkankan.common.user.SSOUser;
import com.fdkankan.common.util.RandomUtil;
import com.fdkankan.common.util.SecurityUtil;
import com.fdkankan.common.util.SsoUtil;
import com.fdkankan.common.validation.Variable;
import com.fdkankan.platform.goods.entity.Camera;
import com.fdkankan.platform.goods.entity.CameraDetail;
import com.fdkankan.platform.goods.service.ICameraDetailService;
import com.fdkankan.platform.goods.service.ICameraService;
import com.fdkankan.platform.user.entity.User;
import com.fdkankan.platform.user.request.RequestUser;
import com.fdkankan.platform.user.service.IUserService;
import com.fdkankan.platform.user.vo.ResponseUser;
import com.fdkankan.platform.user.vo.SSOUserVo;
import com.fdkankan.redis.constant.RedisKey;
import com.fdkankan.redis.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Set;

@Service
public class AppService {
    private static Logger log = LoggerFactory.getLogger("programLog");

    @Autowired
    private ICameraService cameraService;
    @Autowired
    private ICameraDetailService cameraDetailService;
    @Autowired
    private IUserService userService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private RegisterService registerService;
    @Autowired
    private SSOLoginHelper ssoLoginHelper;
    @Autowired
    private RedisUtil redisUtil;

    public String qrCodeLogin(RequestUser user) {
        if(StringUtils.isEmpty(user.getAppUserName()) || StringUtils.isEmpty(user.getAppPassword())
                || StringUtils.isEmpty(user.getUuid())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        Camera dbCameraEntity = cameraService.getByChildNameAndChildPassword(user.getAppUserName(),user.getAppPassword());
        if (dbCameraEntity == null){
            throw new BusinessException(CameraConstant.FAILURE_6003);
        }
        CameraDetail entity = cameraDetailService.getByCameraId(dbCameraEntity.getId());
        if (entity == null ){
            throw new BusinessException(AppConstant.FAILURE_CODE_4012, AppConstant.FAILURE_MSG_4012);
        }
        redisUtil.set(user.getUuid(),user.getAppUserName(), RedisKey.EXPIRE_TIME_2_HOUR);
        return ServerCode.SUCCESS.message();
    }

    public HashMap<String, String> passwordLogin(RequestUser user) {
        if(StringUtils.isEmpty(user.getAppUserName()) || StringUtils.isEmpty(user.getAppPassword())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        Camera cameraEntity = cameraService.getByChildNameAndChildPassword(user.getAppUserName(),user.getAppPassword());
        if (cameraEntity == null){
            throw new BusinessException(ErrorCode.PASSWORD_ERROR);
        }
        String token = ssoLoginHelper.login(LoginType.APP.code(), cameraEntity.getChildName(), RedisKey.CAMERA_EXPIRE_7_TIME);
        HashMap<String,String> obj = new HashMap<>();
        obj.put("token", token);
        return obj;
    }

    public SSOUserVo userNameLogin(RequestUser user) {
        User dbUser = userService.getUserByUserName(user.getPhoneNum());
        SSOUser ssoUser = userService.getSsoUserByUserName(dbUser,user.getPhoneNum());
        if(ssoUser == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }
        String passwordCode = SecurityUtil.MD5(user.getPassword());
        if (!passwordCode.equals(ssoUser.getPassword())){
            throw new BusinessException(ErrorCode.PASSWORD_ERROR);
        }
        return this.setRedisToken(ssoUser,dbUser,user.getCameraType());
    }

    public SSOUserVo quickLogin(RequestUser user) {
        User dbUser = msgService.checkMsgAuth(user);
        SSOUser ssoUser = userService.getSsoUserByUserName(dbUser,user.getPhoneNum());
        if(ssoUser == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }
        ssoLoginHelper.logout(LoginType.APP.code(),user.getPhoneNum());
        return this.setRedisToken(ssoUser,dbUser,user.getCameraType());
    }

    private SSOUserVo setRedisToken(SSOUser ssoUser,User userEntity,Integer CameraType){
        String token = ssoLoginHelper.login(LoginType.APP.code(), ssoUser.getUserName());
        Integer cameraType = CameraType == null ? 4 : CameraType;
        return userService.getUserInfoByUser(cameraType, userEntity, token);
    }

    public String logout(String token) {
        ssoLoginHelper.logout(token);
        return ServerCode.SUCCESS.message();
    }

    public String register(RequestUser user) {
        user.setConfirmPwd(user.getPassword());
        registerService.register(user);
        return ServerCode.SUCCESS.message();
    }

    public ResponseUser getRandomNickName() {
        String nickName = null;

        while(nickName == null){
            nickName = "mob" + RandomUtil.generateShortUuid();
            SSOUser ssoUser = userService.getByNickName(nickName);
            if(ssoUser != null){
                nickName = null;
                log.info("昵称已存在：" + nickName);
            }
        }
        ResponseUser vo = new ResponseUser();
        vo.setNickName(nickName);
        log.info("获取的随机昵称：" + nickName);
        return vo;
    }

    public String checkUserName(RequestUser user) {
        if(StringUtils.isEmpty(user.getAppUserName())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }

        User dbUser = userService.getUserByUserName(user.getAppUserName());
        if(dbUser != null){
            throw new BusinessException(ErrorCode.PHONE_EXIST);
        }
        return ServerCode.SUCCESS.message();
    }

    public String resetPassword(RequestUser user) {
        if(StringUtils.isEmpty(user.getPhoneNum()) || StringUtils.isEmpty(user.getPassword()) ||
                StringUtils.isEmpty(user.getMsgAuthCode())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }

        //正则判断密码是否符合规则（8位以上并且数字英文组合）
        if(!user.getPassword().matches(ConstantRegex.PASSWORD_REGEX)){
            throw new BusinessException(ErrorCode.PASSWORD_VIOLATION);
        }

        User userEntity = userService.getUserByUserName(user.getPhoneNum());
        if(userEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }

        //验证码校验
        String codeValue = redisUtil.get(SsoUtil.PREFIX_MSG_AUTH_CODE + user.getPhoneNum());
        if (StringUtils.isEmpty(codeValue)){
            throw new BusinessException(ErrorCode.V_CODE_ERROR);
        }
        if (!codeValue.equals(user.getMsgAuthCode())){
            throw new BusinessException(ErrorCode.V_CODE_ERROR);
        }
        userEntity.setPassword(SecurityUtil.MD5(user.getPassword()));
        redisUtil.del(SsoUtil.PREFIX_MSG_AUTH_CODE + user.getPhoneNum());
        if(!userService.updateById(userEntity)){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        registerService.removeAllToken(user.getPhoneNum());
        return ServerCode.SUCCESS.message();
    }

    public String uploadHead(RequestUser user) {
        if(StringUtils.isEmpty(user.getPhoneNum()) || StringUtils.isEmpty(user.getHead())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }

        User userEntity = userService.getUserByUserName(user.getPhoneNum());
        if(userEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }

        userEntity.setHead(user.getHead() + "?t=" + System.currentTimeMillis());
        if(!userService.updateById(userEntity)){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        return ServerCode.SUCCESS.message();
    }

    public Long getSubPointsFromUserName(RequestUser user) {
        if(StringUtils.isEmpty(user.getPhoneNum())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        User userEntity = userService.getUserByUserName(user.getPhoneNum());
        if(userEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }
        return cameraDetailService.getSumBalanceByUserId(userEntity.getId());
    }

    public ResponseUser getUserInfo(RequestUser user) {
        if(StringUtils.isEmpty(user.getPhoneNum())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        User userEntity = userService.getUserByUserName(user.getPhoneNum());
        if(userEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }
        Integer cameraType = user.getCameraType() == null ? 4 : user.getCameraType();
        SSOUserVo ssoUserVo = userService.getUserInfoByUser(cameraType, userEntity, "");
        return userService.getUserInfoBySsoUserVo(ssoUserVo);
    }

    public String updateNickName(RequestUser user) {
        if (StringUtils.isEmpty(user.getNickName()) || StringUtils.isEmpty(user.getPhoneNum())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        //检验昵称敏感词
        Set<String> set = Variable.sensitiveWord.getSensitiveWord(user.getNickName(), 1);
        if (set != null && set.size() > 0){
            throw new BusinessException(ErrorCode.NICKNAME_ERROR);
        }
        User userEntity = userService.getUserByUserName(user.getPhoneNum());
        if(userEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }
        userEntity.setNickName(user.getNickName());
        if(!userService.updateById(userEntity)){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        return ServerCode.SUCCESS.message();
    }
}
