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

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;

import com.gingersoft.gsa.cloud.base.R;
import com.gingersoft.gsa.cloud.ui.adapter.BasTextSectiontAdapter;
import com.gingersoft.gsa.cloud.ui.bean.mode.LoginBean;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionHeader;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem;
import com.qmuiteam.qmui.QMUILog;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.section.QMUISection;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionAdapter;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2019-12-10
 * 修订历史：2019-12-10
 * 描述：
 */
public class ChooseRestaurantDialog extends Dialog {

    private static final String TAG = "ChooseRestaurantDialog";

    // 动画时长
    private final static int mAnimationDuration = 300;
    // 持有 ContentView，为了做动画
    private View mContentView;
    private boolean mIsAnimating = false;

    private OnBottomSheetShowListener mOnBottomSheetShowListener;

    public ChooseRestaurantDialog(Context context) {
        super(context, R.style.QMUI_BottomSheet);
    }

    public void setOnBottomSheetShowListener(OnBottomSheetShowListener onBottomSheetShowListener) {
        mOnBottomSheetShowListener = onBottomSheetShowListener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //noinspection ConstantConditions
        getWindow().getDecorView().setPadding(0, 0, 0, 0);

        // 在底部，宽度撑满
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.BOTTOM | Gravity.CENTER;

        int screenWidth = QMUIDisplayHelper.getScreenWidth(getContext());
        int screenHeight = QMUIDisplayHelper.getScreenHeight(getContext());
        params.width = screenWidth < screenHeight ? screenWidth : screenHeight;
        getWindow().setAttributes(params);
        setCanceledOnTouchOutside(true);
    }

    @Override
    public void setContentView(int layoutResID) {
        mContentView = LayoutInflater.from(getContext()).inflate(layoutResID, null);
        super.setContentView(mContentView);
    }

    @Override
    public void setContentView(@NonNull View view, ViewGroup.LayoutParams params) {
        mContentView = view;
        super.setContentView(view, params);
    }

    public View getContentView() {
        return mContentView;
    }

    @Override
    public void setContentView(@NonNull View view) {
        mContentView = view;
        super.setContentView(view);
    }

