package com.cooleshow.student.helper;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;

import com.cooleshow.base.utils.FileUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.Utils;
import com.luck.picture.lib.tools.BitmapUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import io.rong.imkit.IMCenter;
import io.rong.imkit.picture.tools.PictureFileUtils;
import io.rong.imkit.utils.helper.OpenChatHelper;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.ImageMessage;

/**
 * Author by pq, Date on 2022/5/31.
 */
public class ShareHelper {

    public static void saveImg(Context context, String base64, ResultCallBack resultCallBack) {
        Observable.create(new ObservableOnSubscribe<File>() {
            @Override
            public void subscribe(ObservableEmitter<File> emitter) throws Exception {
                File file = saveImgToLocalFile(base64);
                emitter.onNext(file);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<File>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(File file) {
                        if (context != null) {
                            try {
                                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                                        file.getAbsolutePath(), file.getName(), null);
                                // 最后通知图库更新
                                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                        Uri.fromFile(new File(file.getPath()))));
                                if (resultCallBack != null) {
                                    resultCallBack.onResult(true);
                                }
                            } catch (FileNotFoundException e) {
                                ToastUtil.getInstance().show(context, "保存失败");
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (resultCallBack != null) {
                            resultCallBack.onResult(false);
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public static void saveImg(Context context, Bitmap bitmap, ResultCallBack resultCallBack) {
        Observable.create(new ObservableOnSubscribe<File>() {
            @Override
            public void subscribe(ObservableEmitter<File> emitter) throws Exception {
                File file = saveImageToGallery(bitmap);
                emitter.onNext(file);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<File>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(File file) {
                        if (context != null) {
                            try {
                                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                                        file.getAbsolutePath(), file.getName(), null);
                                // 最后通知图库更新
                                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                        Uri.fromFile(new File(file.getPath()))));
                                if (resultCallBack != null) {
                                    resultCallBack.onResult(true);
                                }
                            } catch (FileNotFoundException e) {
                                ToastUtil.getInstance().show(context, "保存失败");
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (resultCallBack != null) {
                            resultCallBack.onResult(false);
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public static void shareImgToChatGroup(String base64, String targetId, Conversation.ConversationType conversationType, ResultCallBack resultCallBack) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                File file = saveImgToLocalFile(base64);
                Message imageMessage = createImageMessage(file, targetId, conversationType);
                IMCenter.getInstance().sendMediaMessage(imageMessage, null, null, new IRongCallback.ISendMediaMessageCallback() {
                    @Override
                    public void onProgress(Message message, int progress) {

                    }

                    @Override
                    public void onCanceled(Message message) {

                    }

                    @Override
                    public void onAttached(Message message) {

                    }

                    @Override
                    public void onSuccess(Message message) {
                        Log.i("pq", "message send success");
                        if (resultCallBack != null) {
                            resultCallBack.onResult(true);
                        }
                    }

                    @Override
                    public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                        Log.i("pq", "message send onError:" + errorCode);
                        if (resultCallBack != null) {
                            resultCallBack.onResult(false);
                        }
                    }
                });
                emitter.onNext("");
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        if (resultCallBack != null) {
                            resultCallBack.onResult(true);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (resultCallBack != null) {
                            resultCallBack.onResult(false);
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public static void shareImgToChatGroup(File file, String targetId, Conversation.ConversationType conversationType, ResultCallBack resultCallBack) {
        if (file == null || !file.exists()) {
            if (resultCallBack != null) {
                resultCallBack.onResult(false);
            }
            return;
        }
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                Message imageMessage = createImageMessage(file, targetId, conversationType);
                IMCenter.getInstance().sendMediaMessage(imageMessage, null, null, new IRongCallback.ISendMediaMessageCallback() {
                    @Override
                    public void onProgress(Message message, int progress) {

                    }

                    @Override
                    public void onCanceled(Message message) {

                    }

                    @Override
                    public void onAttached(Message message) {

                    }

                    @Override
                    public void onSuccess(Message message) {
                        Log.i("pq", "message send success");
                        if (resultCallBack != null) {
                            resultCallBack.onResult(true);
                        }
                    }

                    @Override
                    public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                        Log.i("pq", "message send onError:" + errorCode);
                        if (resultCallBack != null) {
                            resultCallBack.onResult(false);
                        }
                    }
                });
                emitter.onNext("");
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        if (resultCallBack != null) {
                            resultCallBack.onResult(true);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (resultCallBack != null) {
                            resultCallBack.onResult(false);
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private static Message createImageMessage(String base64, Conversation conversation) {
        ImageMessage imageMessage = ImageMessage.obtain();
        imageMessage.setBase64(base64);
        Message message = new Message();
        message.setTargetId(conversation.getTargetId());
        message.setContent(imageMessage);
        message.setConversationType(conversation.getConversationType());
        return message;
    }

    private static File saveImgToLocalFile(String base64) {
        byte[] bytes;
        if (base64.startsWith("data:image/png;base64")) {
            String[] split = base64.split(",");
            bytes = Base64.decode(split[1], Base64.DEFAULT);
        } else {
            bytes = Base64.decode(base64, Base64.DEFAULT);
        }
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        File file = saveImageToGallery(bitmap);
        return new File(file.getAbsolutePath());
    }

    private static Message createImageMessage(File file, String targetId, Conversation.ConversationType conversationType) {
        Uri uri = Uri.fromFile(file);
        ImageMessage imageMessage = ImageMessage.obtain(uri, uri, true);
        Message message = new Message();
        message.setTargetId(targetId);
        message.setContent(imageMessage);
        message.setConversationType(conversationType);
        return message;
    }

    public interface ResultCallBack {
        void onResult(boolean isSuccess);
    }

    public static void parseShareContactData(String base64, Intent data) {
        String targetId = data.getStringExtra("targetId");
        int conversationValue = data.getIntExtra("conversation", -1);
        if (!TextUtils.isEmpty(base64)) {
            Conversation.ConversationType conversationType = OpenChatHelper.getConversationType(conversationValue);
            shareImgToChatGroup(base64, targetId, conversationType, new ShareHelper.ResultCallBack() {
                @Override
                public void onResult(boolean isSuccess) {
                    if (isSuccess) {
                        ToastUtil.getInstance().showShort("分享成功");
                    } else {
                        ToastUtil.getInstance().showShort("分享失败");
                    }
//                    sendCallBack("shareAchievements", "", true);
                }
            });
        }
    }

    public static void parseShareContactData(File file, Intent data) {
        String targetId = data.getStringExtra("targetId");
        int conversationValue = data.getIntExtra("conversation", -1);
        if (file != null) {
            Conversation.ConversationType conversationType = OpenChatHelper.getConversationType(conversationValue);
            shareImgToChatGroup(file, targetId, conversationType, new ShareHelper.ResultCallBack() {
                @Override
                public void onResult(boolean isSuccess) {
                    if (isSuccess) {
                        ToastUtil.getInstance().showShort("分享成功");
                    } else {
                        ToastUtil.getInstance().showShort("分享失败");
                    }
//                    sendCallBack("shareAchievements", "", true);
                }
            });
        }
    }


    public static Bitmap createBitmapByView(View view) {
        //这种方式只适用于view正在显示的
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }


    public static File saveImageToGallery(Bitmap bitmap) {
        File parentFile = new File(FileUtils.getCacheDir(Utils.getApp()) + File.separator + "share");
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        String targetFileName = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date()) + ".png";
        File file = new File(parentFile, targetFileName);
        FileUtils.saveImageToGallery(bitmap, file.getAbsolutePath());
        return file;
    }
}
