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

import android.app.Dialog;
import android.content.Context;
import android.net.ParseException;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

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

import com.gingersoft.gsa.cloud.bean.R;
import com.gingersoft.gsa.cloud.bean.mvp.model.bean.FoodReason;
import com.gingersoft.gsa.cloud.bean.mvp.ui.adapter.FoodReasonAdapter;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
import com.qmuiteam.qmui.layout.QMUILinearLayout;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.QMUISlider;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import org.json.JSONException;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

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

    private static final String TAG = "CancelFoodDialog";

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

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

        setCanceledOnTouchOutside(true);
    }

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

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

    public static class Builder implements View.OnClickListener, QMUISlider.Callback {

        private Context mContext;
        private CancelFoodDialog mDialog;

        private int mRadius;
        private float mShadowAlpha = 0.25f;
        private int mShadowElevationDp = 14;

        private int spanCount = 3;
        /***
         * 可取消最大數
         */
        private int maxCancelNumber = 10;
        /**
         * 當前選擇的取消數
         */
        private int cancelNumber = 1;
        /**
         * 取消原因數據
         */
        private List<FoodReason.DataBean> mItems;
        private FoodReasonAdapter mAdapter;

        private QMUILinearLayout ll_container;
        private QMUITopBar mTopBar;
        private QMUIRoundButton btn_all_number;

        private QMUISlider slider_food_count;
        private TextView tv_number_value, tv_max_number, tv_min_number;

        private QMUIEmptyView mEmptyView;
        private ProgressBar progress;
        private RecyclerView recycle_cancel_info;

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

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

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

        public void setMaxCancelNumber(int maxCancelNumber) {
            this.maxCancelNumber = maxCancelNumber;
        }

        public void setCancelNumber(int cancelNumber) {
            this.cancelNumber = cancelNumber;
        }

        public int getCancelNumber() {
            return cancelNumber;
        }

        @Override
        public void onClick(View v) {
        }

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

        private View buildViews() {
            View view = View.inflate(mContext, getContentViewLayoutId(), null);
            mTopBar = view.findViewById(R.id.topbar);
            ll_container = view.findViewById(R.id.ll_container);
            tv_number_value = view.findViewById(R.id.tv_number_value);
            btn_all_number = view.findViewById(R.id.btn_all_number);
            slider_food_count = view.findViewById(R.id.slider_food_count);
            tv_max_number = view.findViewById(R.id.tv_max_number);
            tv_min_number = view.findViewById(R.id.tv_min_number);
            mEmptyView = view.findViewById(R.id.emptyView);
            progress = view.findViewById(R.id.progress);
            recycle_cancel_info = view.findViewById(R.id.recycle_cancel_info);

            //設置最大最小取消數
            tv_max_number.setText(String.valueOf(maxCancelNumber));
            tv_min_number.setText(String.valueOf(cancelNumber));
            //設置默認進度
            slider_food_count.setCurrentProgress(getCurrentProgress(cancelNumber));

            slider_food_count.setCallback(this);
            btn_all_number.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    slider_food_count.setCurrentProgress(100);
                }
            });
            ll_container.setRadiusAndShadow(mRadius, QMUIDisplayHelper.dp2px(mContext, mShadowElevationDp), mShadowAlpha);

            initTopbar();
            initCancelInfoRecycleView();
            return view;
        }

        public void initParmas() {
            cancelNumber = 1;
            tv_number_value.setText(String.valueOf(cancelNumber));
            slider_food_count.setCurrentProgress(getCurrentProgress(cancelNumber));
        }

        private void initTopbar() {
            mTopBar.setBackgroundColor(ContextCompat.getColor(mContext, R.color.theme_color));
            mTopBar.setTitle("取消原因");
        }

        private void initCancelInfoRecycleView() {
            if (mAdapter == null) {
                mAdapter = new FoodReasonAdapter(mItems);
            }
            mAdapter.setOnItemClickListener((adapter, view, position) -> {
                if (onClickListener != null)
                    onClickListener.onItemClick(mItems.get(position), position, getInputNumber());
            });
            recycle_cancel_info.setLayoutManager(createLayoutManager());
            recycle_cancel_info.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);
                }
            };
        }

        private int getCurrentProgress(int num) {
            if (maxCancelNumber == 0) {
                maxCancelNumber = 10;
            }
            int progress = num * 100 / maxCancelNumber;
            return progress;
        }

        private int getCancelNumberByProgress(int progress) {
            //這裡默認進度從1開始
            float number = (getCurrentProgress(1) + progress) * maxCancelNumber / 100;
            return Math.round(number);
        }

        public void setProgressVisibility(boolean show) {
            progress.setVisibility(show ? View.VISIBLE : View.INVISIBLE);
        }

        public void notifyDataSetChanged() {
            mEmptyView.hide();
            recycle_cancel_info.setVisibility(View.VISIBLE);
            mAdapter.notifyDataSetChanged();
        }

        private int getInputNumber() {
            return Integer.parseInt(tv_number_value.getText().toString());
        }

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

        @Override
        public void onProgressChange(QMUISlider slider, int progress, int tickCount, boolean fromUser) {
            if (progress == 0) {
                cancelNumber = 1;
                tv_number_value.setText(String.valueOf(cancelNumber));
            } else if (progress == 100) {
                cancelNumber = maxCancelNumber;
                tv_number_value.setText(String.valueOf(cancelNumber));
            } else {
                cancelNumber = getCancelNumberByProgress(progress);
                if (cancelNumber == 0)
                    cancelNumber = 1;
                tv_number_value.setText(String.valueOf(cancelNumber));
            }
        }

        @Override
        public void onTouchDown(QMUISlider slider, int progress, int tickCount, boolean hitThumb) {

        }

        @Override
        public void onTouchUp(QMUISlider slider, int progress, int tickCount) {

        }

        @Override
        public void onStartMoving(QMUISlider slider, int progress, int tickCount) {

        }

        @Override
        public void onStopMoving(QMUISlider slider, int progress, int tickCount) {

        }

        private View.OnClickListener onRetryClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //重新加載
                if (onClickListener != null) {
                    onClickListener.onRetryClick();
                }
            }
        };

        public Builder showEmptyView(boolean isSuccess, int size, Throwable t) {
            if (t != null) {
                if (t instanceof UnknownHostException) {
                    //沒有網絡
                    mEmptyView.show(false, mContext.getResources().getString(R.string.emptyView_mode_desc_fail_title), mContext.getResources().getString(R.string.emptyView_mode_desc_fail_desc), mContext.getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
                } else if (t instanceof SocketTimeoutException) {
                    //請求超時
                    mEmptyView.show(false, mContext.getResources().getString(R.string.emptyView_mode_desc_fail_title), mContext.getResources().getString(R.string.emptyView_mode_desc_fail_desc), mContext.getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
                } else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException || t instanceof JsonIOException) {
                    //數據解析錯誤
                    mEmptyView.show(false, mContext.getResources().getString(R.string.response_error_data_parsing_error), null, mContext.getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
                } else {
                    //其他error
                    mEmptyView.show(false, mContext.getResources().getString(R.string.emptyView_mode_desc_fail_title), null, mContext.getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
                }
                recycle_cancel_info.setVisibility(View.INVISIBLE);
                return this;
            }
            if (!isSuccess) {
                mEmptyView.show(false, mContext.getResources().getString(R.string.emptyView_mode_desc_fail_title), null, mContext.getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
                recycle_cancel_info.setVisibility(View.INVISIBLE);
                return this;
            }
            if (size == 0) {
                mEmptyView.show(mContext.getResources().getString(R.string.emptyView_mode_desc_double), null);
                recycle_cancel_info.setVisibility(View.INVISIBLE);
                return this;
            }
            mEmptyView.hide();
            recycle_cancel_info.setVisibility(View.VISIBLE);
            return this;
        }

        private OnClickListener onClickListener;

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

        public interface OnClickListener {

            void onItemClick(FoodReason.DataBean item, int position, int deleteNumber);

            void onRetryClick();
        }
    }

}