    /**
     * BottomSheet升起动画
     */
    private void animateUp() {
        if (mContentView == null) {
            return;
        }
        TranslateAnimation translate = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f
        );
        AlphaAnimation alpha = new AlphaAnimation(0, 1);
        AnimationSet set = new AnimationSet(true);
        set.addAnimation(translate);
        set.addAnimation(alpha);
        set.setInterpolator(new DecelerateInterpolator());
        set.setDuration(mAnimationDuration);
        set.setFillAfter(true);
        mContentView.startAnimation(set);
    }

    /**
     * BottomSheet降下动画
     */
    private void animateDown() {
        if (mContentView == null) {
            return;
        }
        TranslateAnimation translate = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1f
        );
        AlphaAnimation alpha = new AlphaAnimation(1, 0);
        AnimationSet set = new AnimationSet(true);
        set.addAnimation(translate);
        set.addAnimation(alpha);
        set.setInterpolator(new DecelerateInterpolator());
        set.setDuration(mAnimationDuration);
        set.setFillAfter(true);
        set.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mIsAnimating = true;
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mIsAnimating = false;
                /**
                 * Bugfix： Attempting to destroy the window while drawing!
                 */
                mContentView.post(new Runnable() {
                    @Override
                    public void run() {
                        // java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{22dbf5b V.E...... R......D 0,0-1080,1083} not attached to window manager
                        // 在dismiss的时候可能已经detach了，简单try-catch一下
                        try {
                            ChooseRestaurantDialog.super.dismiss();
                        } catch (Exception e) {
                            QMUILog.w(TAG, "dismiss error\n" + Log.getStackTraceString(e));
                        }
                    }
                });
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mContentView.startAnimation(set);
    }

    @Override
    public void show() {
        super.show();
        animateUp();
        if (mOnBottomSheetShowListener != null) {
            mOnBottomSheetShowListener.onShow();
        }
    }

    @Override
    public void dismiss() {
        if (mIsAnimating) {
            return;
        }
        animateDown();
    }

    public interface OnBottomSheetShowListener {
        void onShow();
    }

    /**
     * 生成宫格类型的 {@link QMUIBottomSheet} 对话框。
     */
    public static class BottomListSheetBuilder implements View.OnClickListener {

        private Context mContext;
        private ChooseRestaurantDialog mDialog;
        private List<LoginBean.DataBean.UserBean.BrandsBean> mItems;
        private List<QMUISection<SectionHeader, SectionTextItem>> mQmuiSections;
        private BasTextSectiontAdapter mAdapter;

        private QMUITopBar mTopBar;
        private QMUIStickySectionLayout mSectionLayout;
        private RecyclerView.LayoutManager mLayoutManager;

        public BottomListSheetBuilder(Context context) {
            mContext = context;
            mItems = new ArrayList<>();
        }

        public BottomListSheetBuilder addBrandItem(LoginBean.DataBean.UserBean.BrandsBean brandBean) {
            mItems.add(brandBean);
            return this;
        }

        public BottomListSheetBuilder addBrandItems(List<LoginBean.DataBean.UserBean.BrandsBean> brandsBean) {
            mItems.addAll(brandsBean);
            return this;
        }

        @Override
        public void onClick(View v) {
        }

        public ChooseRestaurantDialog build() {
            mDialog = new ChooseRestaurantDialog(mContext);
            View contentView = buildViews();
            mDialog.setContentView(contentView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, QMUIDisplayHelper.getScreenHeight(mContext)));
            return mDialog;
        }

        private View buildViews() {
            View view = View.inflate(mContext, getContentViewLayoutId(), null);
            mSectionLayout = view.findViewById(R.id.section_layout);
            mTopBar = view.findViewById(R.id.topbar);

            initTopbar();
            initStickyLayout();
            return view;
        }

        private void initTopbar() {
            mTopBar.setBackgroundColor(ContextCompat.getColor(mContext, R.color.theme_color));
            mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    mDialog.dismiss();
                }
            });
            mTopBar.setTitle("選擇餐廳");
        }

        private void initStickyLayout() {
            mLayoutManager = createLayoutManager();
            mSectionLayout.setLayoutManager(mLayoutManager);
            mAdapter = new BasTextSectiontAdapter();
            mAdapter.setCallback(new QMUIStickySectionAdapter.Callback<SectionHeader, SectionTextItem>() {

                @Override
                public void loadMore(QMUISection<SectionHeader, SectionTextItem> section, boolean loadMoreBefore) {

                }

                @Override
                public void onItemClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {
                    if (holder instanceof BasTextSectiontAdapter.ViewHolder) {
                        BasTextSectiontAdapter.ViewHolder viewHolder = (BasTextSectiontAdapter.ViewHolder) holder;
                        if (viewHolder.getTvName().getText() != null) {
                            SectionTextItem item = viewHolder.getSectionTextItem(position);
                            if (mOnItemClickListener != null) {
                                mOnItemClickListener.onItemClick(mDialog,item, position);
                            }
                        }
                    } else {
                        //點擊的頭部，折疊
                    }
                }

                @Override
                public boolean onItemLongClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {
                    return false;
                }
            });

            mSectionLayout.setAdapter(mAdapter, true);

            mQmuiSections = restaurantsTransformToSection(mItems);
            mAdapter.setData(mQmuiSections);
        }

        private List<QMUISection<SectionHeader, SectionTextItem>> restaurantsTransformToSection(List<LoginBean.DataBean.UserBean.BrandsBean> mItems) {
            List<QMUISection<SectionHeader, SectionTextItem>> qmuiSections = new ArrayList<>();
            for (int i = 0; i < mItems.size(); i++) {
                LoginBean.DataBean.UserBean.BrandsBean brandsBean = mItems.get(i);
                qmuiSections.add(createSection(brandsBean));
            }
            return qmuiSections;
        }

        private QMUISection<SectionHeader, SectionTextItem> createSection(LoginBean.DataBean.UserBean.BrandsBean brandsBean) {
            SectionHeader header = new SectionHeader(brandsBean.getBrandName());
            ArrayList<SectionTextItem> contents = new ArrayList<>();
            for (int i = 0; i < Objects.requireNonNull(brandsBean.getRestaurants().size()); i++) {
                contents.add(new SectionTextItem(brandsBean.getRestaurants().get(i).getRestaurantId(), Objects.requireNonNull(brandsBean.getRestaurants().get(i).getRestaurantName())));
            }
            return new QMUISection<>(header, contents, false);
        }

        private RecyclerView.LayoutManager createLayoutManager() {
            return new LinearLayoutManager(mContext) {
                @Override
                public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                    return new RecyclerView.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                }
            };
        }

        protected int getContentViewLayoutId() {
            return R.layout.ui_dialog_choose_restaurant;
        }

        private OnItemClickListener mOnItemClickListener;

        public BottomListSheetBuilder setOnItemClickListener(OnItemClickListener onItemClickListener) {
            mOnItemClickListener = onItemClickListener;
            return this;
        }

        public interface OnItemClickListener {

            void onItemClick(ChooseRestaurantDialog dialog,SectionTextItem item, int position);

        }
    }

}
