package com.gingersoft.gsa.cloud.common.ui.widget.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.gingersoft.gsa.cloud.common.R;
import com.gingersoft.gsa.cloud.common.ui.adapter.MultipleChoiceAdapter;
import com.gingersoft.gsa.cloud.common.ui.view.WheelView;

import java.util.List;

/**
 * Created by Wyh on 2019/11/1.
 */
public abstract class DialogUtils implements LifecycleObserver {
    private static Dialog dialog;
    private View view;
    private int style = R.style.PhotoDialog;
    private ViewHepler viewHepler;

    public DialogUtils(Context mContext, int xmlLayout) {
        view = LayoutInflater.from(mContext).inflate(xmlLayout, null);
        init(mContext);
    }

    private void init(Context context) {
        dialog = new Dialog(context);
        viewHepler = getViewHepler(context);
        initLayout(viewHepler, dialog);
        dialog.setContentView(viewHepler.getContentView());

        Window dialogWindow = dialog.getWindow();
        if (dialogWindow != null) {
            setGravity(Gravity.CENTER);
            setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            //将对话框的大小按屏幕大小的百分比设置
            WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
            p.height = WindowManager.LayoutParams.WRAP_CONTENT;
            p.width = WindowManager.LayoutParams.WRAP_CONTENT;
            dialogWindow.setAttributes(p);
        }
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
    }

    public DialogUtils setWidth(int width) {
        if (dialog != null) {
            Window window = dialog.getWindow();
            if (window != null) {
                WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
                p.width = width;
                window.setAttributes(p);
            }
        }
        return this;
    }

    public DialogUtils setHeight(int height) {
        if (dialog != null) {
            Window window = dialog.getWindow();
            if (window != null) {
                WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
                p.height = height;
                window.setAttributes(p);
            }
        }
        return this;
    }

    public DialogUtils setBackgroundDrawable(Drawable drawable) {
        if (dialog != null) {
            Window window = dialog.getWindow();
            if (window != null) {
                window.setBackgroundDrawable(drawable);
                window.getDecorView().setBackgroundResource(android.R.color.transparent);
            }
        }
        return this;
    }

    public DialogUtils setBackgroundResource(int resid) {
        if (dialog != null) {
            Window window = dialog.getWindow();
            if (window != null) {
                window.getDecorView().setBackgroundResource(resid);
            }
        }
        return this;
    }


//    public DialogUtils createDialogView() {
//        Window dialogWindow = dialog.getWindow();
////        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//        dialogWindow.setGravity(Gravity.CENTER);
//        //将对话框的大小按屏幕大小的百分比设置
////        WindowManager m = activity.getWindowManager();
////        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
//        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
//        Window window = dialog.getWindow();
//        if (window != null) {
//            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//            window.getDecorView().setBackgroundResource(android.R.color.transparent);
//        }
//        p.height = mHeight;
//        p.width = mWidth;
//
//
////        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
////        DisplayMetrics metrics = new DisplayMetrics();
////        wm.getDefaultDisplay().getMetrics(metrics);
////
////        if (metrics.heightPixels < mMaxHeight) {
////            dialog.getWindow().setLayout(mWidth, mHeight);
////        } else {
////            dialog.getWindow().setLayout(mWidth, mMaxHeight);
////        }
//
//        dialogWindow.setAttributes(p);
////        android Activity改成dialog样式后 怎设置点击空白处关闭窗体，点击窗体以外的地方关闭窗体
//        dialog.setCanceledOnTouchOutside(true);
//        dialog.setCancelable(true);
////        dialog.show();
//        return this;
//    }


