package com.izouma.wenlvju.service.sms;

import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.izouma.wenlvju.domain.SmsRecord;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.SmsRecordRepo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
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.io.StringWriter;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class NjwlSmsService {
    @Value("${njwl.app_id}")
    private String        appId;
    @Value("${njwl.app_key}")
    private String        appKey;
    @Value("${njwl.url}")
    private String        url;
    @Autowired
    private SmsRecordRepo smsRecordRepo;

    public String sendVerify(String phone) {
        smsRecordRepo.findLastByPhoneAndExpiresAtAfterAndExpiredFalse(phone, LocalDateTime.now()).ifPresent(record -> {
            if (record.getCreatedAt().plusMinutes(1L).isAfter(LocalDateTime.now())) {
                long sec = record.getCreatedAt()
                        .plusMinutes(1L)
                        .toInstant(ZoneOffset.UTC)
                        .getEpochSecond() - LocalDateTime.now().toInstant(ZoneOffset.UTC).getEpochSecond() + 1;
                throw new BusinessException("请" + sec + "秒后再试");
            }
        });

        String code = RandomStringUtils.randomNumeric(4);

        String message = "您的验证码为：%s，有效时间为10分钟，请勿泄露给他人！";
        this.sendSms(phone, String.format(message, code));

        smsRecordRepo.expire(phone);
        String sessionId = RandomStringUtils.randomAlphabetic(10);
        smsRecordRepo.save(SmsRecord.builder()
                .sessionId(sessionId)
                .phone(phone)
                .code(code)
                .expiresAt(LocalDateTime.now().plusMinutes(10))
                .expired(false)
                .build());
        return sessionId;
    }

    public Map<String, String> getToken() {
        long expiryDate = System.currentTimeMillis() + 1000 * 60 * 10;//10分钟有效时间
        String tokenKey = appId + appKey + expiryDate;
        System.out.println();
        String token = DigestUtils.md5Hex(tokenKey).toLowerCase();
//        log.info("短信时间戳---->" + expiryDate + "，短信token---->" + token);
        Map<String, String> map = new HashMap<>();
        map.put("expiryDate", String.valueOf(expiryDate));
        map.put("token", token);
        return map;
    }

    public void sendSms(String phone, String message) {
        if (StringUtils.isBlank(phone)) {
            return;
        }
        Map<String, Object> map = new HashMap<>();
        Map<String, String> token = this.getToken();
        map.put("appId", appId);
        map.put("expiryDate", token.get("expiryDate"));
        map.put("tokenKey", token.get("token"));
        map.put("operationType", "ADD");
        Map<String, Object> data = new HashMap<>();
        data.put("phone", phone);
        data.put("message", message);
        map.put("data", data);
        String body = JSONObject.toJSONString(map);
        log.info("短信内容--->"+body);
        StringWriter writer = new StringWriter();
        HttpRequest.post(url)
                .contentType("application/json;charset=UTF-8")
                .send(body)
                .receive(writer);

        String responseBody = writer.toString();
        log.info(responseBody);

    }


}
