package com.njyunzhi.pet_identity.common;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SMSUtils implements InitializingBean {
    @Autowired
    HttpUtils httpUtils;

    @Value("${yz.sms.api}")
    String smsAPI;

    @Value("${yz.sms.appid}")
    String appid;

    public void sendMessage(Message message) throws Exception {
        long nowMills = System.currentTimeMillis();
        String timestamp = String.valueOf(nowMills);
        String secret = appid + timestamp;

        Map<String, String> header = new HashMap<>();
        header.put("x-appid", appid);
        header.put("x-timestamp", timestamp);
        header.put("x-sign", EncryptUtils.md5(appid + secret, timestamp));

        Map<String, String> body = new HashMap<>();
        body.put("PhoneNumbers", message.getTel());
        body.put("SignName", message.getSign());
        body.put("TemplateCode", message.getCode());
        body.put("TemplateParam", message.getContent());

        httpUtils.post(smsAPI, header, JSONObject.toJSONString(body, false));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    }

    @Data
    @Accessors(chain = true)
    public static class Message {
        String code;
        String tel;
        String sign;
        String content;
    }
}
