package com.liangjian.dataplatform.member.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.liangjian.dataplatform.member.safe.Tuple3;
import com.liangjian.dataplatform.member.service.IPhoneSMSService;
import com.liangjian.dataplatform.member.util.http.SimpleHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Map;

/**
 * @Author: 黄子奇
 * @Date: 2019/11/15
 */
@Service
public class PhoneSMService implements IPhoneSMSService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void sendSms(String phone, String code) throws Exception {
        String url = String.format("http://sms.360lj.com/MessageHandle.ashx?mobile=%s&content=%s", phone, code);
        Tuple3<Boolean, String, Exception> result = SimpleHttpClient.httpGet(url);
        if(result.get_1()) {
            //首先是请求成功
            String json = result.get_2();
            ObjectReader objectReader = new ObjectMapper().readerFor(new TypeReference<Map<String,String>>() {});
            Map<String,String> resultBody = objectReader.readValue(json);
            if(!resultBody.get("IsSuccess").equals("true")) {
                throw new Exception("发送失败");
            }
        } else {
            //请求不成功
            throw new Exception("请求失败");
        }
        redisTemplate.opsForValue().set(phone, code, Duration.ofSeconds(60));
    }

    @Override
    public boolean verifyPhoneCode(String phone, String code) {
        String codeFromRedis = redisTemplate.opsForValue().get(phone);
        return codeFromRedis != null && codeFromRedis.equals(code);
    }
}
