package com.gingersoft.gsa.cloud.table.mvp.ui.widget;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerTabStrip;
import androidx.viewpager.widget.ViewPager;

import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.DiscountAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.InputTableFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.RegionFragment;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration;
import com.jess.arms.utils.ThirdViewUtil;
import com.qmuiteam.qmui.arch.QMUIFragmentPagerAdapter;
import com.qmuiteam.qmui.layout.QMUILinearLayout;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.tab.QMUITab;
import com.qmuiteam.qmui.widget.tab.QMUITabBuilder;
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;
import com.qmuiteam.qmui.widget.tab.QMUITabView;

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

import butterknife.BindView;
import butterknife.Unbinder;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2020-03-28
 * 修订历史：2020-03-28
 * 描述：
 */
public class DiscountDialog extends Dialog {

    private static final String TAG = "DiscountDialog";

    public DiscountDialog(@NonNull Context context) {
        super(context, R.style.MyDialogTheme2);
    }

    @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 show() {
        super.show();
    }

    @Override
    public void dismiss() {
        super.dismiss();
    }

    public static class Builder implements View.OnClickListener {

//        @BindView(R2.id.topbar)
//        QMUITopBar topbar;
//        @BindView(R2.id.recycler_discount)
//        RecyclerView recyclerDiscount;
//        @BindView(R2.id.tv_pager_indicator)
//        PagerTabStrip tvPagerIndicator;
//        @BindView(R2.id.ll_container)
//        QMUILinearLayout llContainer;
        
        @BindView(R2.id.topbar)
        QMUITopBar topbar;
        @BindView(R2.id.tabSegment)
        QMUITabSegment tabSegment;
        @BindView(R2.id.contentViewPager)
        ViewPager contentViewPager;
        @BindView(R2.id.ll_container)
        QMUILinearLayout llContainer;

        private FragmentActivity mContext;
        private DiscountDialog mDialog;

        private int spanCount = 3;

        private int mRadius;
        private float mShadowAlpha = 0.25f;
        private int mShadowElevationDp = 14;
        private int mBagcolor;
        private boolean canScan = false;

        private List<Discount> mItems;
        private DiscountAdapter mAdapter;
        private Unbinder mUnbinder;

        private String[] mTabTitles = {"折扣", "優惠券"};

        private int mCurrentPageIndex = 0;
        
//        private QMUITopBar topbar;
//        private QMUILinearLayout llContainer;
//        private RecyclerView recyclerDiscount;

        public Builder(FragmentActivity context) {
            mContext = context;
            mItems = new ArrayList<>();
            mRadius = QMUIDisplayHelper.dp2px(mContext, 8);
        }

        public void addItem(Discount item) {
            mItems.add(item);
        }

        public void addItems(List<Discount> items) {
            if (mItems.size() > 0) {
                mItems.clear();
            }
            mItems.addAll(items);
        }

        public void setCanScan(boolean canScan) {
            this.canScan = canScan;
        }

        @Override
        public void onClick(View v) {
        }

        public DiscountDialog build() {
            if (mDialog != null) {
                return mDialog;
            }
            mDialog = new DiscountDialog(mContext);
            View contentView = buildViews();
            mDialog.setContentView(contentView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,(int) (QMUIDisplayHelper.getScreenHeight(mContext) * 0.65)));
            return mDialog;
        }

        private View buildViews() {
            View view = View.inflate(mContext, getContentViewLayoutId(), null);
            ThirdViewUtil.bindTarget(this, view);
            topbar = view.findViewById(R.id.topbar);
//            recyclerDiscount = view.findViewById(R.id.recycler_discount);
            llContainer = view.findViewById(R.id.ll_container);
//            ll_container.setRadiusAndShadow(mRadius, QMUIDisplayHelper.dp2px(mContext, mShadowElevationDp), mShadowAlpha);

            initTopbar();
            initTabAndPager();
            initDiscountRecycleView();
            return view;
        }

