package com.ruoyi.xq.kit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.common.collect.Lists;
import com.ruoyi.xq.config.AliSmsProperties;
import com.ruoyi.xq.enums.common.CodeEnum;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class AliSmsKit {
	@Autowired
	@Setter
    private AliSmsProperties config;
    private IClientProfile profile;

    @PostConstruct
    public void init() {
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		profile = DefaultProfile.getProfile("cn-hangzhou", config.getAccessKeyId(), config.getAccessKeySecret());
    }

	private boolean batchSendMessage(List<String> phone,String messageTemplate){
		Asserts.notBlank(messageTemplate, "短信模板不能为空");
		IAcsClient client = new DefaultAcsClient(profile);
		CommonRequest request = new CommonRequest();
		request.setSysMethod(MethodType.POST);
		request.setSysDomain("dysmsapi.aliyuncs.com");
		request.setSysVersion("2017-05-25");
		request.setSysAction("SendBatchSms");
		List<String> signName = phone.stream().map(i -> config.getSignName()).collect(Collectors.toList());
		request.putQueryParameter("TemplateCode", messageTemplate);
		request.putQueryParameter("SignNameJson", JSON.toJSONString(signName));
		request.putQueryParameter("PhoneNumberJson", JSON.toJSONString(phone));
		try {
			CommonResponse response = client.getCommonResponse(request);
			String data = response.getData();
			JSONObject jsonObject = JSONObject.parseObject(data);
			if(jsonObject.get("Code") == null || !"OK".equals(jsonObject.get("Code"))){
				log.error("短信发送失败 response={}", jsonObject.toJSONString());
				return false;
			}
		} catch (ClientException e) {
			log.error(e.getMessage(),e);
			throw new RuntimeException("短信发送失败!");
		}
		return true;
	}

    private boolean sendMessage(String phone, String messageTemplate, String messageCode) {
        Asserts.notBlank(messageTemplate, "短信模板不能为空");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("SignName", config.getSignName());
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("TemplateCode", messageTemplate);
        if (StringUtils.isNoneBlank(messageCode)) {
            request.putQueryParameter("TemplateParam", "{\"code\":\"" + messageCode + "\"}");
        }
        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);
            String data = response.getData();
            JSONObject jsonObject = JSONObject.parseObject(data);
            if(jsonObject.get("Code") == null || !"OK".equals(jsonObject.get("Code"))){
            	log.error("短信发送失败 response={}", jsonObject.toJSONString());
                return false;
            }
        } catch (ClientException e) {
			log.error(e.getMessage(),e);
            throw new RuntimeException("短信发送失败!");
        }
        return true;
    }


    public boolean sendMessage(String phone, String messageTemplate, String messageCode, boolean isAsy) {
        if (isAsy) {
            new Thread(() -> {
                sendMessage(phone, messageTemplate, messageCode);
            }).start();
            return true;
        } else {
            return sendMessage(phone, messageTemplate, messageCode);
        }
    }

    public boolean batchSendMessagePublic(List<String> phone,String messageTemplate){
		if(CollectionUtils.isEmpty(phone)){
			return false;
		}
		List<List<String>> list = Lists.partition(phone, 100);
		for (List<String> phoneList : list) {
			this.batchSendMessage(phoneList,messageTemplate);
		}
		return true;
	}

    /**
     * 异步发送消息
     * @param phone
     * @param messageTemplate
     * @return
     */
    public boolean sendMessageAsync(String phone, String messageTemplate) {
        return sendMessage(phone,messageTemplate,null,true);
    }

	public static void main(String[] args) {
		AliSmsKit messageSenderUtil = new AliSmsKit();
		AliSmsProperties config = new AliSmsProperties();
		messageSenderUtil.setConfig(config);
		messageSenderUtil.init();
		messageSenderUtil.sendMessage("15302786929", CodeEnum.LOGIN.getAliTemplate(), "123332");

	}

}
