package cn.com.poc.support.sms.channel.baidu;

import cn.com.poc.common.dto.SmsDto;
import cn.com.poc.support.sms.ThirdPlatformSmsService;
import cn.com.yict.framemax.core.config.Config;
import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.sms.SmsClient;
import com.baidubce.services.sms.SmsClientConfiguration;
import com.baidubce.services.sms.model.SendMessageV3Request;
import com.baidubce.services.sms.model.SendMessageV3Response;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;


/**
 * @author Jennie.Chen
 */
@Component
public class BaiDuThirdPlatformService implements ThirdPlatformSmsService {

    @Override
    public boolean doSend(SmsDto smsDto) throws Exception {
        String ACCESS_KEY_ID = Config.get("baidu.code.keyId");
        String SECRET_ACCESS_KEY = Config.get("baidu.code.keySecret");
        String ENDPOINT = "http://smsv3.bj.baidubce.com";

        String code = smsDto.getSmsCode();

        SmsClientConfiguration config = new SmsClientConfiguration();
        config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
        config.setEndpoint(ENDPOINT);
        SmsClient client = new SmsClient(config);

        SendMessageV3Request request = new SendMessageV3Request();
        request.setMobile(smsDto.getMobilePhone());
        //判断手机号码是不是大陆的
        boolean matches = Pattern.matches("(?:0|86|\\+86)?1[3-9]\\d{9}", smsDto.getMobilePhone());
        if(matches){
            request.setSignatureId(Config.get("baidu.code.mainLand.signatureId"));
            request.setTemplate(Config.get("baidu.code.mainLand.template"));
        }else {
            request.setSignatureId(Config.get("baidu.code.gangAo.signatureId"));
            request.setTemplate(Config.get("baidu.code.gangAo.template"));
        }
        Map<String, String> contentVar = new HashMap<>();
        contentVar.put("SMSvCode", code);
        request.setContentVar(contentVar);
        SendMessageV3Response response = client.sendMessage(request);
        // 解析请求响应 response.isSuccess()为true 表示成功
        if (response != null && response.isSuccess()) {
            return true;
        } else {
            return false;
        }
    }
}