        private void initTabAndPager() {
            QMUIFragmentPagerAdapter pagerAdapter = new QMUIFragmentPagerAdapter(mContext.getSupportFragmentManager()) {
                @Override
                public Fragment createFragment(int position) {
                    Bundle bundle = new Bundle();
//                    switch (position) {
//                        case 1:
//                            if (allTableFragment != null) {
//                                return allTableFragment;
//                            }
//                            allTableFragment = RegionFragment.newInstance();
//                            bundle.putInt("currentPageIndex", FUNCTION_ALL_TABLE);
//                            allTableFragment.setArguments(bundle);
//                            return allTableFragment;
//                        default:
//                            if (inputTableFragment != null) {
//                                return inputTableFragment;
//                            }
//                            inputTableFragment = InputTableFragment.newInstance();
//                            return inputTableFragment;
//                    }
                    return null;
                }

                @Override
                public int getCount() {
                    return mTabTitles.length;
                }

                @Override
                public CharSequence getPageTitle(int position) {
                    return "";
                }
            };
            QMUITabBuilder builder = tabSegment.tabBuilder();
            QMUITab tab1 = builder
                    .setText(mTabTitles[0])
                    .build(mContext);
            QMUITab tab2 = builder
                    .setText(mTabTitles[1])
                    .build(mContext);
            tabSegment
                    .addTab(tab1)
                    .addTab(tab2);

            contentViewPager.setAdapter(pagerAdapter);
            contentViewPager.setCurrentItem(mCurrentPageIndex);
            int space = QMUIDisplayHelper.dp2px(mContext, 16);
            tabSegment.setIndicator(new QMUITabIndicator(QMUIDisplayHelper.dp2px(mContext, 2), false, true));
            tabSegment.setDefaultTextSize(QMUIDisplayHelper.dp2px(mContext, 16), QMUIDisplayHelper.dp2px(mContext, 16));
            tabSegment.setPadding(space, 0, space, 0);
            tabSegment.setupWithViewPager(contentViewPager, false);
            tabSegment.addOnTabSelectedListener(new QMUITabSegment.OnTabSelectedListener() {

                @Override
                public void onTabSelected(int index) {
                    LoganManager.w_tableMode(TAG, "當前頁面【" + mTabTitles[index] + "】");
                }

                @Override
                public void onTabUnselected(int index) {
                }

                @Override
                public void onTabReselected(int index) {
                }

                @Override
                public void onDoubleTap(int index) {
                }
            });
        }

        private void initTopbar() {
            if (mBagcolor != 0) {
                topbar.setBackgroundColor(mBagcolor);
            } else {
                topbar.setBackgroundColor(ContextCompat.getColor(mContext, R.color.theme_color));
            }
            if (canScan) {
                topbar.addRightImageButton(R.mipmap.table_white_scan, R.id.topbar_right_change_button)
                        .setOnClickListener(v -> {
                            if (onClickListener != null) {
                                onClickListener.onScan();
                            }
                        });
            }
            topbar.setTitle("折扣");
        }

        private void initDiscountRecycleView() {
            if (mAdapter == null) {
                mAdapter = new DiscountAdapter(mContext, mItems);
            }
            mAdapter.setOnItemClickListener((view, viewType, data, position) -> {
                if (onClickListener != null) {
                    onClickListener.onItemClick((Discount) data, position);
                }
                closeDialog();
            });
//            recyclerDiscount.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.HORIZONTAL_LIST));
//            recyclerDiscount.setLayoutManager(createLayoutManager());
//            recyclerDiscount.setItemAnimator(new DefaultItemAnimator());
//            recyclerDiscount.setAdapter(mAdapter);
        }

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

        public void closeDialog() {
            mDialog.dismiss();
        }

        public void setTopBarBagcolor(int mBagcolor) {
            this.mBagcolor = mBagcolor;
        }

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


        private OnClickListener onClickListener;

        public void setOnClickListener(OnClickListener onClickListener) {
            this.onClickListener = onClickListener;
        }

        public interface OnClickListener {

            void onItemClick(Discount item, int position);

            void onScan();

        }
    }

}
