package com.yd.rmi.ali.sms.service.impl;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.yd.dal.entity.sms.ShortMessageSendRecord;
import com.yd.dal.service.sms.ShortMessageSendRecordService;
import com.yd.rmi.ali.sms.service.AliSmsInterfService;
import com.yd.rmi.cache.SystemConfigService;
import com.yd.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service("aliSmsInterfService")
public class AliSmsInterfServiceImpl implements AliSmsInterfService {
	@Autowired
	private SystemConfigService systemConfigService;
	@Autowired
	private ShortMessageSendRecordService shortMessageSendRecordService;

    /**
     * 
     * @param phoneNumber
     * @param signName
     * @param templateCode
     * @param templateParam
     * @param outId
     * @return SendSmsResponse
     * @throws ClientException
     */
    private SendSmsResponse send(String source,String phoneNumber,String signName,String templateCode,String templateParam,String outId) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
		IClientProfile profile;
        if ("sfp".equals(source)) {
			profile = DefaultProfile.getProfile("cn-hangzhou", systemConfigService.getSingleConfigValue("ALI_SMS_ACCESS_KEY_ID_CFFP"), systemConfigService.getSingleConfigValue("ALI_SMS_ACCESS_KEY_SECRET_CFFP"));
			signName = (CommonUtil.isNullOrBlank(signName)) ? systemConfigService.getSingleConfigValue("ALI_SMS_SIGN_NAME_SFP") : signName;
		}else{
			profile = DefaultProfile.getProfile("cn-hangzhou", systemConfigService.getSingleConfigValue("ALI_SMS_ACCESS_KEY_ID"), systemConfigService.getSingleConfigValue("ALI_SMS_ACCESS_KEY_SECRET"));
			signName = (CommonUtil.isNullOrBlank(signName)) ? systemConfigService.getSingleConfigValue("ALI_SMS_SIGN_NAME") : signName;
		}
        
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", systemConfigService.getSingleConfigValue("ALI_SMS_PRODUCT"), systemConfigService.getSingleConfigValue("ALI_SMS_DOMAIN"));
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phoneNumber);//必填:待发送手机号	"13917505984"
        request.setSignName(signName);//必填:短信签名-可在短信控制台中找到	"安吉保"
        request.setTemplateCode(templateCode); //必填:短信模板-可在短信控制台中找到	"SMS_76610855"
        request.setTemplateParam(templateParam);//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为	"{\"code\":\"231145\"}"
        request.setOutId(outId);//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者	"zxh_out_id"

        SendSmsResponse sendSmsResponse = new SendSmsResponse();
        try{
        	sendSmsResponse = acsClient.getAcsResponse(request);//hint 此处可能会抛出异常，注意catch
        }catch(Exception e){
        	e.printStackTrace();
        	sendSmsResponse.setCode("Exception");
        	sendSmsResponse.setMessage(e.getMessage());
        }
        return sendSmsResponse;
    }

    /**
     * @param phoneNumber
     * @param bizId
     * @param sendDate	必填-发送日期 支持30天内记录查询，格式yyyyMMdd
     * @return
     * @throws ClientException
     */
    private QuerySendDetailsResponse querySendDetails(String phoneNumber,String bizId,String sendDate) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", systemConfigService.getSingleConfigValue("ALI_SMS_ACCESS_KEY_ID"), systemConfigService.getSingleConfigValue("ALI_SMS_ACCESS_KEY_SECRET"));
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", systemConfigService.getSingleConfigValue("ALI_SMS_PRODUCT"), systemConfigService.getSingleConfigValue("ALI_SMS_DOMAIN"));
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        request.setPhoneNumber(phoneNumber);//必填-号码	"13917505984"
        request.setBizId(bizId);//可选-流水号
