package xiaoqu.home.open.utils;

import com.alibaba.fastjson.JSONObject;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.ListMessage;
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.MultiMedia;
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.AbstractTemplate;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.gexin.rp.sdk.template.style.AbstractNotifyStyle;
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.stereotype.Component;
import xiaoqu.home.open.entity.PushInput;

import java.util.List;

@Component
public class GeTuiUtils {
    private static Logger log = LoggerFactory.getLogger("task");

    private static String appId;
    private static String appSecret;
    private static String appKey;
    private static String masterSecret;

    @Value("${getui.appKey}")
    public void setAppKey(String appKey1) {
        appKey = appKey1;
    }

    @Value("${getui.masterSecret}")
    public void setMasterSecret(String masterSecret1) {
        masterSecret = masterSecret1;
    }

    @Value("${getui.appId}")
    public void setappId(String appId1) {
        appId = appId1;
    }

    @Value("${getui.appSecret}")
    public void setappSecret(String appSecret1) {
        appSecret = appSecret1;
    }


//    public static IGtPush push = new IGtPush(appKey, masterSecret);


    /**
     * 批量推送到个推
     *
     * @param targets
     * @param content
     */
    public static void pushByType(List<Target> targets, String content) {
        System.setProperty("gexin_pushList_needDetails", "true");
        IGtPush push = new IGtPush(appKey, masterSecret);
        String taskId = push.getContentId(getListMessage(content));
        IPushResult ret = null;
        try {
            ret = push.pushMessageToList(taskId, targets);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ret != null) {
            log.debug("【pushByType】ret:" + JSONObject.toJSONString(ret));

            System.out.println(ret.getResponse().toString());
        } else {
            log.debug("【pushByType】ret:服务器响应异常");
            System.out.println("服务器响应异常");
        }
    }


    public static void pushByTypePost(List<Target> targets, String content, PushInput pushInput) {
        IGtPush push = new IGtPush(pushInput.getAppKey(), pushInput.getMasterSecret());
        String taskId = push.getContentId(getListMessagePost(content, pushInput));
        IPushResult ret = null;
        try {
            ret = push.pushMessageToList(taskId, targets);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ret != null) {
            log.debug("【pushByTypePost】ret:" + JSONObject.toJSONString(ret));
            System.out.println(ret.getResponse().toString());
        } else {
            log.debug("【pushByTypePost】ret:服务器响应异常");
            System.out.println("服务器响应异常");
        }
    }

    private static ListMessage getListMessage(String content) {
        NotificationTemplate template = getNotificationTemplate(appId, appSecret, content);
        ListMessage message = new ListMessage();
        message.setData(template);
        // 设置消息离线，并设置离线时间
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 1000 * 3600);
        message.setPushNetWorkType(1);//判断客户端是否wifi环境下推送。1为仅在wifi环境下推送，0为不限制网络环境，默认不限
        message.setPriority(1);

        return message;
    }

    private static ListMessage getListMessagePost(String content, PushInput pushInput) {
        NotificationTemplate template = getNotificationTemplate(pushInput.getAppId(), pushInput.getAppSecret(), content);
        ListMessage message = new ListMessage();
        message.setData(template);
        // 设置消息离线，并设置离线时间
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 1000 * 3600);
        message.setPushNetWorkType(1);//判断客户端是否wifi环境下推送。1为仅在wifi环境下推送，0为不限制网络环境，默认不限
        message.setPriority(1);
        return message;
    }

    private SingleMessage getSingleMessage(AbstractTemplate template) {
        SingleMessage message = new SingleMessage();
        message.setData(template);
        // 设置消息离线，并设置离线时间
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 3600 * 1000);
        message.setPriority(1);
        message.setPushNetWorkType(1); // 判断客户端是否wifi环境下推送。1为仅在wifi环境下推送，0为不限制网络环境，默认不限
        return message;
    }


    /**
     * 点击通知打开应用模板, 在通知栏显示一条含图标、标题等的通知，用户点击后激活您的应用。
     * 通知模板(点击后续行为: 支持打开应用、发送透传内容、打开应用同时接收到透传 这三种行为)
     *
     * @return
     */
    public static NotificationTemplate getNotificationTemplate(String appId, String appSecret, String content) {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appSecret);
        //设置展示样式
        template.setStyle(getStyle0(content));
        template.setTransmissionType(1);  // 透传消息设置，收到消息是否立即启动应用： 1为立即启动，2则广播等待客户端自启动
        template.setTransmissionContent(content);
