package tech.glinfo.enbao.common.utils;

import com.alibaba.druid.support.json.JSONUtils;
import com.gexin.fastjson.JSONObject;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.notify.Notify;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.base.payload.VoIPPayload;
import com.gexin.rp.sdk.dto.GtReq;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.gexin.rp.sdk.template.style.Style0;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@ConfigurationProperties(prefix = "getui")
public class AppPush {

    protected Logger logger = LoggerFactory.getLogger(getClass());
    private String appId;
    private String appSecret;
    private String appKey;
    private String masterSecret;

    private static String host = "http://sdk.open.api.igexin.com/apiex.htm";

    private static final String INTENT = "intent:#Intent;launchFlags=0x04000000;action=android.intent.action.oppopush;package=com.zwgongxiang.jieshi;component=com.zwgongxiang.jieshi/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=${title};S.content=${content};S.payload=zwgongxiang;end";

    /**
     * 推送
     *
     * @param title    标题
     * @param content  内容
     * @param clientId 客户端ID，对应app_user表thirdid第三方ID
     */
    public void push(String title, String content, String clientId) {
        String[] cids = clientId.split("#");
        logger.info("消息推送push：{},{},{}", title, content, clientId);
        if (cids.length > 1) {
//            if ("1".equals(cids[1])) {
//                pushAndroid(title, content, cids[0]);
//            } else if ("2".equals(cids[1])) {
//                pushIos(title, content, cids[0]);
//            }
            toSingle(title, content, cids[0]);
        } else {
//            pushAndroid(title, content, clientId);
            toSingle(title, content, clientId);
        }
    }

    public void pushAndroid(String title, String content, String clientId) {
        IGtPush push = new IGtPush(host, appKey, masterSecret);
        NotificationTemplate template = getNotificationTemplate(title, content);
//        TransmissionTemplate template = getTransmissionTemplate(content);
        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒
        message.setOfflineExpireTime(24 * 3600 * 1000);
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(clientId);
        //target.setAlias(Alias);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            logger.info(ret.getResponse().toString());
        } else {
            logger.error("服务器响应异常");
        }
    }

    public NotificationTemplate getNotificationTemplate(String title, String content) {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);

        Style0 style = new Style0();
        // 设置通知栏标题与内容
        style.setTitle(title);
        style.setText(content);
        // 配置通知栏图标
        style.setLogo("push.png");
        // 配置通知栏网络图标
        style.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        template.setStyle(style);

        template.setTransmissionType(2);  // 透传消息接受方式设置，1：立即启动APP，2：客户端收到消息后需要自行处理
        template.setTransmissionContent(content);
        return template;
    }


    public TransmissionTemplate getTransmissionTemplate(String content) {

        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);

        template.setTransmissionType(2);
        template.setTransmissionContent(content);
        //template.setAPNInfo(getAPNPayload()); //详见本页iOS通知样式设置
        return template;

    }

    /**
     * 单个用户ios推送
     *
     * @param
     * @return
     */
    public void pushIos(String title, String msg, String cId) {
        IGtPush push = new IGtPush(host, appKey, masterSecret);

        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionContent(msg);
        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(2);
        //设置ios
        template.setAPNInfo(getAPNPayload(title, msg));

        SingleMessage message = new SingleMessage();
        message.setData(template);
        message.setOffline(true);
        //离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 1000 * 3600);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);

        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cId);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            logger.info(ret.getResponse().toString());
        } else {
            logger.error("【IOS】个推，服务器异常");
        }
    }

    private APNPayload getAPNPayload(String title, String msg) {

        APNPayload payload = new APNPayload();
        //在已有数字基础上加1显示，设置为-1时，在已有数字上减1显示，设置为数字时，显示指定数字(设置角标)
        payload.setAutoBadge("+1");

        payload.setContentAvailable(1);

        //简单模式APNPayload.SimpleMsg
//        payload.setAlertMsg(new APNPayload.SimpleAlertMsg(msg));
        //字典模式使用下者
        payload.setAlertMsg(getDictionaryAlertMsg(title, msg));
        //添加附加信息
        payload.addCustomMsg("message", msg);
        return payload;
    }

