package com.qs.mp.common.jsms;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.ApacheHttpClient;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jsms.api.SendSMSResult;
import cn.jsms.api.ValidSMSResult;
import cn.jsms.api.account.AccountBalanceResult;
import cn.jsms.api.account.AppBalanceResult;
import cn.jsms.api.common.SMSClient;
import cn.jsms.api.common.model.BatchSMSPayload;
import cn.jsms.api.common.model.BatchSMSResult;
import cn.jsms.api.common.model.RecipientPayload;
import cn.jsms.api.common.model.SMSPayload;
import cn.jsms.api.schedule.model.ScheduleResult;
import cn.jsms.api.schedule.model.ScheduleSMSPayload;
import cn.jsms.api.template.SendTempSMSResult;
import cn.jsms.api.template.TempSMSResult;
import cn.jsms.api.template.TemplatePayload;
import com.alibaba.fastjson.JSON;
import com.google.gson.GsonBuilder;
import com.qs.mp.common.enums.ServerEnvEnum;
import com.qs.mp.common.utils.LogUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class JSMSUtils {

    protected static final Logger logger = LoggerFactory.getLogger(JSMSUtils.class);

    private static final String appkey = "07abbc24df161327ea51d311";
    private static final String masterSecret = "a7710786463881179a3d5b22";
    private static String env;

    @Value("${server.env}")
    public void setEnv(String serverEnv) {
        env = serverEnv;
    }

    public static void main(String[] args) {
        //testSendSMSCode();
         //testSendValidSMSCode();
//        testSendVoiceSMSCode();
//        testSendTemplateSMS();
    }

    /**
     * 提货短信发送
     * @param mobile    手机号
     * @param orderNo   订单尾号
     * @param context   内容
     */
    public static SendSMSResult sendDeliverSMS(String mobile,String orderNo ,String context) {
        SMSClient client = new SMSClient(masterSecret, appkey);
        Map<String, String> map = new HashedMap<>();
        map.put("number", orderNo);
        map.put("context", context);
        SMSPayload payload = SMSPayload.newBuilder().setMobileNumber(mobile).setTempId(209720).setTempPara(map).build();
        try {
                SendSMSResult res = client.sendTemplateSMS(payload);
                logger.info(res.toString());
                return res;
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. " + e.getMessage());
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. " + e.getMessage());
        }
        return null;
    }


    public static SendSMSResult sendSMSCode(String mobile) {
        SMSClient client = new SMSClient(masterSecret, appkey);
        SMSPayload payload = SMSPayload.newBuilder().setMobileNumber(mobile).setTempId(1).build();
        try {
//            if (ServerEnvEnum.PROD.getCode().equals(env)) {
                SendSMSResult res = client.sendSMSCode(payload);
                logger.info(res.toString());
                return res;
//            } else {
//                logger.info("非生产环境，不发送短信验证码！" + mobile);
//                return (new GsonBuilder()).excludeFieldsWithoutExposeAnnotation().create().fromJson("{\"msg_id\":\"123456789\"}", SendSMSResult.class);
//
//            }
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. " + e.getMessage());
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. " + e.getMessage());
        }
        return null;
    }

    public static SendSMSResult sendChannelActNotify(String mobile) {
        return sendSMSResult(mobile, 206810);
    }



    private static SendSMSResult sendSMSResult(String mobile, int tempId) {
        SMSClient client = new SMSClient(masterSecret, appkey);
        SMSPayload payload = SMSPayload.newBuilder().setMobileNumber(mobile).setTempId(tempId).build();
        try {
            if (ServerEnvEnum.PROD.getCode().equals(env)) {
                SendSMSResult res = client.sendTemplateSMS(payload);
                LogUtil.info(logger, "短信发送，mobile:{0}, res:{1}", new Object[]{mobile, JSON.toJSONString(res)});
                return res;
            } else {
                logger.info("非生产环境，不发送短信！" + mobile + "," + tempId);
                return (new GsonBuilder()).excludeFieldsWithoutExposeAnnotation().create().fromJson("{\"msg_id\":\"123456789\"}", SendSMSResult.class);

            }
        } catch (APIConnectionException e) {
            LogUtil.error(logger, "短信发送失败，mobile:{0}，msg:{1}", new Object[]{mobile, e.getMessage()});
        } catch (APIRequestException e) {
            LogUtil.error(logger, "短信发送失败，mobile:{0}，msg:{1}", new Object[]{mobile, e.getMessage()});
        }
        return null;
    }

    public static void testSendSMSWithIHttpClient() {
        SMSClient client = new SMSClient(masterSecret, appkey);
        String authCode = ServiceHelper.getBasicAuthorization(appkey, masterSecret);
        ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, ClientConfig.getInstance());
        // NettyHttpClient httpClient = new NettyHttpClient(authCode, null,
        // ClientConfig.getInstance());
        // ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null,
        // ClientConfig.getInstance());
        // 可以切换 HttpClient，默认使用的是 NativeHttpClient
        client.setHttpClient(httpClient);
        // 如果使用 NettyHttpClient，发送完请求后要调用 close 方法
        // client.close();
        SMSPayload payload = SMSPayload.newBuilder().setMobileNumber("13800138000").setTempId(1).build();
        try {
            SendSMSResult res = client.sendSMSCode(payload);
            logger.info(res.toString());
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        }
    }

    public static ValidSMSResult sendValidSMSCode(String messageId,String code) {
        SMSClient client = new SMSClient(masterSecret, appkey);
        try {
            logger.info("当前环境为:" + env);
            if (ServerEnvEnum.PROD.getCode().equals(env)) {
                ValidSMSResult res = client.sendValidSMSCode(messageId, code);
                logger.info(res.toString());
                return res;
            } else {
                logger.info("非生产环境，不做短信验证码验证！" + messageId + "," + code);
                return (new GsonBuilder()).excludeFieldsWithoutExposeAnnotation().create().fromJson("{\"is_valid\":TRUE}", ValidSMSResult.class);
            }
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. " +  e.getMessage());
        } catch (APIRequestException e) {
            if (e.getStatus() != 403) {
                logger.error(e.getStatus() + " errorCode: " + e.getErrorCode() + " " + e.getErrorMessage());
            }
        }
        return null;
    }

    /**
     * The default value of ttl is 60 seconds.
     */
    public static void testSendVoiceSMSCode() {
        SMSClient client = new SMSClient(masterSecret, appkey);
        SMSPayload payload = SMSPayload.newBuilder().setMobileNumber("13800138000").setTTL(90).build();
        try {
            SendSMSResult res = client.sendVoiceSMSCode(payload);
            logger.info(res.toString());
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        }
    }

    public static void testSendTemplateSMS() {
        SMSClient client = new SMSClient(masterSecret, appkey);
        SMSPayload payload = SMSPayload.newBuilder().setMobileNumber("13800138000").setTempId(1).addTempPara("test", "jpush").build();
        try {
            SendSMSResult res = client.sendTemplateSMS(payload);
            logger.info(res.toString());
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        }
    }

    public static void testSendBatchTemplateSMS() {
        SMSClient client = new SMSClient(masterSecret, appkey);
        List<RecipientPayload> list = new ArrayList<RecipientPayload>();
        RecipientPayload recipientPayload1 = new RecipientPayload.Builder().setMobile("13800138000").addTempPara("code", "638938").build();
        RecipientPayload recipientPayload2 = new RecipientPayload.Builder().setMobile("13800138000").addTempPara("code", "829302").build();
        list.add(recipientPayload1);
        list.add(recipientPayload2);
        RecipientPayload[] recipientPayloads = new RecipientPayload[list.size()];
        BatchSMSPayload smsPayload = BatchSMSPayload.newBuilder().setTempId(1).setRecipients(list.toArray(recipientPayloads)).build();
        try {
            BatchSMSResult result = client.sendBatchTemplateSMS(smsPayload);
            logger.info("Got result: " + result);
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        }
    }

    public static void testSendScheduleSMS() {
        SMSClient client = new SMSClient(masterSecret, appkey);
        ScheduleSMSPayload payload = ScheduleSMSPayload.newBuilder().setMobileNumber("13800138000").setTempId(1111).setSendTime("2017-07-31 16:17:00").addTempPara("number", "798560").build();
        try {
            ScheduleResult result = client.sendScheduleSMS(payload);
            logger.info(result.toString());
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        }
    }

    public static void testUpdateScheduleSMS() {
        SMSClient client = new SMSClient(masterSecret, appkey);
        ScheduleSMSPayload payload = ScheduleSMSPayload.newBuilder().setMobileNumber("13800138000").setTempId(1111).setSendTime("2017-07-31 15:00:00").addTempPara("number", "110110").build();
        try {
            ScheduleResult result = client.updateScheduleSMS(payload, "dsfd");
            logger.info(result.toString());
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        }
    }

    public static void testSendBatchScheduleSMS() {
        SMSClient client = new SMSClient(masterSecret, appkey);
        List<RecipientPayload> list = new ArrayList<RecipientPayload>();
        RecipientPayload recipientPayload1 = new RecipientPayload.Builder().setMobile("13800138000").addTempPara("number", "638938").build();
        RecipientPayload recipientPayload2 = new RecipientPayload.Builder().setMobile("13800138001").addTempPara("number", "829302").build();
        list.add(recipientPayload1);
        list.add(recipientPayload2);
        RecipientPayload[] recipientPayloads = new RecipientPayload[list.size()];
        ScheduleSMSPayload smsPayload = ScheduleSMSPayload.newBuilder().setSendTime("2017-07-31 16:00:00").setTempId(1245).setRecipients(list.toArray(recipientPayloads)).build();
        try {
            BatchSMSResult result = client.sendBatchScheduleSMS(smsPayload);
            logger.info(result.toString());
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        }
    }

    public static void testUpdateBatchScheduleSMS() {
        SMSClient client = new SMSClient(masterSecret, appkey);
        List<RecipientPayload> list = new ArrayList<RecipientPayload>();
        RecipientPayload recipientPayload1 = new RecipientPayload.Builder().setMobile("13800138000").addTempPara("number", "328393").build();
        RecipientPayload recipientPayload2 = new RecipientPayload.Builder().setMobile("13800138001").addTempPara("number", "489042").build();
        list.add(recipientPayload1);
        list.add(recipientPayload2);
        RecipientPayload[] recipientPayloads = new RecipientPayload[list.size()];
        ScheduleSMSPayload smsPayload = ScheduleSMSPayload.newBuilder().setSendTime("2017-07-31 16:00:00").setTempId(1245).setRecipients(list.toArray(recipientPayloads)).build();
        try {
            BatchSMSResult result = client.updateBatchScheduleSMS(smsPayload, "dfs");
            logger.info(result.toString());
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        }
    }

    public static void testDeleteScheduleSMS() {
        SMSClient client = new SMSClient(masterSecret, appkey);
        try {
            ResponseWrapper result = client.deleteScheduleSMS("sd");
            logger.info("Response content: " + result.responseContent + " response code: " + result.responseCode);
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        }
    }

    public static void testGetAccountSMSBalance() {
        SMSClient client = new SMSClient(masterSecret, appkey);
        try {
            AccountBalanceResult result = client.getSMSBalance();
            logger.info(result.toString());
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        }
    }

    public static void testGetAppSMSBalance() {
        SMSClient client = new SMSClient(masterSecret, appkey);
        try {
            AppBalanceResult result = client.getAppSMSBalance();
            logger.info(result.toString());
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        }
    }

    public void testCreateTemplate() {
        try {
            SMSClient client = new SMSClient(masterSecret, appkey);
            TemplatePayload payload = TemplatePayload.newBuilder().setTemplate("您好，您的验证码是{{code}}，2分钟内有效！").setType(1).setTTL(120).setRemark("验证短信").build();
            SendTempSMSResult result = client.createTemplate(payload);
            logger.info(result.toString());
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        }
    }

    // 只有审核不通过状态的模板才允许修改
    public void testUpdateTemplate() {
        try {
            SMSClient client = new SMSClient(masterSecret, appkey);
            TemplatePayload payload = TemplatePayload.newBuilder().setTempId(12345).setTemplate("您好，您的验证码是{{code}}，2分钟内有效！").setType(1).setTTL(120).setRemark("验证短信").build();
            SendTempSMSResult result = client.updateTemplate(payload, 12345);
            logger.info(result.toString());
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        }
    }

    public void testCheckTemplate() {
        try {
            SMSClient client = new SMSClient(masterSecret, appkey);
            TempSMSResult result = client.checkTemplate(144923);
            logger.info(result.toString());
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        }
    }

    public void testDeleteTemplate() {
        try {
            SMSClient client = new SMSClient(masterSecret, appkey);
            ResponseWrapper result = client.deleteTemplate(144923);
            logger.info(result.toString());
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Message: " + e.getMessage());
        }
    }

}
