package com.wecloud.im.tillo.app_ws.sender;

import com.wecloud.im.entity.ImApplication;
import com.wecloud.im.entity.ImClient;
import com.wecloud.im.entity.ImMessage;
import com.wecloud.im.push.PushUtils;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 异步系统推送
 */
@Component
@Slf4j
public class PushTask {

    /**
     * 谷歌推送地址
     */
    private static final String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";


    //您收到一条新消息
    String title = "You have received a new message";

    //点击查看
    String body = "Click to view";

    /**
     * 异步系统推送
     *
     * @param imClientReceiver
     * @param imClientSender
     * @param imMessage
     */
    @Async
    public void push(ImClient imClientReceiver, ImClient imClientSender, ImMessage imMessage, ImApplication imApplication) {
        log.debug("push " + imClientReceiver.getClientId());

        // 校验参数
        if (imClientReceiver.getValid() == null || imClientReceiver.getDeviceToken() == null || imClientReceiver.getDeviceType() == null) {

            log.debug("push参数错误");
            return;
        }
        // 设备不想收到推送提醒, 1想, 0不想
        if (imClientReceiver.getValid() == 0) {
            return;
        }

        //  设备类型1:ios; 2:android
        if (imClientReceiver.getDeviceType() == 1) {
            ios(imClientReceiver, imApplication);

        } else {
            android(imClientReceiver, imApplication, imMessage);
        }
    }

    private void android(ImClient imClientReceiver, ImApplication imApplication, ImMessage imMessage) {
        // 安卓推送通道,友盟:1;firebase:2; 信鸽3
        if (imApplication.getAndroidPushChannel() == 1) {
            log.debug("友盟");

            // 友盟推送
            PushUtils pushUtils = new PushUtils(imApplication.getUmengKey(), imApplication.getUmengSecret());

            // 安卓 单推
            String deviceTokenIOS = imClientReceiver.getDeviceToken();
            String titleIOS = title;
            String subtitle = "";
            try {
                pushUtils.sendIOSUnicast(deviceTokenIOS, titleIOS, subtitle, body);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (imApplication.getAndroidPushChannel() == 2) {

            //firebase:2
            log.debug("firebase");

            String jsonStr = null;
            try {
                URL url = new URL(API_URL_FCM);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setUseCaches(false);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setConnectTimeout(10000);
                conn.setRequestMethod("POST");
                //不设置默认发送文本格式。设置就是json
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Authorization", "key=" + imApplication.getFirebaseSecret());
                JSONObject json = new JSONObject();
                //推送到哪台客户端机器
                json.put("to", imClientReceiver.getDeviceToken());
                JSONObject info = new JSONObject();


                info.put("title", title);
                info.put("body", body);
                //数据消息data  通知消息 notification
                json.put("notification", info);

                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                jsonStr = json.toString();
                wr.write(jsonStr);
                wr.flush();
                InputStream inputStream = conn.getInputStream();
                InputStreamReader in = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(in);

                wr.close();
                reader.close();
            } catch (Exception e) {
                log.error("FCM push failure: " + jsonStr, e);
            }

        } else if (imApplication.getAndroidPushChannel() == 3) {
            //  信鸽3
            log.debug("信鸽3");


        } else {
            log.debug("没有找到推送类型");
            return;
        }
    }

    private void ios(ImClient imClientReceiver, ImApplication imApplication) {
        // ios推送通道,友盟:1;firebase:2; apns原生:3
        if (imApplication.getIosPushChannel() == 1) {
            log.debug("友盟");

            // 友盟推送
            PushUtils pushUtils = new PushUtils(imApplication.getUmengKey(), imApplication.getUmengSecret());

            // 安卓单推
            String deviceToken = imClientReceiver.getDeviceToken();
            String unicastText = "Android unicast text";
            String unicastTicker = body;
            try {
                pushUtils.sendAndroidUnicast(deviceToken, unicastText, unicastTicker, title);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (imApplication.getIosPushChannel() == 2) {

            //firebase:2
            log.debug("firebase");


            String jsonStr = null;
            try {
                URL url = new URL(API_URL_FCM);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setUseCaches(false);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setConnectTimeout(10000);
                conn.setRequestMethod("POST");
                //不设置默认发送文本格式。设置就是json
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Authorization", "key=" + imApplication.getFirebaseSecret());
                JSONObject json = new JSONObject();
                //推送到哪台客户端机器
                json.put("to", imClientReceiver.getDeviceToken());
                JSONObject info = new JSONObject();
                info.put("title", title);
                info.put("body", body);
                //数据消息data  通知消息 notification
                json.put("notification", info);

                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                jsonStr = json.toString();
                wr.write(jsonStr);
                wr.flush();
                InputStream inputStream = conn.getInputStream();
                InputStreamReader in = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(in);
//            String line = null;

                wr.close();
                reader.close();
            } catch (Exception e) {
                log.error("FCM push failure: " + jsonStr, e);
            }


        } else if (imApplication.getIosPushChannel() == 3) {
            //  apns原生:3
            log.debug("apns原生");


        } else {
            log.debug("没有找到推送类型");
            return;
        }
    }

}
