package com.lightinit.hsdataportal.common;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.log4j.LogManager;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class PhoneSendUtils {

    public static org.apache.log4j.Logger log = LogManager.getLogger(PhoneSendUtils.class);

    public static Map<String,Object> send(String phone){
        Map<String,Object> map = null ;
        String regionId = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.REGIONID);
        String accesskeyId = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.ACCESSKEYID);
        String secret = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.SECRET);
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accesskeyId, secret);

        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "衡水智慧城市建设有限公司");
        request.putQueryParameter("TemplateCode", "SMS_158948957");
        int newNum = (int)((Math.random()*9+1)*100000);
        String code = String.valueOf(newNum);
        String newCode = "{\"code\":\""+code+"\"}" ;
        request.putQueryParameter("TemplateParam", newCode);
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            map = HttpUtil.strToMap(data) ;
            map.put("returnCode",code) ;
        } catch (ServerException e) {
//            throw new RuntimeException("获取短信验证码异常",e.getCause()) ;
            e.printStackTrace();
            log.error("获取短信验证码异常:"+e.getErrCode()+e.getMessage());
        } catch (ClientException e) {
            e.printStackTrace();
//            throw new RuntimeException("获取短信验证码异常",e.getCause()) ;
            log.error("获取短信验证码异常:"+e.getErrCode()+e.getMessage());

        }
        return map ;
    }

}
