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

import com.fdkankan.sms.SendMailAcceUtils;
import com.fdkankan.sms.SmsService;
import com.fdkankan.common.util.PatternUtils;
import com.fdkankan.common.util.SsoUtil;
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;

@Service
public class MsgService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IUserService userService;
    @Autowired
    private SmsService smsService;

    @Value("${admin.register.validCode}")
    private  String registerValidCode;
    @Value("${phone.code.cn}")
    private String cnCode;
    @Value("${phone.code.en}")
    private String enCode;
    @Value("${environment}")
    private String environment;


    public String getMsgAuthCode(RequestUser param) throws Exception{
        if(StringUtils.isBlank(param.getPhoneNum()) || StringUtils.isBlank(param.getAreaNum())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        String key = SsoUtil.PREFIX_MSG_NOT_CODE + param.getPhoneNum();
        Long time = redisUtil.getExpire(key);
        if(time!=null && time >0){
            throw  new BusinessException(ErrorCode.V_CODE_TIME_NOT_OUT.code(),String.valueOf(time));
        }
        String code = String.valueOf((int)((Math.random()*9+1)*100000));
        if ("86".equals(param.getAreaNum())){
            if (!PatternUtils.isPhoneNumber(param.getPhoneNum())){
                throw new BusinessException(ErrorCode.PHONE_VIOLATION);
            }
            String sendCode = smsService.sendSms(param.getPhoneNum(), "{\"code\":\"" + code + "\"}", cnCode);
            if("isv.BUSINESS_LIMIT_CONTROL".equals(sendCode)){
                throw new BusinessException(ErrorCode.PHONE_CODE_TO_MANY);
            }
        }else{
            try{
                smsService.sendSMSMessage(param.getAreaNum()+param.getPhoneNum(), code);
            }catch (Exception e){
                e.printStackTrace();
                throw new BusinessException(ErrorCode.PHONE_VIOLATION);
            }
        }
        //短信验证码，5分钟有效
        redisUtil.set(SsoUtil.PREFIX_MSG_AUTH_CODE + param.getPhoneNum(), code, 300);
        //短信60秒内不能重发
        redisUtil.set(SsoUtil.PREFIX_MSG_NOT_CODE + param.getPhoneNum(), code, 60);
        return ServerCode.SUCCESS.message();
    }

    public String getEmailAuthCode(RequestUser param)throws Exception {
        if(StringUtils.isEmpty(param.getEmail())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        String code = String.valueOf((int)((Math.random()*9+1)*100000));
        switch (param.getCountry()){
            case "1" :
                SendMailAcceUtils.sendMail(param.getEmail(), SendMailAcceUtils.EN_CODE_SUBJECT, SendMailAcceUtils.EN_CODE_MSG.replace("${code}", code), null);
                break;
            case "2" :
                SendMailAcceUtils.sendMailUsa(param.getEmail(), SendMailAcceUtils.EN_CODE_SUBJECT_USA, SendMailAcceUtils.EN_CODE_MSG_USA.replace("${code}", code), null);
                break;
            default:
                SendMailAcceUtils.sendMail(param.getEmail(), SendMailAcceUtils.CN_CODE_SUBJECT, SendMailAcceUtils.CN_CODE_MSG.replace("${code}", code), null);
                break;
        }
        redisUtil.set(SsoUtil.PREFIX_MSG_AUTH_CODE + param.getPhoneNum(), code, 300);
        return ServerCode.SUCCESS.message();
    }

    public User checkMsgAuth(RequestUser user){
        if(StringUtils.isEmpty(user.getPhoneNum()) || org.apache.commons.lang.StringUtils.isEmpty(user.getMsgAuthCode())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        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);
        }
        return  userService.getUserByUserName(user.getPhoneNum());
    }
}
