package com.dahe.mylibrary.utils;

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

import androidx.fragment.app.Fragment;
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.glide.GlideEngine;
import com.dahe.mylibrary.weight.FullyGridLayoutManager;
import com.luck.picture.lib.PictureSelectorPreviewFragment;
import com.luck.picture.lib.basic.IBridgeViewLifecycle;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.InjectResourceSource;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.luck.picture.lib.interfaces.OnInjectActivityPreviewListener;
import com.luck.picture.lib.interfaces.OnInjectLayoutResourceListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.luck.picture.lib.utils.DensityUtil;

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

import me.jessyan.autosize.utils.ScreenUtils;

public class SelectPhotoUtils6 implements View.OnClickListener {
    private Activity ctx;
    private OnResultCallbackListener listener;
    private GridImageAdapter mAdapter;
    private Build build;
    private final List<LocalMedia> mData = new ArrayList<>();

    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;

        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 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,
                DensityUtil.dip2px(ctx, 8), true
        ));
        recyclerView.setLayoutManager(manager);
        mAdapter = new GridImageAdapter(ctx, mData);
        mAdapter.setSelectMax(build.maxSelect);
//        mAdapter.setIsOnlyShow(build.isOnlyShow);
        recyclerView.setAdapter(mAdapter);


        mAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                // 预览图片、视频、音频
                PictureSelector.create(ctx)
                        .openPreview()
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setSelectorUIStyle(new PictureSelectorStyle())
//                        .isAutoVideoPlay(cb_auto_video.isChecked())
//                        .isLoopAutoVideoPlay(cb_auto_video.isChecked())
//                        .isPreviewFullScreenMode(cb_preview_full.isChecked())
//                        .isVideoPauseResumePlay(cb_video_resume.isChecked())
//                        .setCustomLoadingListener(getCustomLoadingListener())
                        .isPreviewZoomEffect(true, recyclerView)
                        .setExternalPreviewEventListener(new MyExternalPreviewEventListener())
                        .setAttachViewLifecycle(new IBridgeViewLifecycle() {
                            @Override
                            public void onViewCreated(Fragment fragment, View view, Bundle savedInstanceState) {
//                                PictureSelectorPreviewFragment previewFragment = (PictureSelectorPreviewFragment) fragment;
//                                MediumBoldTextView tvShare = view.findViewById(R.id.tv_share);
//                                tvShare.setVisibility(View.VISIBLE)
//                                previewFragment.addAminViews(tvShare);
//                                ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) tvShare.getLayoutParams();
//                                layoutParams.topMargin = cb_preview_full.isChecked() ? DensityUtil.getStatusBarHeight(getContext()) : 0;
//                                tvShare.setOnClickListener(new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View v) {
//                                        PicturePreviewAdapter previewAdapter = previewFragment.getAdapter();
//                                        ViewPager2 viewPager2 = previewFragment.getViewPager2();
//                                        LocalMedia media = previewAdapter.getItem(viewPager2.getCurrentItem());
//                                        ToastUtils.showToast(fragment.getContext(), "自定义分享事件:" + viewPager2.getCurrentItem());
//                                    }
//                                });
                            }

                            @Override
                            public void onDestroy(Fragment fragment) {
//                                if (cb_preview_full.isChecked()) {
//                                    // 如果是全屏预览模式且是startFragmentPreview预览，回到自己的界面时需要恢复一下自己的沉浸式状态
//                                    // 以下提供2种解决方案:
//                                    // 1.通过ImmersiveManager.immersiveAboveAPI23重新设置一下沉浸式
//                                    int statusBarColor = ContextCompat.getColor(getContext(), R.color.ps_color_grey);
//                                    int navigationBarColor = ContextCompat.getColor(getContext(), R.color.ps_color_grey);
//                                    ImmersiveManager.immersiveAboveAPI23(MainActivity.this,
//                                            true, true,
//                                            statusBarColor, navigationBarColor, false);
//                                    // 2.让自己的titleBar的高度加上一个状态栏高度且内容PaddingTop下沉一个状态栏的高度
//                                }
                            }
                        })
                        .startActivityPreview(position, true, mAdapter.getData());
            }

            @Override
            public void openPicture() {

            }
        });


    }






    @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);
            }
        });
    }

    /**
     * 外部预览监听事件
     */
    private class MyExternalPreviewEventListener implements OnExternalPreviewEventListener {

        @Override
        public void onPreviewDelete(int position) {
            mAdapter.remove(position);
            mAdapter.notifyItemRemoved(position);
        }

        @Override
        public boolean onLongPressDownload(Context context, LocalMedia media) {
            return false;
        }
    }
}