    public Dialog getDialog() {
        return dialog;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public DialogUtils dismiss() {
        if (dialog != null)
            dialog.dismiss();
        if (viewHepler != null) {
            viewHepler.clearAll();
        }
        dialog = null;
        return this;
    }

    public static void staticDismiss() {
        if (dialog != null)
            dialog.dismiss();
        dialog = null;
    }

    public DialogUtils setGravity(int gravity) {
        if (dialog != null && dialog.getWindow() != null) {
            dialog.getWindow().setGravity(gravity);
        }
        return this;
    }

    public DialogUtils show() {
        dialog.dismiss();
        dialog.show();
        return this;
    }

    public View getView() {
        if (viewHepler != null) {
            return viewHepler.getContentView();
        } else {
            return null;
        }
    }

    public boolean isShowing() {
        return dialog != null && dialog.isShowing();
    }

    public DialogUtils setOnDismissListener(DialogInterface.OnDismissListener dismissListener) {
        dialog.setOnDismissListener(dismissListener);
        return this;
    }

    public abstract void initLayout(ViewHepler hepler, Dialog dialog);

    private ViewHepler getViewHepler(Context context) {
        return ViewHepler.get(context, view);
    }


    public DialogUtils setCanceledOnTouchOutside(boolean cancel) {
        dialog.setCanceledOnTouchOutside(cancel);
        return this;
    }

    public static class ViewHepler {
        private final SparseArray<View> mViews;
        private View mConvertView;
        private static ViewHepler viewHepler = null;
        private Context context;

        private ViewHepler(Context context, int layoutId) {
            this.mViews = new SparseArray<>();
            this.context = context;
            mConvertView = LayoutInflater.from(context).inflate(layoutId, null);
        }

        private ViewHepler(Context context, View view) {
            this.mViews = new SparseArray<>();
            this.context = context;
            mConvertView = view;
        }

        public void clearAll() {
            context = null;
            if (mViews != null) {
                mViews.clear();
            }
            mConvertView = null;
            viewHepler = null;
        }

        public static ViewHepler get(Context context, int layoutId) {
            viewHepler = new ViewHepler(context, layoutId);
            return viewHepler;
        }

        public static ViewHepler get(Context context, View view) {
            viewHepler = new ViewHepler(context, view);
            return viewHepler;
        }

        public View getContentView() {
            return mConvertView;
        }


        /**
         * 通过控件的Id获取对于的控件，如果没有则加入views
         *
         * @param viewId
         * @return
         */
        public <T extends View> T getView(int viewId) {
            View view = mViews.get(viewId);
            if (view == null) {
                view = mConvertView.findViewById(viewId);
                mViews.put(viewId, view);
            }
            return (T) view;
        }

        public ViewHepler setAdapter(int viewId, RecyclerView.LayoutManager layoutManager, RecyclerView.Adapter adapter) {
            RecyclerView rv = getView(viewId);
            rv.setLayoutManager(layoutManager);
            rv.setAdapter(adapter);
            return this;
        }

        public ViewHepler setOnClickListenter(int viewId, View.OnClickListener onClickListener) {
            getView(viewId).setOnClickListener(onClickListener);
            return this;
        }


        /**
         * 为TextView设置字符串
         *
         * @param viewId
         * @param text
         * @return
         */
        public ViewHepler setText(int viewId, String text) {
            if (text == null) {
                text = "";
            }
            TextView view = getView(viewId);
            view.setText(text);
            return this;
        }

        /**
         * 为ImageView设置图片
         *
         * @param viewId
         * @param drawableId
         * @return
         */
        public ViewHepler setImageResource(int viewId, int drawableId) {
            ImageView view = getView(viewId);
            view.setImageResource(drawableId);

            return this;
        }

        /**
         * 为ImageView设置图片
         *
         * @param viewId
         * @param bm
         * @return
         */
        public ViewHepler setImageBitmap(int viewId, Bitmap bm) {
            ImageView view = getView(viewId);
            view.setImageBitmap(bm);
            return this;
        }

        /**
         * 为ImageView设置图片
         *
         * @param viewId         ImageView的id
         * @param url            圖片鏈接
         * @param roundedCorners 圖片圓角
         * @param defaultImg     默認圖
         * @return ViewHepler
         */
        public ViewHepler setImageByUrl(int viewId, String url, int roundedCorners, int defaultImg) {
            ImageView view = (ImageView) isHaveView(viewId);

            Glide.with(context).load(url)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .apply(RequestOptions.bitmapTransform(new RoundedCorners(roundedCorners)))
                    .error(defaultImg)
                    .fallback(defaultImg)
                    .placeholder(defaultImg)
                    .into(view);
            return this;
        }

        /**
         * 获取view，如果缓存中已存在，则直接取出来
         *
         * @param viewId
         * @return
         */
        private View isHaveView(int viewId) {
            ImageView view = (ImageView) mViews.get(viewId);
            if (view == null) {
                view = mConvertView.findViewById(viewId);
                mViews.put(viewId, view);
            }
            return view;
        }

        public ViewHepler setLayoutParams(int viewId, ViewGroup.LayoutParams params) {
            View view = isHaveView(viewId);
            view.setLayoutParams(params);
            return this;
        }

        private View.OnClickListener mListener;

        public void setViewClick(int viewId, final ViewClickCallBack callBack) {
            View view = mViews.get(viewId);
            if (view == null) {
                view = mConvertView.findViewById(viewId);
                mViews.put(viewId, view);
            }

            view.setOnClickListener(v -> callBack.doClickAction(v));
        }

        public static interface ViewClickCallBack {
            public void doClickAction(View v);
        }

    }

    public interface onPopupSureClickListener {
        void onClick(int select);
    }

    public static void showSelectPopop(Context context, List<String> items, String title, int defaultSelect, onPopupSureClickListener onClickListener) {
        new DialogUtils(context, R.layout.dialog_select_print_device) {
            @Override
            public void initLayout(ViewHepler hepler, Dialog dialog) {
                hepler.setText(R.id.tv_title, title);
                WheelView wheelView = hepler.getView(R.id.wv_model);
                wheelView.setSeletion(defaultSelect);
                wheelView.setItems(items);
                hepler.getView(R.id.btn_cancel).setOnClickListener(v -> dialog.dismiss());
                hepler.getView(R.id.btn_confirm).setOnClickListener(v -> {
                    dialog.dismiss();
                    if (onClickListener != null)
                        onClickListener.onClick(wheelView.getSeletedIndex());
                });
            }
        }
                .setWidth(WindowManager.LayoutParams.MATCH_PARENT)
                .setGravity(Gravity.BOTTOM)
                .show();
    }

    public interface onPopupMultipleChoiceSureClickListener {
        void onClick(String checkIndex);
    }

    public static void showMultipleChoicePopop(Context context, List<String> items, String title, List<Integer> defaultSelect, onPopupMultipleChoiceSureClickListener onClickListener) {
        new DialogUtils(context, R.layout.dialog_multiple_choice_layout) {
            @Override
            public void initLayout(ViewHepler hepler, Dialog dialog) {
                hepler.setText(R.id.tv_title, title);
                RecyclerView recyclerView = hepler.getView(R.id.rv_dialog_multiple_choice);
                MultipleChoiceAdapter adapter = new MultipleChoiceAdapter(items, defaultSelect);
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
                recyclerView.setAdapter(adapter);

                hepler.getView(R.id.btn_cancel).setOnClickListener(v -> dialog.dismiss());
                hepler.getView(R.id.btn_confirm).setOnClickListener(v -> {
                    dialog.dismiss();
                    if (onClickListener != null)
                        onClickListener.onClick(adapter.getChecked());
                });
            }
        }
                .setWidth(WindowManager.LayoutParams.MATCH_PARENT)
                .setGravity(Gravity.BOTTOM)
                .show();
    }
}
