package com.dahe.pass.utils;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dahe.mylibrary.R;
import com.dahe.mylibrary.adapter.GridImageAdapter;
import com.dahe.mylibrary.dialog.DialogPhotoSelect;
import com.dahe.mylibrary.net.CommonResponseBean;
import com.dahe.mylibrary.utils.ToastUtils;
import com.dahe.mylibrary.weight.FullyGridLayoutManager;
import com.dahe.mylibrary.weight.GlideEngine;
import com.dahe.pass.net.BaseObserver;
import com.dahe.pass.net.DataManager;
import com.dahe.pass.net.RxHttpCallBack;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.tools.ScreenUtils;

import java.lang.ref.WeakReference;
import java.util.List;

public class SelectPhotoUtils6 implements View.OnClickListener {
    private Activity ctx;
    private OnResultCallbackListener listener;
    private GridImageAdapter mAdapter;
    private Build build;

    private SelectPhotoUtils6(Build build, Activity ctx) {
        this.build = build;
        this.ctx = ctx;
        this.listener = build.listener;
        if (null == listener) {
            ToastUtils.showToast(ctx, "请初始化回调listener");
            return;
        }
        if (build.isSingle) {//单选
            if (null == build.imageView) {
                ToastUtils.showToast(ctx, "请初始化ImageView");
                return;
            }
            selectSimple(build.imageView);
        } else {//多选
            if (null == build.recyclerView || !(build.recyclerView instanceof RecyclerView)) {
                ToastUtils.showToast(ctx, "请初始化RecycleView");
                return;
            }
            selectMul(build.recyclerView);

        }
    }


    public static class Build {
        private int maxSelect;
        private boolean isSingle;
        private boolean isOnlyShow;
        private ImageView imageView;
        private RecyclerView recyclerView;
        private List<LocalMedia> pics;
        private OnResultCallbackListener listener;
        private String orderId;

        public Build maxSelect(int max) {
            this.maxSelect = max;
            return this;
        }

        public Build isSingle(boolean isSingle) {
            this.isSingle = isSingle;
            return this;
        }

        public Build isOnlyShow(boolean isOnlyShow) {
            this.isOnlyShow = isOnlyShow;
            return this;
        }

        public Build imageview(ImageView imageView) {
            this.imageView = imageView;
            return this;
        }

        public Build recycleview(RecyclerView recyclerView) {
            this.recyclerView = recyclerView;
            return this;
        }

        public Build newPics(List<LocalMedia> pics) {
            this.pics = pics;
            return this;
        }

        public Build resultListener(OnResultCallbackListener listener) {
            this.listener = listener;
            return this;
        }

        public Build orderId(String orderId) {
            this.orderId = orderId;
            return this;
        }

        public SelectPhotoUtils6 create(Activity ctx) {
            return new SelectPhotoUtils6(this, ctx);
        }
    }

    public GridImageAdapter getmAdapter() {
        return mAdapter;
    }


    public void selectSimple(ImageView imageView) {
        imageView.setOnClickListener(this);
    }


    public void selectMul(RecyclerView recyclerView) {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(ctx,
                4, GridLayoutManager.VERTICAL, false);

        recyclerView.addItemDecoration(new GridSpacingItemDecoration(40,
                ScreenUtils.dip2px(ctx, 8), true
        ));
        recyclerView.setLayoutManager(manager);
        mAdapter = new GridImageAdapter(ctx, onAddPicClickListener);
        mAdapter.setSelectMax(build.maxSelect);
        mAdapter.setIsOnlyShow(build.isOnlyShow);
        recyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener((v, position) -> {
            List<LocalMedia> selectList = mAdapter.getData();
            if (selectList.size() > 0) {
                LocalMedia media = selectList.get(position);
                String mimeType = media.getMimeType();
                int mediaType = PictureMimeType.getMimeType(mimeType);
                switch (mediaType) {
                    case PictureConfig.TYPE_VIDEO:
                        // 预览视频
                        PictureSelector.create(ctx)
                                .themeStyle(R.style.picture_default_style)
//                                .setPictureStyle(mPictureParameterStyle)// 动态自定义相册主题
                                .externalPictureVideo(TextUtils.isEmpty(media.getAndroidQToPath()) ? media.getPath() : media.getAndroidQToPath());
                        break;
                    case PictureConfig.TYPE_AUDIO:
                        // 预览音频
                        PictureSelector.create(ctx)
                                .externalPictureAudio(PictureMimeType.isContent(media.getPath()) ? media.getAndroidQToPath() : media.getPath());
                        break;
                    default:
                        // 预览图片 可自定长按保存路径
//                        PictureWindowAnimationStyle animationStyle = new PictureWindowAnimationStyle();
//                        animationStyle.activityPreviewEnterAnimation = R.anim.picture_anim_up_in;
//                        animationStyle.activityPreviewExitAnimation = R.anim.picture_anim_down_out;
                        PictureSelector.create(ctx)
                                .themeStyle(R.style.picture_default_style) // xml设置主题
//                                .setPictureStyle(mPictureParameterStyle)// 动态自定义相册主题
                                //.setPictureWindowAnimationStyle(animationStyle)// 自定义页面启动动画
                                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                                .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                                //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定义播放回调控制，用户可以使用自己的视频播放界面
                                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                                .openExternalPreview(position, selectList);
                        break;
                }
            }
        });
    }


