package com.efounder.chat.utils;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import androidx.core.app.TaskStackBuilder;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.efounder.chat.R;
import com.efounder.chat.activity.GroupNotifacationActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.ApplyGroupNotice;
import com.efounder.chat.model.Group;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.struct.StructFactory;
import com.efounder.frame.activity.EFAppAccountMainActivity;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.AppContext;
import com.efounder.util.JSONUtil;
import com.efounder.util.URLModifyDynamic;
import com.efounder.utils.ResStringUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static android.content.Context.NOTIFICATION_SERVICE;

/**
 * 消息 通知服务，zidingyi
 * Created by yqs on 2016/10/31.
 */

public class ImNotificationUtil {
    public static String TAG = "ImNotificationUtil";
    public static String APPLYING = "APPLYING";//加群申请
    public static final String CHANNEL_ID_CONTACTS = "channel_id_contacts";
    public static final String CHANNEL_ID_BACKGROUND_SERVICE = "pansoft_channel_id_background_service";

    public static final String CHANNEL_ID_SUBSCRIBER = "channel_id_subscribes";
    public static final String NOTIFI_GROUP_ID_MAIN = "group_id_main";
//    public static String APPLYSUCCESS = "APPLYSUCCESS";//加群申请通过


    public static synchronized void showNotificationIm(final Context context, final IMStruct002 imstruct002) {
        createNotificationChannel(context);

        String userName = "";
        String fromUserName = "";
        int userId = -1;
        User user = null;
        String avatatUrl = "";
        final int requestCode;
        int unreadNum = 1;//未读消息数目，显示在通知的右下方
        /**
         * 根据单人、公号聊天或是群聊，得到User或Group对象
         * 设置通知中显示的消息标题userName（用户名或群名），unreadNum未读消息数
         */
        if (imstruct002.getToUserType() == StructFactory.TO_USER_TYPE_PERSONAL
                || imstruct002.getToUserType() == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT) { //个人聊天或公众号聊天
            user = WeChatDBManager.getInstance().getOneFriendById(imstruct002.getFromUserId());
            if (String.valueOf(user.getId()).equals(user.getNickName()))
                user = WeChatDBManager.getInstance().getOneUserById(imstruct002.getFromUserId());
            if (user != null) {
                userName = user.getNickName();
                userId = user.getId();
                fromUserName = userName;
                avatatUrl = user.getAvatar();
            }
            unreadNum = JFMessageManager.getInstance().getUnReadCount(imstruct002.getFromUserId(), imstruct002.getToUserType());
        } else if (imstruct002.getToUserType() == StructFactory.TO_USER_TYPE_GROUP) {//群聊
            Group group = WeChatDBManager.getInstance().getGroupWithUsers(imstruct002.getToUserId());
            user = WeChatDBManager.getInstance().getOneUserById(imstruct002.getFromUserId());
            if (group != null) {
                userName = group.getGroupName();
                userId = group.getGroupId();
                avatatUrl = group.getAvatar();
                fromUserName = user.getNickName();
            }
            unreadNum = JFMessageManager.getInstance().getUnReadCount(imstruct002.getToUserId(), imstruct002.getToUserType());
        }

        PendingIntent contentIntent = null;
        requestCode = getUniqueCode(imstruct002, userId);

        /**
         * 如果应用启动，通过判断user的类型，1为公众号，0为个人好友
         * 获取他们的id，分别调到公号聊天或个人、群聊
         * 若应用没有启动，则启动TabBottomActivity
         */
        Log.i(TAG, "---packageName--" + context.getPackageName());
        if (AppUtils.isAppAlive(context, context.getPackageName())) {
            Log.i(TAG, "---app is live---");
            if (user != null && user.getType() == 1) {
                Intent intent = null;
                intent = new Intent(context, EFAppAccountMainActivity.class);
                intent.putExtra("id", user.getId());
                intent.putExtra("nickName", user.getNickName());
                intent.putExtra("type", "chat");
                contentIntent = PendingIntent.getActivity(context, requestCode,
                        intent, PendingIntent.FLAG_UPDATE_CURRENT);
            } else {

                try {
                    //通过主工程配置 可以获取到要跳转的界面
                    String className = context.getResources().getString(R.string.chat_actiivity_class);
                    Class clazz = Class.forName(className);

                    String backClassName = context.getResources().getString(R.string.from_group_backto_first);
                    Class backClass = Class.forName(backClassName);
                    Intent intent = new Intent(context, clazz);
                    intent.putExtra("id", userId);
                    intent.putExtra("chattype", imstruct002.getToUserType());
                    TaskStackBuilder stackBuilder = TaskStackBuilder.create(AppContext.getInstance());
                    stackBuilder.addParentStack(backClass);
                    stackBuilder.addNextIntent(intent);
                    contentIntent = stackBuilder.getPendingIntent(requestCode, PendingIntent.FLAG_UPDATE_CURRENT);


                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } else {
            try {
                Class clazz = Class.forName(context.getResources().getString(R.string.from_group_backto_first));
                Intent intent = new Intent(context, clazz);
                intent.setFlags(
                        Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                contentIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent
                        .FLAG_UPDATE_CURRENT);

//                Intent intent = new Intent(context, clazz);
//                TaskStackBuilder stackBuilder = TaskStackBuilder.create(AppContext.getInstance());
//                stackBuilder.addParentStack(New_FriendsActivity.class);
//                stackBuilder.addNextIntent(intent);
//                 contentIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        final NotificationManager mNM = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        final String message = getMessage(context, imstruct002);//消息内容
//        long[] vibrate = {0, 100, 200, 300};//震动间隔
        //构建通知的Builder
        final String finalAvatatUrl = avatatUrl;
        final PendingIntent finalContentIntent = contentIntent;
        //in case title too long, restrict it to 12 characters
        if (userName.length() >= 12) {
            userName = userName.substring(0, 10).concat("...");
        }
        final String finalUserName = userName;
        final int finalUnreadNum = unreadNum;
        final String finalFromUserName = fromUserName;
        //创建通知时，标记你的渠道id
//        Notification notification = new Notification.Builder(MainActivity.this, channelId)
//                .setSmallIcon(R.mipmap.ic_launcher)
//                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
//                .setContentTitle("一条新通知")
//                .setContentText("这是一条测试消息")
//                .setAutoCancel(true)
//                .build();
//        notificationManager.notify(1, notification);
        Disposable disposable = Observable.create(new ObservableOnSubscribe<Bitmap>() {
            @Override
            public void subscribe(ObservableEmitter<Bitmap> emitter) throws Exception {
                Bitmap bitmap = getAvatar(context, finalAvatatUrl);
                emitter.onNext(bitmap);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Bitmap>() {
            @Override
            public void accept(Bitmap bitmap) throws Exception {
                NotificationCompat.Builder mBuilder = null;
                if (imstruct002.getToUserType() == StructFactory.TO_USER_TYPE_PERSONAL ||
                        imstruct002.getToUserType() == StructFactory.TO_USER_TYPE_GROUP) {
                    mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID_CONTACTS);
                } else {
                    mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID_CONTACTS);
                }
                        mBuilder
                        //大图标为头像
                        .setLargeIcon(bitmap)
                        .setTicker(context.getResources().getString(R.string.im_new_message_tip))
                        //设置Intent
                        .setContentIntent(finalContentIntent)
                        //设置未读聊天数
                        .setNumber(finalUnreadNum)
                        // .setDefaults(Notification.DEFAULT_LIGHTS)
                        //.setDefaults(Notification.FLAG_SHOW_LIGHTS)
                        .setAutoCancel(true)
                        // .setVibrate(vibrate)//设置震动
                        .setLights(0xff00ff00, 300, 1000)
                        //设置通知中显示的小图标的背景色
                        .setColor(Color.parseColor("#243BAE"))
                        //设置时间
                        .setWhen(imstruct002.getTime());

                if (finalUnreadNum == 0) {
                    //消息被其他端已读，不显示新消息数量
                    //设置标题，发送人或群聊名
                    mBuilder.setContentTitle(finalUserName);
                } else {
                    //设置标题，发送人或群聊名
                    mBuilder.setContentTitle((context.getString(R.string.chat_notification_title,
                            finalUserName, finalUnreadNum)));
                }

                try {
                    if (imstruct002.getMessageChildType() == MessageChildTypeConstant.subtype_mZoneNotification) {
                        try {
                            mBuilder.setContentText(context.getResources().getString(R.string.zone_message_hint)
                                    + JSONUtil.parseJson(new String(imstruct002.getBody(), "utf-8")).
                                    get("showMsg").getAsString());
                        } catch (IllegalStateException e) {
                            mBuilder.setContentText(context.getResources().getString(R.string.zone_message_hint)
                                    + message);//正文为发送人+信息内容
                        }
                    } else if (imstruct002.getMessageChildType() == MessageChildTypeConstant
                            .subtype_format_text && TextFormatMessageUtil.checkHasAtMe(imstruct002)) {
                        //消息类型是@类型，且是@我的，之前加[有人@我]
                        mBuilder.setContentText(ResStringUtil.getString(R.string.chat_mention_hint) + finalFromUserName + ":" + message);
                    }else {
                        mBuilder.setContentText(finalFromUserName + ":" + message);//正文为发送人+信息内容
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                /**
                 * 5.0以上需要使用透明背景纯白的小图标
                 * 5.0以下使用彩色图标
                 */
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                    mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher_alpha);
//                } else {
                mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher);
                // }
                //显示通知，id和PendingIntent的requestCode一致
                mNM.notify(requestCode, mBuilder.build());
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {

            }
        });


    }

    /**
     * 获取头像的Bitmap
     *
     * @param avatatUrl 头像Url
     * @return 头像Bitmap
     */
    private static Bitmap getAvatar(Context context, String avatatUrl) throws ExecutionException, InterruptedException {
        Object imageObject = null;
        if (avatatUrl.contains("http")) {
            imageObject = URLModifyDynamic.getInstance().replace(avatatUrl);
        } else {
            File file = new File(avatatUrl);
            if (file != null && file.exists()) {
                imageObject = "file://" + avatatUrl;
            } else {
                imageObject = R.drawable.default_useravatar;
            }
        }
        FutureTarget<Bitmap> target = Glide.with(context).asBitmap()
                .load(imageObject).apply(new RequestOptions().error(R.drawable.default_useravatar))
                .submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
        return target.get();
    }

    /**
     * 获取信息，非文本和表情则显示各自信息的类型
     *
     * @param imstruct002 imStruct002
     * @return 消息内容
     */
    public static String getMessage(Context context, IMStruct002 imstruct002) {
        String message = "";
        message = ChatTypeUtil.getMessageByType(context, imstruct002, "");

        return message;
    }

//TODO 显示加群申请或加入成功的提示

    /**
     * @param context context
     * @param notice  好友申请通知
     * @param type    类型
     */
    public static void showApplyGroupNotice(Context context, ApplyGroupNotice notice, String
            type) {
        String text = "";
        if (notice.getGroup() != null) {
            text = notice.getGroup().getGroupName();
        }
        if (text.length() > 8) {
            text = text.substring(0, 8) + "..群";
        } else {
            text = text + "群";

        }
        NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intent = new Intent(context, GroupNotifacationActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(AppContext.getInstance());
        stackBuilder.addParentStack(GroupNotifacationActivity.class);
        stackBuilder.addNextIntent(intent);
        PendingIntent contentIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
//        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        long[] vibrate = {0, 100, 200, 300};
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context, CHANNEL_ID_CONTACTS)
                        .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), com.efounder.chat.R.drawable.wechat_icon_launcher))
                        .setTicker(notice.getUser().getNickName() + "申请加入" + text)
                        .setContentTitle(context.getResources().getString(R.string.im_add_group_request))
                        .setContentText(notice.getLeaveMessage().equals("")?"申请加入":notice.getLeaveMessage())
                        .setContentIntent(contentIntent)
                        .setDefaults(Notification.DEFAULT_LIGHTS)
                        .setDefaults(Notification.FLAG_SHOW_LIGHTS)
                        .setAutoCancel(true)
                        .setVibrate(vibrate)//设置震动f
                        .setLights(0xff00ff00, 300, 1000)
                        .setColor(Color.parseColor("#243BAE"))
                        .setWhen(System.currentTimeMillis());
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher_alpha);
//        } else {
        mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher);
        //   }
        mNM.notify(1, mBuilder.build());

    }

