
package cn.axzo.msg.center.notices.manager;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.volcengine.model.request.SmsSendRequest;
import com.volcengine.model.response.SmsSendResponse;
import com.volcengine.service.sms.SmsService;
import com.volcengine.service.sms.SmsServiceInfoConfig;
import com.volcengine.service.sms.impl.SmsServiceImpl;

import cn.axzo.msg.center.common.exception.ServiceException;
import cn.axzo.msg.center.notices.manager.api.SmsSendManager;
import cn.axzo.msg.center.notices.manager.api.dto.request.MessageSendRequestDto;
import cn.axzo.msg.center.notices.manager.api.dto.response.SendSmsCommonResponseDto;
import cn.axzo.msg.center.notices.manager.support.VolcSmsProps;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * https://www.volcengine.com/docs/6361/173288
 * https://www.volcengine.com/docs/6361/173291
 *
 * @author yanglin
 */
@Slf4j
@RequiredArgsConstructor
@Service("volcManager")
public class VolcManager implements SmsSendManager, InitializingBean {

	private final VolcSmsProps props;
	private SmsService smsService;

	@Override
	public SendSmsCommonResponseDto sendMessage(MessageSendRequestDto requestDto) {
		SmsSendRequest volcRequest = new SmsSendRequest();
		volcRequest.setPhoneNumbers(requestDto.getPhoneNo());
		volcRequest.setSmsAccount(props.getGroupId());
		volcRequest.setTemplateId(requestDto.getTemplateNo());
		volcRequest.setSign(props.getSign());

		Map<String, String> effectiveParam = new HashMap<>();
		if (requestDto.getTemplateMap() != null) {
			for (Map.Entry<String, Object> e : requestDto.getTemplateMap().entrySet()) {
				if (e.getKey() == null || e.getValue() == null)
					continue;
				effectiveParam.put(e.getKey(), String.valueOf(e.getValue()));
			}
		}
		volcRequest.setTemplateParamByMap(effectiveParam);

		try {
			log.info("[VolcManager#sendMessage] 开始发送sms, request={}", volcRequest);
			SmsSendResponse volcResponse = smsService.sendV2(volcRequest);
			log.info("[VolcManager#sendMessage] 结束发送sms, request={}, response={}", volcRequest, volcResponse);
			if (StringUtils.isBlank(volcResponse.getCode())) {
				SendSmsCommonResponseDto result = new SendSmsCommonResponseDto();
				result.setBizId(volcResponse.getResult().getMessageId().get(0));
				result.setRequestId(volcResponse.getResponseMetadata().getRequestId());
				result.setMessage(result.getMessage());
				return result;
			}
			throw new ServiceException(
				"发送短信失败, request=" + JSON.toJSONString(volcRequest) + ", response=" + JSON.toJSONString(volcResponse));
		}
		catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	@Override
	public void afterPropertiesSet() {
		smsService = SmsServiceImpl.getInstance(
			new SmsServiceInfoConfig(props.getAccessKey(), props.getSecretAccessKey()));
	}

}