//        template.setSmsInfo(PushSmsInfo.getSmsInfo()); //短信补量推送

//        template.setDuration("2019-07-09 11:40:00", "2019-07-09 12:24:00");  // 设置定时展示时间，安卓机型可用
        template.setNotifyid(123); // 在消息推送的时候设置notifyid。如果需要覆盖此条消息，则下次使用相同的notifyid发一条新的消息。客户端sdk会根据notifyid进行覆盖。
        return template;
    }

    /**
     * Style0 系统样式
     *
     * @return
     * @link http://docs.getui.com/getui/server/java/template/ 查看效果
     */
    public static AbstractNotifyStyle getStyle0(String content) {
        Style0 style = new Style0();
        // 设置通知栏标题与内容
        style.setTitle(content);
        style.setText(content);
        // 配置通知栏图标
        style.setLogo("icon.png"); //配置通知栏图标，需要在客户端开发时嵌入，默认为push.png
        // 配置通知栏网络图标
        style.setLogoUrl("");

        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        style.setChannel("通知渠道id");
        style.setChannelName("通知渠道名称");
        style.setChannelLevel(3); //设置通知渠道重要性
        return style;
    }


    public static TransmissionTemplate transmissionTemplateDemo(String appId, String appKey) {
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionContent("透传内容");
        template.setTransmissionType(2);
        Notify notify = new Notify();
        notify.setTitle("请输入通知栏标题1");
        notify.setContent("请输入通知栏内容1");
        notify.setIntent("intent:#Intent;launchFlags=0x10000000;package=com.pp.yl;component=你的包名/com.getui.demo.MainActivity;i.parm1=12;end");
        notify.setType(GtReq.NotifyInfo.Type._intent);
// notify.setUrl("https://dev.getui.com/");
//notify.setType(Type._url);
        template.set3rdNotifyInfo(notify);//设置第三方通知
        return template;
    }


    public static String uniPushOffLine(String title, String text,  PushInput pushInput,String clientId,JSONObject jsonObject) {

        String result = null;
        if (pushInput == null) {
            log.debug("【uniPushOffLine】appKey："+appKey+",masterSecret:"+masterSecret+",appId:"+appId+",appSecret:"+appSecret);
            IGtPush push = new IGtPush(appKey, masterSecret);
            TransmissionTemplate template = offLinetransmissionTemplate(title, text,  appId,appKey,jsonObject);
            result = getString(appId, clientId, push, template);

        }else{
            IGtPush push = new IGtPush(pushInput.getAppKey(), pushInput.getMasterSecret());
            TransmissionTemplate template = offLinetransmissionTemplate(title, text,  pushInput.getAppId(), pushInput.getAppKey(),jsonObject);
            result = getString(pushInput.getAppId(), pushInput.getClientId(), push, template);
        }
        return result;
    }

    public static String uniPushOnLine(String title, String text, PushInput pushInput, String context, String clientId) {
        String result = null;
        if (pushInput == null) {
            log.debug("【uniPushOnLine】appKey："+appKey+",masterSecret:"+masterSecret+",appId:"+appId+",appSecret:"+appSecret+",context"+context);
            IGtPush push = new IGtPush(appKey, masterSecret);
            NotificationTemplate template = onlineNotificationTemplate(title, text, context, appId, appKey);
            result = getString(appId, clientId, push, template);
        } else {
            IGtPush push = new IGtPush(pushInput.getAppKey(), pushInput.getMasterSecret());
            NotificationTemplate template = onlineNotificationTemplate(title, text, context, pushInput.getAppId(), pushInput.getAppKey());
            result = getString(pushInput.getAppId(), clientId, push, template);
        }
        return result;
    }

    private static String getString(String appId, String clientId, IGtPush push, AbstractTemplate template) {
        log.debug("【getString】appid:"+appId+",clientId:"+clientId);
        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) {
            log.info("推送成功，第三方返回：" + ret.getResponse().toString());
        } else {
            log.error("推送时第三方服务器响应异常");
        }
        return JSONObject.toJSONString(ret.getResponse());
    }

    public static TransmissionTemplate offLinetransmissionTemplate(String title, String text,  String appId1, String appkey1,JSONObject paramJosn) {

        //厂商通道离线推送注意类的使用，在线和离线使用不同
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId1);
        template.setAppkey(appkey1);
        Notify notify = new Notify();
        notify.setTitle(title);
        notify.setContent(text);