    //// TODO: 2017/6/20  显示
    public static void showApplyPublicNotification(int publicId, Context
            mContext) {


        PendingIntent contentIntent = null;
        // String tickerTile = "关注应用号成功";

        User user = WeChatDBManager.getInstance().getOneOfficialNumber(publicId);
        String tickerTile = "您已成功关注" + user.getNickName() + "应用号";

        NotificationManager mNM = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

        Bitmap myBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.wechat_icon_launcher);

        long[] vibrate = {0, 100, 200, 300};
        //构建通知的Builder
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext, CHANNEL_ID_CONTACTS)
                .setLargeIcon(myBitmap)//大图标为头像
                .setTicker("新消息提示")
                //.setContentIntent(contentIntent)//设置Intent
                .setContentTitle(tickerTile)//设置标题，发送人或群聊名
                //.setNumber(34)//设置未读聊天数
                //  .setContentText("您已成功关注"+user.getNickName()+"")//正文为发送人+信息内容
                // .setDefaults(Notification.DEFAULT_LIGHTS)
                //.setDefaults(Notification.FLAG_SHOW_LIGHTS)
                .setAutoCancel(true)
                .setVibrate(vibrate)//设置震动
                .setLights(0xff00ff00, 300, 1000)
                .setColor(Color.parseColor("#243BAE"))//设置通知中显示的小图标的背景色
                .setWhen(System.currentTimeMillis());//设置时间
        /**
         * 5.0以上需要使用透明背景纯白的小图标
         * 5.0以下使用彩色图标
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher);
        } else {
            mBuilder.setSmallIcon(R.drawable.wechat_icon_launcher);
        }

        mBuilder.setAutoCancel(true);//设置点击后消失
        //显示通知，id和PendingIntent的requestCode一致
        mNM.notify(0, mBuilder.build());
    }

    private static int getUniqueCode(IMStruct002 imstruct002, int userId) {
        //requestCode用来标记PendingIntent，使用type+id，如0123
        return Integer.valueOf(userId + "" + imstruct002.getToUserType());
    }

    public static void createNotificationChannel(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            NotificationManager notificationManager = (NotificationManager)
                    context.getSystemService(Context.NOTIFICATION_SERVICE);

            //分组（可选）
            //groupId要唯一
//            NotificationChannelGroup group = new NotificationChannelGroup(NOTIFI_GROUP_ID_MAIN,
//                    ResStringUtil.getString(R.string.notification_group_main));
//
//            //创建group
//            notificationManager.createNotificationChannelGroup(group);

            NotificationChannel ontactsChannel = new NotificationChannel(CHANNEL_ID_CONTACTS,
                    ResStringUtil.getString(R.string.notification_channel_contacts),
                    NotificationManager.IMPORTANCE_HIGH);
            //补充channel的含义（可选）
           // ontactsChannel.setDescription(ResStringUtil.getString(R.string.notification_channel_contacts));
            //将渠道添加进组（先创建组才能添加）
            //ontactsChannel.setGroup(NOTIFI_GROUP_ID_MAIN);

            //后台服务运行的通知栏图标
            NotificationChannel lowImportanceChanel = new NotificationChannel(CHANNEL_ID_BACKGROUND_SERVICE,
                    ResStringUtil.getString(R.string.notification_channel_background_service),
                    NotificationManager.IMPORTANCE_LOW);
            List<NotificationChannel> channelList = new ArrayList<>();
            channelList.add(ontactsChannel);
            channelList.add(lowImportanceChanel);

            //创建channel
            notificationManager.createNotificationChannels(channelList);

//            NotificationChannel adChannel = new NotificationChannel(CHANNEL_ID_SUBSCRIBER,
//                    "公众号消息", NotificationManager.IMPORTANCE_DEFAULT);
//            //补充channel的含义（可选）
//            adChannel.setDescription("公众号消息");
//            //将渠道添加进组（先创建组才能添加）
//            adChannel.setGroup(NOTIFI_GROUP_ID_MAIN);
//            //创建channel
//            notificationManager.createNotificationChannel(adChannel);








// //           打开通知渠道设置
//            Intent channelIntent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
//            channelIntent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
//            channelIntent.putExtra(Settings.EXTRA_CHANNEL_ID,channelId);//渠道id必须是我们之前注册的
//            startActivity(channelIntent);

        }
    }
}
