package ink.wgink.module.sms.factory.sms.impl;

import ink.wgink.exceptions.base.SystemException;
import ink.wgink.module.sms.factory.sms.ISmsSend;
import ink.wgink.properties.sms.SmsDefaultProperties;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: DefaultSendSmsImpl
 * @Description: 默认发请求
 * @Author: wanggeng
 * @Date: 2021/5/1 3:52 下午
 * @Version: 1.0
 */
public class DefaultSmsSendImpl implements ISmsSend {

    private static final Logger LOG = LoggerFactory.getLogger(DefaultSmsSendImpl.class);
    private static final String URL_SMS = "?action=send&userid=&account={account}&password={password}&mobile={mobile}&content={content}&sendTime=&extno={extno}";
    private SmsDefaultProperties smsDefaultProperties;

    public DefaultSmsSendImpl(SmsDefaultProperties smsDefaultProperties) {
        this.smsDefaultProperties = smsDefaultProperties;
    }

    @Override
    public void code(String phone, String code) {
        String content = smsDefaultProperties.getTemplate().getVerificationCode().replace("{sign}", smsDefaultProperties.getSign()).replace("{content}", code);
        send(phone, content);
    }

    @Override
    public void content(String phone, String content) {
        StringBuilder contentSB = new StringBuilder(smsDefaultProperties.getSign()).append(content);
        send(phone, contentSB.toString());
    }

    /**
     * 发送
     *
     * @param phone
     * @param content
     */
    private void send(String phone, String content) {
        String[] paramArray = new String[]{
                smsDefaultProperties.getAccount(),
                smsDefaultProperties.getPassword(),
                phone,
                content,
                phone
        };
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(smsDefaultProperties.getUrl() + URL_SMS, String.class, paramArray);
        JSONObject jsonObject = XML.toJSONObject(result);
        if (StringUtils.equals("Success", jsonObject.getJSONObject("returnsms").getString("returnstatus"))) {
            LOG.info("短信发送成功");
        } else {
            LOG.error("短信发送失败，原因：{}。", jsonObject);
            throw new SystemException(jsonObject.toString());
        }
    }

}
