package com.naz.sdkdemo.picselect;


import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;

import androidx.annotation.Nullable;


import com.naz.sdkdemo.R;
import com.naz.sdkdemo.utils.LogUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Date: 2020/8/17 上午12:30
 */
public class SPictureSelectView extends ViewGroup implements View.OnClickListener {
    private int itemWidth; //每一个的宽度
    private int itemHeight; //每一个高度
    private int iconClose;
    private int columns; //每一行显示多少个
    private int horizontalSpec;
    private int verticalSpec;
    private int maxItemCount;
    private int curItemCount = 0;
    private int realItemCount = 0;
    private List<Boolean> dataList = null;
    private SPictureSelector selector;
    private PictureItemView clickItem;
    private List<File> selectPictures;
    private OnPictureSelectListener selectListener;
    private SDialogHelper selectDialog;
    private Drawable cameraDrawable;
    private Drawable deleteDrawable;

    public SPictureSelectView(Context context) {
        super(context);
        initView(context, null);
    }

    public SPictureSelectView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    public SPictureSelectView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    public void setPictureSelectListener(OnPictureSelectListener listener) {
        this.selectListener = listener;
    }

    private void initView(Context context, @Nullable AttributeSet attrs) {
        if (attrs != null) {
            TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.SPictureSelectView, 0, 0);
            itemHeight = array.getDimensionPixelSize(R.styleable.SPictureSelectView_psvItemHeight, 0);
            itemWidth = array.getDimensionPixelSize(R.styleable.SPictureSelectView_psvItemWidth, 0);
            horizontalSpec = array.getDimensionPixelSize(R.styleable.SPictureSelectView_psvHorizontalSpec,
                    dp2px(context, 10));
            verticalSpec = array.getDimensionPixelSize(R.styleable.SPictureSelectView_psvVerticalSpec,
                    dp2px(context, 10));
            columns = array.getInteger(R.styleable.SPictureSelectView_psvColumns, 0);
            maxItemCount = array.getInteger(R.styleable.SPictureSelectView_psvMaxCount, 0);
            deleteDrawable = array.getDrawable(R.styleable.SPictureSelectView_psvDeleteIcon);
            cameraDrawable = array.getDrawable(R.styleable.SPictureSelectView_psvAddIcon);
            array.recycle();
        }
        if (null == cameraDrawable) {
            cameraDrawable = getResources().getDrawable(R.mipmap.icon_picselect_camera);
        }
        selectPictures = new ArrayList<>();
        selector = new SPictureSelector(context, SPictureSelector.RESULT_FILE);
        int size = dp2px(context, 80);
//        selector.setOutSize(size,size);
        selector.setTargetImageSize(800);
        selector.setCallback(new SPictureSelector.ResultCallbackAdapter() {

            @Override
            public void begin() {
                super.begin();
                if (null != clickItem) {
                    clickItem.showProgress(true);
                }
            }

            @Override
            public void result(boolean video, File file) {
                if (null != clickItem) {
                    LogUtils.E("添加成功");
                    selectPictureSuccess(file);
                    clickItem.showProgress(false);
                    clickItem.updateImage(file);
                }
            }
        });
        addEmptyView();
        dataList = new ArrayList<>();
        dataList.add(true);
    }

    private void addEmptyView() {
        curItemCount++;
        PictureItemView itemView = new PictureItemView(getContext());
        itemView.setOnClickListener(this);
        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        addView(itemView, lp);
        post(new Runnable() {
            @Override
            public void run() {
                requestLayout();
                invalidate();
            }
        });
    }

    private void selectPictureSuccess(File file) {
        realItemCount++;
        selectPictures.add(file);
        if (null != selectListener) {
            selectListener.onPictureSelect(selectPictures);
        }
        if (realItemCount < maxItemCount) {
            dataList.add(0, false);
            addEmptyView();
        } else {
            dataList.set(dataList.size() - 1, false);
        }
    }

    private void delete(File file) {
        curItemCount--;
        dataList.remove(0);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (maxItemCount <= 0 || columns <= 0) {
            setMeasuredDimension(0, 0);
            return;
        }
        LogUtils.E("onMeasure getclildcount=" + getChildCount() + ",curItemCount=" + curItemCount);
        int width = measureWidth(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec);
        setMeasuredDimension(width, height);
        PictureItemView itemView = null;
        LayoutParams lp = null;
        for (int i = 0; i < curItemCount; i++) {
            itemView = (PictureItemView) getChildAt(i);
            itemView.setTag(i);
            lp = itemView.getLayoutParams();
            if (lp == null) {
                lp = new LayoutParams(itemWidth, itemHeight);
            }
            lp.width = itemWidth;
            lp.height = itemHeight;
            itemView.setLayoutParams(lp);
            measureChild(itemView, itemWidth, itemHeight);
        }
    }

    private int measureWidth(int widthMeasureSpec) {
        int widthModel = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int width = 0;
        if (widthModel == MeasureSpec.EXACTLY) {
            width = widthSize;
        } else {
            width = getScreenWidth(getContext()) - getPaddingLeft() - getPaddingRight();
        }
        if (itemWidth == 0) {
            itemWidth = (width - horizontalSpec * (columns - 1)) / columns;
        }
        LogUtils.E("itemWidth=" + itemWidth + ",width=" + width + ",columns=" + columns + ",horizontalSpec=" + horizontalSpec);
        return width;
    }

    private int measureHeight(int heightMeasureSpec) {
        int heightModel = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int height = 0;
        int row = 1;
        if (heightModel == MeasureSpec.EXACTLY) {
            height = heightSize;
        } else {
            if (itemHeight == 0) {
                itemHeight = itemWidth;
            }
            row = curItemCount % columns > 0 ? curItemCount / columns + 1 : curItemCount / columns;
            height = row * itemHeight + (row - 1) * verticalSpec;
        }
        LogUtils.E("itemHeight=" + itemHeight + ",height=" + height + ",row=" + row + ",verticalSpec=" + verticalSpec);
        return height;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (curItemCount <= 0) {
            return;
        }
        PictureItemView itemView = null;
        int startX = getPaddingLeft(), startY = getPaddingTop();
        LogUtils.E("onlayout curItemCount=" + curItemCount);
        for (int i = 0; i < curItemCount; i++) {
            itemView = (PictureItemView) getChildAt(i);
            itemView.layout(startX, startY, startX + itemWidth, startY + itemHeight);
            LogUtils.E("onlayout i=" + i + ",startX=" + startX + ",starty=" + startY);
            if ((i + 1) % columns == 0) { //换行
                startX = getPaddingLeft();
                startY += itemHeight + verticalSpec;
            } else {
                startX += itemWidth + horizontalSpec;
            }
        }
    }

    /**
     * 如果返回类型为File，必须在Activity onRequestPermissionsResult中调用
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        if (null != selector) {
            selector.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (null != selector) {
            selector.onActivityResult(requestCode, resultCode, data);
        }
    }

    public void setMaxCount(int count) {
        maxItemCount = count;
    }

    @Override
    public void onClick(View v) {
        Object value = v.getTag();
        if (null == value || null == dataList || dataList.isEmpty()) {
            return;
        }
        int position = -1;
        if (value instanceof Integer) {
            position = Integer.parseInt(value+"");
        }
        if (position < 0 || position >= curItemCount) {
            return;
        }
        boolean addItem = dataList.get(position);
        if (null == selector) {
            return;
        }
        clickItem = (PictureItemView) getChildAt(position);
        if (addItem) {
            showSelectDialog();
        }
    }

    public void setCameraDrawable(Drawable cameraDrawable) {
        this.cameraDrawable = cameraDrawable;
    }

    public void setDeleteDrawable(Drawable deleteDrawable) {
        this.deleteDrawable = deleteDrawable;
    }

    private class PictureItemView extends FrameLayout {
        private ImageView imgPicture;
        private ImageView imgClose;
        private ImageView imgCamera;
        private ProgressBar progressBar;
        private File selectFile;
        private int state = 0; //0--空界面、1--加载中、2--设置完成

        public PictureItemView(Context context) {
            super(context);
            initView(context);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            LogUtils.E("tag=" + getTag() + "width=" + getMeasuredWidth() + ",height=" + getMeasuredHeight());
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            super.onLayout(changed, left, top, right, bottom);
            LogUtils.E("tag=" + getTag() + "onlayout changed=" + changed);
        }

        private void initView(Context context) {
            state = 0;
            FrameLayout container = new FrameLayout(context);

            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
            lp.topMargin = dp2px(context, 8);
            lp.rightMargin = dp2px(context, 8);
            addView(container, lp);

            imgPicture = new ImageView(context);
            imgPicture.setId(ViewGroup.generateViewId());
            imgPicture.setScaleType(ImageView.ScaleType.CENTER_CROP);
            lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            lp.gravity = Gravity.CENTER;
            //imgPicture.setImageResource(R.drawable.bg_frame_ffe6e6e6);
            container.addView(imgPicture, lp);

            imgCamera = new ImageView(context);
            lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.gravity = Gravity.CENTER;
            imgCamera.setImageDrawable(cameraDrawable);
            container.addView(imgCamera, lp);

            progressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleLarge);
            lp = new FrameLayout.LayoutParams(dp2px(context, 30), dp2px(context, 30));
            lp.gravity = Gravity.CENTER;
            progressBar.setVisibility(View.GONE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                ColorStateList stateList = ColorStateList.valueOf(Color.parseColor("#999999"));
                progressBar.setIndeterminateTintList(stateList);
                progressBar.setIndeterminateTintMode(PorterDuff.Mode.SRC_ATOP);
            }
            container.addView(progressBar, lp);

            imgClose = new ImageView(context);
            lp = new FrameLayout.LayoutParams(dp2px(context, 16), dp2px(context, 16));
            lp.gravity = Gravity.RIGHT | Gravity.TOP;
            imgClose.setImageDrawable(deleteDrawable);
            imgClose.setVisibility(View.INVISIBLE);
            imgClose.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (realItemCount == maxItemCount) {
                        imgClose.setVisibility(View.INVISIBLE);
                        imgCamera.setVisibility(View.VISIBLE);
                        imgPicture.setImageDrawable(null);
                        selectPictures.remove(selectFile);
                        if (null != selectPictures) {
                            selectListener.onPictureSelect(selectPictures);
                        }
                        dataList.set(dataList.size() - 1, true);
                    } else {
                        selectPictures.remove(selectFile);
                        dataList.remove(0);
                        if (null != selectPictures) {
                            selectListener.onPictureSelect(selectPictures);
                        }
                        ViewParent parent = PictureItemView.this.getParent();
                        if (parent instanceof ViewGroup) {
                            ((ViewGroup) parent).removeView(PictureItemView.this);
                        }
                        curItemCount--;
                    }
                    realItemCount--;
                    SPictureSelectView.this.requestLayout();
                }
            });
            addView(imgClose, lp);
        }

        private ImageView getImgPicture() {
            return imgPicture;
        }

        private void updateImage(File file) {
            selectFile = file;
            state = 2;
            if (null != imgPicture) {
                if (null != selectListener) {
                    selectListener.loadImage(Uri.fromFile(file), imgPicture);
                }
            }
            if (null != imgClose) {
                imgClose.setVisibility(View.VISIBLE);
            }
            if (null != imgCamera) {
                imgCamera.setVisibility(View.GONE);
            }
        }

        private void showProgress(boolean show) {
            if (show) {
                state = 1;
            }
            progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
            if (null != imgCamera) {
                imgCamera.setVisibility(View.GONE);
            }
        }

        public void setDefaultImage() {
            if (null != imgPicture) {
                imgCamera.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.icon_picselect_camera));
            }
        }
    }

    private void showSelectDialog() {
        if (null == selectDialog) {
            View rootView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_picture_select, null);
            rootView.findViewById(R.id.btn_camera).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != selector) {
                        selector.fromCamera();
                    }
                    selectDialog.dismiss();
                }
            });
            rootView.findViewById(R.id.btn_gallery).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != selector) {
                        selector.fromGallery();
                    }
                    selectDialog.dismiss();
                }
            });
            rootView.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectDialog.dismiss();
                }
            });
            selectDialog = SDialogHelper.newBuilder()
                    .setRootView(rootView)
                    .setDialogStyle(SDialogHelper.DIALOG_STYLE_BOTTOM)
                    .setContext(getContext())
                    .builder();
        }
        if (selectDialog.isShowing()) {
            return;
        }
        selectDialog.show();
    }

    public List<File> getSelectPictures() {
        return selectPictures;
    }

    public interface OnPictureSelectListener {
        void onPictureSelect(List<File> selectPictures);
        void loadImage(Uri url, ImageView view);
    }

    public static int dp2px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public static int getScreenWidth(Context context) {
        if (null == context) {
            return 0;
        }
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }
}
