package com.bizzan.bitrade.vendor.provider.support;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
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 com.bizzan.bitrade.util.HttpClientUtil;
import com.bizzan.bitrade.util.HttpSend;
import com.bizzan.bitrade.util.MessageResult;
import com.bizzan.bitrade.vendor.provider.SMSProvider;
import com.sparkframework.security.Encrypt;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MstxSMSProvider implements SMSProvider {
	private String username = "210168"; // appID
    private String password = "fw6vfk"; // signature
    private String sign; // sign
    private String gateway = "http://120.24.193.108:9001/smsSend.do"; // gateway
    
    private String appId = "LTAI5tAKb4s4HQ7zmwGM7kGX";
    private String appsecret = "4W1NGjQAA8cll392h49QBVsXtNhVI5";
    private String templateId = "104935";
    
    private String projectName;
    private String smsbaoUsername;
    private String smsbaoPassword;

    public MstxSMSProvider(String username, String password, String gateway, String appId, String appsecret, String projectName, String smsbaoUsername, String smsbaoPassword) {
    	this.username = username;
    	this.password = password;
    	this.gateway = gateway;
    	this.appId = appId;
    	this.appsecret = appsecret;
    	this.projectName = projectName;
    	this.smsbaoUsername = smsbaoUsername;
    	this.smsbaoPassword = smsbaoPassword;
    }

	@Override
	public MessageResult sendSingleMessage(String mobile, String content) throws Exception {
		// TODO Auto-generated method stub
		/*Map<String, String> params = new HashMap<String, String>();
        params.put("username", username);
        params.put("mobile", mobile);
        log.info("手机号", mobile);
        String smsContent;
        if(content.length() == 6) {
        	smsContent = "【FOX】您的验证码为" + content + "，十分钟内有效，如非本人操作，请忽略。";
        } else {
        	smsContent = content;
        }
        params.put("content", URLEncoder.encode(smsContent, "UTF-8"));
        String newPassword = Encrypt.MD5(username + Encrypt.MD5(
        		password));
        params.put("password", newPassword);
        log.info("云邮短信==!!==", params.toString());

        String returnStr= HttpSend.post(gateway, params);
        log.info("result = {}", returnStr);
        return parseResult(returnStr);*/
		String smsContent;
        if(content.length() == 6) {
        	//smsContent = "【"+this.projectName+"】您的验证码为：" + content + "，十分钟内有效，如非本人操作，请忽略。";
        	smsContent = "您的验证码为：" + content + "，十分钟内有效，如非本人操作，请忽略。";
        } else {
        	smsContent = content;
        }
		String url = "https://api.smsbao.com/sms?u="+smsbaoUsername+"&p="+smsbaoPassword+"&m="+mobile+"&c="+URLEncoder.encode(smsContent, "UTF-8");
		String result = HttpClientUtil.get(url, null, null);
		return parseResult(result);
	}
	
	private MessageResult parseResult(String result) {
        //JSONObject jsonObject = JSONObject.parseObject(result);

        MessageResult mr = new MessageResult(500, "系统错误");
        if(result.length()>5 || Integer.parseInt(result)==0) {
            mr.setCode(0);
            mr.setMessage("短信发送成功！");
        }else{
            mr.setCode(1);
            mr.setMessage("短信发送失败，请联系平台处理！");
        }
        return mr;
    }

	@Override
	public MessageResult sendMessageByTempId(String mobile, String content, String templateId) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public MessageResult sendCustomMessage(String mobile, String content) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public MessageResult sendInternationalMessage(String randomCode, String areaCode, String phone) throws Exception {
		// TODO Auto-generated method stub
		/*DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", appId,appsecret);
		IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        //域名，请勿修改
        request.setSysDomain("dysmsapi.aliyuncs.com");
        //API版本号，请勿修改
        request.setSysVersion("2017-05-25");
        //API名称
        request.setSysAction("SendMessageToGlobe");
        //接收号码，格式为：国际码+号码，必填
        request.putQueryParameter("To", content+phone);
        //发送方senderId，选填
        //request.putQueryParameter("From", "1234****90");
        //短信内容，必填
        request.putQueryParameter("Type", "OTP");
        String smsContent = "【】您的验证码为" + randomCode + "，十分钟内有效，如非本人操作，请忽略。";
        request.putQueryParameter("Message", smsContent);
        
        
        try {
            CommonResponse response = client.getCommonResponse(request);
            return getResult(response.getData());
        } catch (ServerException e) {
            log.error(e.getErrMsg());
        } catch (ClientException e) {
            log.error(e.getErrMsg());
        }
        return MessageResult.error("短信发送失败，请联系平台处理！");*/
		String smsContent;
        if(randomCode.length() == 6) {
        	//smsContent = "【"+this.projectName+"】Your verification code is:" + randomCode + ", it will be available in 10 minutes, please ignore if you didn't operate";
        	smsContent = "Your verification code is:" + randomCode + ", it will be available in 10 minutes, please ignore if you didn't operate";
        } else {
        	smsContent = randomCode;
        }
        String mobile = URLEncoder.encode("+"+areaCode+phone, "UTF-8");
		String url = "https://api.smsbao.com/wsms?u="+smsbaoUsername+"&p="+smsbaoPassword+"&m="+mobile+"&c="+URLEncoder.encode(smsContent, "UTF-8");
		String result = HttpClientUtil.get(url, null, null);
		return parseResult(result);
	}
	
	public MessageResult getResult(String result) {
		MessageResult messageResult = MessageResult.success();
		JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getString("Code").equals("OK")) {
        	messageResult.setCode(0);
        	messageResult.setMessage("短信发送成功！");
        } else {
        	messageResult.setCode(1);
            messageResult.setMessage("短信发送失败，请联系平台处理！");
        }
        return messageResult;
	}

}
