package io.renren.modules.app.service.impl;

import org.springframework.stereotype.Service;

import java.util.Date;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import org.apache.commons.lang.StringUtils;

import io.renren.common.utils.ConfigConstant;
import io.renren.common.utils.DateUtils;
import io.renren.modules.app.dao.SmsCodeDao;
import io.renren.modules.app.entity.SmsCodeEntity;
import io.renren.modules.app.service.SmsCodeService;
import io.renren.common.utils.AliyunSmsUtils;

@Service("smsCodeService")
public class SmsCodeServiceImpl extends ServiceImpl<SmsCodeDao, SmsCodeEntity> implements SmsCodeService {

    @Override
    public String getCode(String uuid, String phone) {
        if (StringUtils.isBlank(uuid)) {
            throw new RRException("uuid不能为空");
        }
        // 生成数字验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        SmsCodeEntity smsCodeEntity = new SmsCodeEntity();
        smsCodeEntity.setUuid(uuid);
        smsCodeEntity.setPhone(phone);
        smsCodeEntity.setCode(code);
        smsCodeEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), ConfigConstant.EXPIRE_TIME));

        String result = "";
        try {
            this.save(smsCodeEntity);
            // 发送验证码
            result = AliyunSmsUtils.sendSms(phone, ConfigConstant.SignName, ConfigConstant.TemplateCode,
                    "{\"code\":" + code + "}");
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void validate(String uuid, String code, String phone)  throws RRException{
        SmsCodeEntity smsCodeEntity = this.getOne(new QueryWrapper<SmsCodeEntity>().eq("uuid", uuid));
        if (smsCodeEntity == null) {
            throw new RRException("验证码不正确");
        }

        if (smsCodeEntity.getCode().equalsIgnoreCase(code) && smsCodeEntity.getPhone().equalsIgnoreCase(phone)
                && smsCodeEntity.getExpireTime().getTime() >= System.currentTimeMillis()) {
            // 删除验证码
            this.removeById(uuid);
        } else {
            throw new RRException("验证码不正确");
        }
    }
}