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

import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
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.common.utils.SmsUtils;
import io.renren.modules.app.dao.SmsCodeDao;
import io.renren.modules.app.entity.SmsCodeEntity;
import io.renren.modules.app.service.SmsCodeService;

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

    @Override
    public String getCode(String uuid, String phone) throws Exception {
        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);
            // 发送验证码
            StringBuilder sb = new StringBuilder();
            sb.append("accountSid").append("=").append(ConfigConstant.ACCOUNT_SID);
            sb.append("&to").append("=").append(phone);
            sb.append("&param").append("=").append(URLEncoder.encode(code + "," + ConfigConstant.EXPIRE_TIME, "UTF-8"));
            sb.append("&templateid").append("=").append(ConfigConstant.TEMPLATE_ID);
            String body = sb.toString() + SmsUtils.createCommonParam(ConfigConstant.ACCOUNT_SID, ConfigConstant.AUTH_TOKEN);
            result = SmsUtils.post(ConfigConstant.BASE_URL, body);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
            result = "数据库存在相同记录";
        }
        return result;
    }

    @Override
    public boolean validate(String uuid, String code, String phone) {
        SmsCodeEntity smsCodeEntity = this.getOne(new QueryWrapper<SmsCodeEntity>().eq("uuid", uuid));
        if(smsCodeEntity == null){
            return false;
        }

        //删除验证码
        this.removeById(uuid);

        if(smsCodeEntity.getCode().equalsIgnoreCase(code) && smsCodeEntity.getPhone().equalsIgnoreCase(phone) && smsCodeEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
            return true;
        }
        return false;
    }
}