    private final GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(ctx)
                    .openGallery(PictureMimeType.ofImage())
                    .imageEngine(GlideEngine.createGlideEngine())
                    .selectionMode(build.isSingle ? PictureConfig.SINGLE : PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .maxSelectNum(build.maxSelect)
                    .isPreviewImage(true)// 是否可预览图片 true or fals
                    .isGif(false)// 是否显示gif图片 true or false
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .isEnableCrop(false)// 是否裁剪 true or false
                    .selectionData(mAdapter.getData())// 是否传入已选图片
                    .isCompress(true)// 是否压缩 true or false
                    .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                    .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false
                    .cutOutQuality(30)// 裁剪压缩质量 默认90 int
                    .minimumCompressSize(30)// 小于100kb的图片不压缩
                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
//                .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                    .scaleEnabled(false)// 裁剪是否可放大缩小图片 true or false
                    .forResult(new MyResultCallback(mAdapter));
        }

        @Override
        public void onDelPicClick(int postion, LocalMedia localMedia) {
//            DataManager.getInstance().delBill(build.orderId,localMedia.getId() + "")
//                    .compose(DataManager.setThread())
//                    .subscribe(new BaseObserver(ctx, new RxHttpCallBack(ctx) {
//                        @Override
//                        public void onSuccess(CommonResponseBean t) {
//                            super.onSuccess(t);
////                            list.remove(index);
//                            mAdapter.getData().remove(postion);
//                            mAdapter.notifyItemRemoved(postion);
//                            mAdapter.notifyItemRangeChanged(postion, mAdapter.getData().size());
//                        }
//                    }));
        }
    };

    /**
     * 返回结果回调
     */
    private class MyResultCallback implements OnResultCallbackListener<LocalMedia> {
        private WeakReference<GridImageAdapter> mAdapterWeakReference;

        public MyResultCallback(GridImageAdapter adapter) {
            super();
            this.mAdapterWeakReference = new WeakReference<>(adapter);
        }

        @Override
        public void onResult(List<LocalMedia> result) {
//            for (LocalMedia media : result) {
//                Log.i(TAG, "是否压缩:" + media.isCompressed());
//                Log.i(TAG, "压缩:" + media.getCompressPath());
//                Log.i(TAG, "原图:" + media.getPath());
//                Log.i(TAG, "绝对路径:" + media.getRealPath());
//                Log.i(TAG, "是否裁剪:" + media.isCut());
//                Log.i(TAG, "裁剪:" + media.getCutPath());
//                Log.i(TAG, "是否开启原图:" + media.isOriginal());
//                Log.i(TAG, "原图路径:" + media.getOriginalPath());
//                Log.i(TAG, "Android Q 特有Path:" + media.getAndroidQToPath());
//                Log.i(TAG, "宽高: " + media.getWidth() + "x" + media.getHeight());
//                Log.i(TAG, "Size: " + media.getSize());
//
//                Log.i("MMM", "onResult: " + media.toString());
//                // TODO 可以通过PictureSelectorExternalUtils.getExifInterface();方法获取一些额外的资源信息，如旋转角度、经纬度等信息
//            }
            listener.onResult(result);
            if (mAdapterWeakReference.get() != null) {
                mAdapterWeakReference.get().setList(result);
                mAdapterWeakReference.get().notifyDataSetChanged();
            }
        }

        @Override
        public void onCancel() {
//            Log.i(TAG, "PictureSelector Cancel");
        }
    }


    /**
     * 相机拍照
     */
    private void doTakePhoto(Activity ctx) {
        PictureSelector.create(ctx)
                .openCamera(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())
                .isEnableCrop(false)// 是否裁剪 true or false
                .isCompress(true)// 是否压缩 true or false
                .isGif(false)// 是否显示gif图片 true or false
                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false
                .cutOutQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(30)// 小于100kb的图片不压缩
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .rotateEnabled(false) // 裁剪是否可旋转图片 true or false
                .scaleEnabled(false)// 裁剪是否可放大缩小图片 true or false
                .forResult(listener);
    }

    //从本地相册中选择
    private void doSelectPhoto(Activity ctx) {
        PictureSelector.create(ctx)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .isPreviewImage(true)// 是否可预览图片 true or fals
                .isGif(false)// 是否显示gif图片 true or false
                .isCamera(false)// 是否显示拍照按钮 true or false
                .isEnableCrop(false)// 是否裁剪 true or false
                .isCompress(true)// 是否压缩 true or false
                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false
                .cutOutQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(30)// 小于100kb的图片不压缩
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
//                .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                .scaleEnabled(false)// 裁剪是否可放大缩小图片 true or false
                .forResult(listener);
//                .forResult(PictureConfig.CHOOSE_REQUEST);
    }


    @Override
    public void onClick(View view) {
        DialogPhotoSelect dialogPhotoSelect = new DialogPhotoSelect(ctx);
        dialogPhotoSelect.show();
        dialogPhotoSelect.setOnSelectClickListener(new DialogPhotoSelect.onSelectClickListener() {
            @Override
            public void onTakePhoto() {
                doTakePhoto(ctx);
            }

            @Override
            public void onSelectPhoto() {
                doSelectPhoto(ctx);
            }
        });
    }
}
