package com.njcn.cloud.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.cloud.mapper.AppUserMapper;
import com.njcn.cloud.enums.app.UserCodeEnum;
import com.njcn.cloud.pojo.dto.AppSendMsg;
import com.njcn.cloud.service.IAppSendMsgService;
import com.njcn.cloud.service.IAppUserService;
import com.njcn.cloud.utils.SmsUtil;
import com.njcn.common.pojo.constant.PatternRegex;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.PubUtils;
import com.njcn.redis.pojo.enums.RedisKeyEnum;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.user.enums.MessageEnum;
import com.njcn.user.enums.UserResponseEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.njcn.cloud.pojo.dto.AppUser;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Random;

/**
 * @author hongawen
 * @date: 2019/10/17 11:37
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {

    private final SmsUtil smsUtil;
    private final RedisUtil redisUtil;
    private final IAppSendMsgService appSendMsgService;


    /**
     * 发送短信
     *
     * @param phone   手机号
     * @param devCode 设备ID
     * @param type    短信类型
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setMessage(String phone, String devCode, String type) {
        if (!PubUtils.match(PatternRegex.PHONE_REGEX, phone)) {
            throw new BusinessException(UserResponseEnum.REGISTER_PHONE_WRONG);
        }
        String msgTemplate = SmsUtil.getMessageTemplate(type);
        String vCode = null;
        SendSmsResponse sendSmsResponse = null;

            //type为4，账号替换为新手机号
            if (!msgTemplate.equalsIgnoreCase(MessageEnum.REGISTER.getTemplateCode())) {
                AppUser appUser = this.getOne(new LambdaQueryWrapper<AppUser>()
                        .eq(AppUser::getPhone, phone)
                        .ne(AppUser::getState, 0)
                );
                if ("4".equalsIgnoreCase(type)) {
                    //注册，无需判断手机号与设备的匹配
                    if (appUser != null) {
                        throw new BusinessException(UserCodeEnum.REGIST_PHONE_FAIL.getMsg());
                    }
                } else {
                    if (null == appUser) {
                        throw new BusinessException(UserCodeEnum.NO_USER.getMsg());
                    } else {
                        appUser.setDevCode(devCode);
                        this.updateById(appUser);
                    }
                }
            }
        try {
            //开始执行短信发送
            vCode = getMessageCode();
            sendSmsResponse=new SendSmsResponse();
            sendSmsResponse.setCode("OK");
//            sendSmsResponse = smsUtil.sendSms(phone, msgTemplate, "code", vCode);
            String key = RedisKeyEnum.SMS_LOGIN_KEY.getKey() + phone;
            if (sendSmsResponse.getCode() != null && "OK".equals(sendSmsResponse.getCode())) {
                //成功发送短信验证码后，保存进redis，验证码失效为5分钟
                redisUtil.saveByKeyWithExpire(key, vCode, 300L);
            } else {
                throw new BusinessException(UserResponseEnum.SEND_CODE_FAIL);
            }
            //短信入库
            addSendMessage(phone, vCode, sendSmsResponse);
        } catch (Exception e) {
            log.error("发送短信异常，异常为：" + e.getMessage());
            //短信入库
            addSendMessage(phone, vCode, sendSmsResponse);
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 自定义获取验证码，固定为字母和数字的组合
     */
    private String getMessageCode() {
        String result = "";
        char[] numbers = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        //填充数字
        for (int i = 0; i < 6; i++) {
            int numberIndex = new Random().nextInt(10);
            result = result + numbers[numberIndex];
        }
        return result;
    }

    /**
     * 验证码入库
     */
    public void addSendMessage(String phone, String vCode, SendSmsResponse sendSmsResponse) {
        AppSendMsg appSendMsg = new AppSendMsg();
        appSendMsg.setPhone(phone);
        appSendMsg.setMessage(vCode);
        appSendMsg.setSendTime(LocalDateTime.now());
        appSendMsg.setSendStatus(sendSmsResponse.getCode() == null ? "无状态" : sendSmsResponse.getCode());
        appSendMsgService.save(appSendMsg);
    }
}


