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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fdkankan.common.constant.ConstantRegex;
import com.fdkankan.common.constant.ConstantUrl;
import com.fdkankan.common.util.Base64Converter;
import com.fdkankan.common.util.SecurityUtil;
import com.fdkankan.common.util.SsoUtil;
import com.fdkankan.common.validation.Variable;
import com.fdkankan.common.user.SSOLoginHelper;
import com.fdkankan.platform.user.entity.User;
import com.fdkankan.platform.user.request.RequestUser;
import com.fdkankan.platform.user.service.IUserService;
import com.fdkankan.redis.util.RedisUtil;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.constant.ServerCode;
import com.fdkankan.common.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Set;

@Service
public class RegisterService {

    @Value("${admin.register.validCode}")
    private  String registerValidCode;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IUserService userService;
    @Autowired
    private SSOLoginHelper ssoLoginHelper;


    private void checkParam(RequestUser param){
        //正则判断密码是否符合规则（8位以上并且数字英文组合）
        if(!param.getPassword().matches(ConstantRegex.PASSWORD_REGEX)){
            throw new BusinessException(ErrorCode.PASSWORD_VIOLATION);
        }
        if (!param.getConfirmPwd().equals(param.getPassword())){
            throw new BusinessException(ErrorCode.PASSWORD_TWO_VIOLATION);
        }
//        if ("86".equals(param.getCountry()) && !PatternUtils.isPhoneNumber(param.getPhoneNum())){
//            throw new BusinessException(ErrorCode.PHONE_VIOLATION);
//        }
        //验证码校验
        String msgAuthCode = param.getMsgAuthCode();
        if (!StringUtils.equals(msgAuthCode, registerValidCode)) {
            String codeValue = (String)redisUtil.get(SsoUtil.PREFIX_MSG_AUTH_CODE + param.getPhoneNum());
            if (StringUtils.isEmpty(codeValue)) {
                throw new BusinessException(ErrorCode.V_CODE_ERROR);
            }
            if (!codeValue.equals(param.getMsgAuthCode())) {
                throw new BusinessException(ErrorCode.V_CODE_ERROR);            }
        }

    }


    public void register(RequestUser param) {
        if (StringUtils.isEmpty(param.getPassword()) || StringUtils.isEmpty(param.getPhoneNum()) ||
                StringUtils.isEmpty(param.getMsgAuthCode()) || StringUtils.isEmpty(param.getNickName()) ||
                StringUtils.isEmpty(param.getCountry()) || StringUtils.isEmpty(param.getConfirmPwd())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        User dbUser = userService.getUserByUserName(param.getPhoneNum());
        if (dbUser != null){
            throw new BusinessException(ErrorCode.PHONE_EXIST);
        }
        this.checkParam(param);
        //检验昵称敏感词
        Set<String> set = Variable.sensitiveWord.getSensitiveWord(param.getNickName(), 1);
        if (set != null && set.size() > 0){
            throw new BusinessException(ErrorCode.NICKNAME_ERROR);
        }
        //注册，新建注册用户信息
        User userEntity = new User();
        userEntity.setPassword(SecurityUtil.MD5(param.getPassword()));
        userEntity.setEmail(param.getEmail());
        userEntity.setUserName(param.getPhoneNum());
        userEntity.setRegisterTime(new Date());
        userEntity.setNickName(param.getNickName());
        userEntity.setHead(ConstantUrl.DEFAULT_USER_HEAD);
        userEntity.setCountry(param.getCountry());
        userEntity.setStatus(1);
        userEntity.setIsNotice(1);
        userService.save(userEntity);
        //删除验证码缓存
        redisUtil.del(SsoUtil.PREFIX_MSG_AUTH_CODE + param.getPhoneNum());
    }

    public String changePassword(RequestUser param) {
        if (StringUtils.isEmpty(param.getPassword()) || StringUtils.isEmpty(param.getConfirmPwd()) ||
                StringUtils.isEmpty(param.getMsgAuthCode()) || StringUtils.isEmpty(param.getPhoneNum())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        User dbUser = userService.getUserByUserName(param.getPhoneNum());
        if (dbUser == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }
        this.checkParam(param);
        //对前端传的密码解密
        String password = Base64Converter.decode(Base64Converter.subText(param.getPassword()));
        dbUser.setPassword(SecurityUtil.MD5(password));
        if(!userService.updateById(dbUser)){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        this.removeAllToken(param.getPhoneNum());
        return ServerCode.SUCCESS.message();
    }

    public void removeAllToken(String phone){
        //删除缓存
        redisUtil.del(SsoUtil.PREFIX_MSG_AUTH_CODE + phone);
        JSONArray tokenArray = new JSONArray();
        if(redisUtil.hasKey(SsoUtil.USER_TOKEN + phone)){
            tokenArray = JSONArray.parseArray((String)redisUtil.get(SsoUtil.USER_TOKEN + phone));
            for(int i = 0, len = tokenArray.size(); i < len; i++){
                JSONObject json = tokenArray.getJSONObject(i);
                ssoLoginHelper.logout(json.getString("token"));
            }
            redisUtil.del(SsoUtil.USER_TOKEN + phone);
            redisUtil.del(SsoUtil.PREFIX_CACHE_CAMERA + phone);
        }
    }
}
