/**
 * 
 */
package org.springblade.message.sms;

import org.springblade.message.model.MsgResponse;
import org.springblade.message.model.SmsInfo;
import org.springblade.message.model.SmsMsgRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.qiniu.http.Response;
import com.qiniu.sms.SmsManager;
import com.qiniu.sms.model.TemplateInfo;
import com.qiniu.sms.model.TemplateInfo.Item;
import com.qiniu.util.Auth;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wookvn
 *
 */
@Slf4j
@Component
public class QiniuSmsTemplate extends SmsMsgTemplate {

	@Override
	public MsgResponse sendMessage(SmsMsgRequest smsMsgRequest) {
		try {
			SmsInfo smsInfo = smsMsgRequest.getSmsInfo();
			Auth auth = Auth.create(smsInfo.getAccessKey(), smsInfo.getSecretKey());
			SmsManager smsManager = new SmsManager(auth);
			Response response = smsManager.sendMessage(smsInfo.getTemplateId(), StringUtils.toStringArray(smsMsgRequest.getPhones()), smsMsgRequest.getParams());
			log.info("七牛云短信发送完成,res=" + response.bodyString());
			return new MsgResponse(response.isOK(), response.statusCode, response.toString());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return MsgResponse.failure(e.getMessage());
		}
	}

	@Override
	public MsgResponse queryTemplateContent(SmsInfo smsInfo) {
		try {
			Auth auth = Auth.create(smsInfo.getAccessKey(), smsInfo.getSecretKey());
			SmsManager smsManager = new SmsManager(auth);
			//审核状态, 取值范围为: passed (通过), rejected (未通过), reviewing (审核中)
			TemplateInfo templateInfo = smsManager.describeTemplateItems("passed", 0, 100);
			if(templateInfo != null && CollectionUtil.isNotEmpty(templateInfo.getItems())) {
				Item templateItem = templateInfo.getItems().stream().filter(item -> item.getId().equals(smsInfo.getTemplateId())).findAny().orElse(null);
				if(templateItem != null) { 
					return MsgResponse.success(200, templateItem.getTemplate());
				}
			}
			return MsgResponse.failure("未查询到该模版");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return MsgResponse.failure(e.getMessage());
		}
	}
}