/*    private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(String title, String body) {
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        // iOS8.2以上版本支持
        alertMsg.setTitle(title);

        alertMsg.setBody(body);
        return alertMsg;
    }*/

    /**
     * 推送消息至App所有用户，100次/天，每分钟不能超过5次，相同的消息内容，10分钟内不可以重复发送<br/>
     * 华为，平果测试通过
     *
     * @param getuiMessage
     * @return
     */
//    public IPushResult toApp(GetuiMessage getuiMessage) {
//        TransmissionTemplate template = getTransmissionTemplateWith3rdNotifyInfoAndAPNPayload(getuiMessage.getMessageTitle(),
//                getuiMessage.getMessageContent(), "+1", getuiMessage);
//        AppMessage message = new AppMessage();
//        message.setData(template);
//        message.setOffline(true);
//        message.setOfflineExpireTime(24 * 1000 * 3600);
//        message.setAppIdList(Arrays.asList(appId));
//        IPushResult ret = GetuiConfig.me.getPush().pushMessageToApp(message);
//        logger.info(JSONUtils.toJSONString(ret));
//        return ret;
//    }

    /**
     * 推送消息至特定的ClientID,频次限制：没有限制！
     *
     * @param title 标题
     * @param content 内容
     * @param clientId     接收的ClientId
     * @return
     */
    public IPushResult toSingle(String title, String content, String clientId) {
        IGtPush push = new IGtPush(host, appKey, masterSecret);
        Map params = new MapUtils().put("title", title).put("content", content);
        // 获取消息模板
        TransmissionTemplate template = getTransmissionTemplateWith3rdNotifyInfoAndAPNPayload(title, content, "+1", params);
        // 制作消息
        SingleMessage message = new SingleMessage();
        message.setData(template);
        message.setOffline(true);// 设置消息离线，并设置离线时间
        message.setOfflineExpireTime(72 * 3600 * 1000); // 离线有效时间，单位为毫秒，可选
//      message.setPriority(1);// 优先级
//      message.setPushNetWorkType(0); // 判断客户端是否wifi环境下推送。1为仅在wifi环境下推送，0为不限制网络环境，默认不限
        // 生成接收人
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(clientId);
        // 发送消息
        IPushResult ret = push.pushMessageToSingle(message, target);
        if(ret != null) {
            logger.info("消息推送结果：{}", ret.getResponse());
        } else {
            logger.info("消息推送结果：没有返回");

        }
        return ret;
    }

    /**
     * 获取同时有Android第三方推送及IOS推送功能的很透传消息
     *
     * @param title       标题
     * @param body        正文
     * @param badge       IOS的角标数
     * @param customParam 自定义属性
     * @return
     */
    public TransmissionTemplate getTransmissionTemplateWith3rdNotifyInfoAndAPNPayload(String title, String body, String badge,
                                                                                      Map<String, String> customParam) {
        TransmissionTemplate template = new TransmissionTemplate();

        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);

        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(2);
        template.setTransmissionContent(JSONUtils.toJSONString(customParam)); // 透传内容

        // 第三方厂商推送
        template.set3rdNotifyInfo(get3rdNotifyInfo(title, body, customParam));

        // 针对IOS，设置APNs
        template.setAPNInfo(getAPNPayload(title, body, badge, customParam)); // ios消息推送
        return template;
    }

    /**
     * 第三方厂商通知
     *
     * @param title   标题
     * @param content 正文
     * @param payload 附带属性
     * @return
     */
    private Notify get3rdNotifyInfo(String title, String content, Map<String, String> payload) {
        Notify notify = new Notify();
        notify.setTitle(title);
        notify.setContent(content);
        notify.setType(GtReq.NotifyInfo.Type._intent);
        notify.setIntent(getIntent(title, content, payload));
        notify.setPayload(JSONUtils.toJSONString(payload));
        return notify;
    }

    private String getIntent(String title, String content, Map<String, String> payload) {
        return "intent:#Intent;launchFlags=0x04000000;action=android.intent.action.oppopush;package=com.zwgongxiang.jieshi;component=com.zwgongxiang.jieshi/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title="+title+";S.content="+content+";S.payload=zwgongxiang;end";
    }

    /**
     * IOS的APNs消息
     *
     * @param title
     * @param body
     * @param badge
     * @param customMsg
     * @return
     */
    private APNPayload getAPNPayload(String title, String body, String badge, Map<String, String> customMsg) {
        APNPayload payload = new APNPayload();
        // 在已有数字基础上加1显示，设置为-1时，在已有数字上减1显示，设置为数字时，显示指定数字
        if (badge != null && badge.trim().length() > 0) {
            payload.setAutoBadge(badge);
        }
        payload.setContentAvailable(1);
        // ios 12.0 以上可以使用 Dictionary 类型的 sound
        payload.setSound("default");
//      payload.setCategory("$由客户端定义");
        if (customMsg != null) {
            for (Map.Entry<String, String> enty : customMsg.entrySet()) {
                payload.addCustomMsg(enty.getKey(), enty.getValue());
            }
        }
//      payload.setAlertMsg(new APNPayload.SimpleAlertMsg("helloCCCC"));//简单模式APNPayload.SimpleMsg
        payload.setAlertMsg(getDictionaryAlertMsg(title, body)); // 字典模式使用APNPayload.DictionaryAlertMsg

//      // 设置语音播报类型，int类型，0.不可用 1.播放body 2.播放自定义文本
//      payload.setVoicePlayType(2);
//      // 设置语音播报内容，String类型，非必须参数，用户自定义播放内容，仅在voicePlayMessage=2时生效
//      // 注：当"定义类型"=2, "定义内容"为空时则忽略不播放
//      payload.setVoicePlayMessage("定义内容");
//
//      // 添加多媒体资源
//      payload.addMultiMedia(new MultiMedia().setResType(MultiMedia.MediaType.pic).setResUrl("资源文件地址").setOnlyWifi(true));

        return payload;
    }

    /**
     * IOS通知提示样式
     *
     * @param title
     * @param body
     * @return
     */
    private APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(String title, String body) {
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        alertMsg.setBody(body);
//      alertMsg.setActionLocKey("显示关闭和查看两个按钮的消息");
//      alertMsg.setLocKey("loc-key1");
//      alertMsg.addLocArg("loc-ary1");
//      alertMsg.setLaunchImage("调用已经在应用程序中绑定的图形文件名");
        // iOS8.2以上版本支持
        alertMsg.setTitle(title);
//      alertMsg.setTitleLocKey("自定义通知标题");
//      alertMsg.addTitleLocArg("自定义通知标题组");
        return alertMsg;
    }

    /**
     * 需要使用iOS语音传输，请使用VoIPPayload代替APNPayload【未测试】
     *
     * @return
     */
    private VoIPPayload getVoIPPayload() {
        //TODO 未测试，未开发完成
        VoIPPayload payload = new VoIPPayload();
        JSONObject jo = new JSONObject();
        jo.put("key1", "value1");
        payload.setVoIPPayload(jo.toString());
        return payload;
    }

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getAppSecret() {
        return appSecret;
    }

    public void setAppSecret(String appSecret) {
        this.appSecret = appSecret;
    }

    public String getAppKey() {
        return appKey;
    }

    public void setAppKey(String appKey) {
        this.appKey = appKey;
    }

    public String getMasterSecret() {
        return masterSecret;
    }

    public void setMasterSecret(String masterSecret) {
        this.masterSecret = masterSecret;
    }
}
