package cn.reghao.autodop.dmaster.notification.service.notifier.sms;

import cn.reghao.autodop.common.http.WebRequest;
import cn.reghao.autodop.common.http.WebResponse;
import cn.reghao.autodop.dmaster.notification.model.po.SmsAccount;
import cn.reghao.autodop.dmaster.notification.service.notifier.Notify;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

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

/**
 * 短信通知
 *
 * @author reghao
 * @date 2020-05-07 01:30:43
 */
@Slf4j
public class SmsNotify implements Notify<SmsMsg> {
    private WebRequest webRequest;
    private Map<String, String> params = new HashMap<>();

    public SmsNotify(WebRequest webRequest, SmsAccount smsAccount) {
        this.webRequest = webRequest;
        params.put("sname", smsAccount.getUsername());
        params.put("spwd", smsAccount.getPassword());
        params.put("scorpid", smsAccount.getScorpid());
        params.put("sprdid", smsAccount.getSprdid());
    }

    /**
     * TODO 保证线程安全
     *
     * @param
     * @return
     * @date 2021-06-23 上午11:50
     */
    @Override
    public synchronized void send(String receiver, SmsMsg msg) throws Exception {
        params.put("sdst", receiver);
        params.put("smsg", msg.getContent());
        String url = params.remove("url");

        WebResponse webResponse = webRequest.postFormData(url, params);
        if (webResponse.getStatusCode() != 200) {
            throw new Exception("消息发送失败, " + webResponse.getBody());
        }
        checkResponse(webResponse.getBody());
    }

    private void checkResponse(String body) throws Exception {
        Element root = DocumentHelper.parseText(body).getRootElement();
        List<Element> elements = root.elements();
        Map<String, Object> map = new HashMap<>(elements.size());
        for (Element element : elements) {
            map.putIfAbsent(element.getName(), element.getData());
        }

        Integer state = (Integer) map.get("State");
        if (state != 0) {
            throw new Exception((String) map.get("State"));
        }
    }
}