//这是厂商通道连接，其中注意参数component=io.dcloud.xxx/io.dcloud.PandoraEntry，有xxx是你的包名，S.payload这个值是你要穿透的内容，注意连接的长度，过长厂商通道会失效。
//paramJosn.toJSONString()
//android.intent.action.oppopush;launchFlags=0x14000000;component=io.dcloud.xxx/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=收车;S.content=收车;在
        String jsonstring = paramJosn!=null?paramJosn.toJSONString():"";
        String intent = "intent:#Intent;action=android.intent.action.oppopush;launchFlags=0x14000000;component=io.dcloud.UNI0F29818/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=" + title + ";S.content=" + text + ";" + "S.payload=" + jsonstring+ ";end";
        log.info("【TransmissionTemplate】"+intent);
        notify.setIntent(intent);
        notify.setType(GtReq.NotifyInfo.Type._intent);
        template.set3rdNotifyInfo(notify);//设置第三方通知
        //ios处理通知消息
        APNPayload payload = new APNPayload();
        payload.setAutoBadge("+1");
        payload.setContentAvailable(0);
        payload.setSound("default");


        for (String key : paramJosn.keySet()) {
            //System.out.println(key +":" + paramJosn.get(key).getAsString());
            payload.addCustomMsg(key, paramJosn.get(key));
        }

        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        alertMsg.setTitle(title);
        alertMsg.setBody(text);
        payload.setAlertMsg(alertMsg);

        //ios
        template.setAPNInfo(payload);
        //这里也可设置穿透内容
        template.setTransmissionContent(text);
        template.setTransmissionType(1);

        return template;
    }


    public static NotificationTemplate onlineNotificationTemplate(String title, String text, String penetrateParam, String appId1, String appkey1) {
        log.info("【onlineNotificationTemplate】title"+title+",text"+text+",penetrateParam"+penetrateParam+",appId1"+appId1);

        //这里可以看到在线和离线使用的不同类进行处理
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId1);
        template.setAppkey(appkey1);

        Style0 style = new Style0();
        // 设置通知栏标题与内容
        style.setTitle(title);
        style.setText(text);
        // 配置通知栏图标
//         style.setLogo("icon.png");
        // 配置通知栏网络图标
//        style.setLogoUrl("http://img.schyxgl.com/201908201619esc.png");
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        //style.setChannel("通知渠道id");
        // style.setChannelName("通知渠道名称");
        style.setChannelLevel(3); //设置通知渠道重要性
        //安卓
        template.setStyle(style);


        //ios处理
        APNPayload payload = new APNPayload();
        payload.setAutoBadge("+1");
        payload.setContentAvailable(0);
        payload.setSound("default");
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        alertMsg.setTitle(title);
        alertMsg.setBody(text);
//        alertMsg.addLocArg(penetrateParam);
        payload.setAlertMsg(alertMsg);

        MultiMedia multiMedia = new MultiMedia();
        multiMedia.setResUrl("http://img.schyxgl.com/201908201619esc.png");
        multiMedia.setResType(MultiMedia.MediaType.pic);
        multiMedia.setOnlyWifi(false);
//        multiMedia.setResId(UUIDUtils.getUUID());
//        payload.addMultiMedia(multiMedia);
//        ios
        template.setAPNInfo(payload);

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


}