//        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");//必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        request.setSendDate(sendDate);//ft.format(new Date())
        request.setPageSize(10L);//必填-页大小
        request.setCurrentPage(1L);//必填-当前页码从1开始计数

        QuerySendDetailsResponse querySendDetailsResponse = new QuerySendDetailsResponse();
        try{
        	querySendDetailsResponse = acsClient.getAcsResponse(request);//hint 此处可能会抛出异常，注意catch
        }catch(Exception e){
        	e.printStackTrace();
        	querySendDetailsResponse.setCode("Exception");
        	querySendDetailsResponse.setMessage(e.getMessage());
        }
        return querySendDetailsResponse;
    }
	
    /**
     * 
     * @param smsRecord
     * @return QuerySendDetailsResponse
     */
    @Override
	public SendSmsResponse sendSms(String source,ShortMessageSendRecord smsRecord, String signName) {
    	String phoneNumber = smsRecord.getMobileNo();
    	String templateParam;
    	String outId = "ajb";
    	String templateCode;
    	SendSmsResponse sendSmsResponse = null;
    	if("1".equals(smsRecord.getSmsType())){//验证码短信
    		templateCode = systemConfigService.getSingleConfigValue("ALI_SMS_VERIFICATION_CODE_TEMPLATECODE");
    		templateParam = "{\"code\":\""+smsRecord.getVerificationCode()+"\"}";
    	}else if("2".equals(smsRecord.getSmsType())){//支付提醒短信
    		templateCode = systemConfigService.getSingleConfigValue("ALI_SMS_PAY_NOTIFY_TEMPLATECODE");
    		templateParam = smsRecord.getSmsContent();
    	}else if("3".equals(smsRecord.getSmsType())){//承保成功短信
    		templateCode = systemConfigService.getSingleConfigValue("ALI_SMS_POLICY_SUCCESS_NOTIFY_TEMPLATECODE");
    		templateParam = smsRecord.getSmsContent();
    	}else if("4".equals(smsRecord.getSmsType())){//生日祝福短信
    		templateCode = systemConfigService.getSingleConfigValue("ALI_SMS_BIRTHDAY_TEMPLATECODE");
    		templateParam = smsRecord.getSmsContent();
    	}else if("5".equals(smsRecord.getSmsType())){//提醒续保ALI_SMS_RENEWAL
    		templateCode = systemConfigService.getSingleConfigValue("ALI_SMS_RENEWAL");
    		templateParam = smsRecord.getSmsContent();
    	}else if("0".equals(smsRecord.getSmsType())){//其他临时短信
    		templateCode = smsRecord.getTemplateCode();
    		templateParam = smsRecord.getSmsContent();
    	}else{
    		templateCode = smsRecord.getTemplateCode();
    		templateParam = smsRecord.getSmsContent();
    	}
    	try {
    		sendSmsResponse = send(source, phoneNumber, signName, templateCode, templateParam, outId);
    		smsRecord.setSendTime(new Date());
    		smsRecord.setSendStatus(sendSmsResponse.getCode());
    		smsRecord.setReturnMessage(sendSmsResponse.getMessage());
    		smsRecord.setRequestId(sendSmsResponse.getRequestId());
    		smsRecord.setBizId(sendSmsResponse.getBizId());
    		smsRecord.setSmsContent(templateParam);
    		smsRecord.setTemplateCode(templateCode);
    		shortMessageSendRecordService.save(smsRecord);
		} catch (ClientException e) {
			e.printStackTrace();
		}
    	return sendSmsResponse;
	}
    
    public QuerySendDetailsResponse querySmsDetail(ShortMessageSendRecord smsRecord){
    	QuerySendDetailsResponse response = null;
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//必填-发送日期 支持30天内记录查询，格式yyyyMMdd
    	String sendDate = sdf.format(smsRecord.getSendTime());
    	try {
			response = querySendDetails(smsRecord.getMobileNo(),null, sendDate);
			
			System.out.println("短信明细查询接口返回数据----------------");
            System.out.println("Code=" + response.getCode());
            System.out.println("Message=" + response.getMessage());
            int i = 0;
            for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : response.getSmsSendDetailDTOs())
            {
                System.out.println("SmsSendDetailDTO["+i+"]:");
                System.out.println("Content=" + smsSendDetailDTO.getContent());
                System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
            }
            System.out.println("TotalCount=" + response.getTotalCount());
            System.out.println("RequestId=" + response.getRequestId());
		} catch (ClientException e) {
			e.printStackTrace();
		}
    	return response;
    }
    
    public static void main(String[] args) {

    }
}
