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

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.core.table.TableManagerItem;
import com.gingersoft.gsa.cloud.common.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.ui.view.TriangleLabelView;
import com.jess.arms.base.BaseHolder;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaRelativeLayout;
import com.qmuiteam.qmui.layout.QMUIRelativeLayout;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;

import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2018/8/31
 * 修订历史：2018/8/31
 * 描述：
 */

public class TableAdapter extends DefaultAdapter<TableBean.DataBean> {

    private Context mContext;

    //当前功能（1：所有餐台、2：餐台带状态）
    private int mFunction;

    //Item行数（行数根据数据自动计算）
    private int ItemRowCount = 6;
    //Item高度
    private int ItemColHeight;

    //展示的布局高度
    private float mDiaplayScreenHeight;

    private int style;

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

    /**
     * 1=餐檯页
     * 2=分檯页
     */
    private int formType = 1;

    public TableAdapter(Context context, List<TableBean.DataBean> infos, float diaplayScreenHeight, int function) {
        super(infos);
        this.mContext = context;
        this.mFunction = function;
        this.mDiaplayScreenHeight = diaplayScreenHeight;
        this.mRadius = QMUIDisplayHelper.dp2px(context, 5);

        initItemDispalyHeight();
    }

    public void initItemDispalyHeight() {
        float screenHeight = mDiaplayScreenHeight - 75 - 75;
        ItemColHeight = (int) Math.ceil((double) screenHeight / (double) (ItemRowCount));
        ItemColHeight = ItemColHeight - 3;
    }

    @Override
    public int getItemCount() {
        return mInfos.size();
    }

    @Override
    public BaseHolder<TableBean.DataBean> getHolder(View v, int viewType) {
        return new TableItemHolder(v);
    }

    @Override
    public int getLayoutId(int viewType) {
        return R.layout.table_recycler_table;
    }

    class TableItemHolder extends BaseHolder<TableBean.DataBean> {

        @BindView(R2.id.ll_container)
        QMUIRelativeLayout ll_container;
        @BindView(R2.id.rl_table)
        QMUIAlphaRelativeLayout rl_table;
        @BindView(R2.id.btn_table)
        TextView btn_table;
        @BindView(R2.id.tv_people)
        TextView tv_people;
        @BindView(R2.id.tv_service_fee)
        TextView tv_service_fee;
        @BindView(R2.id.tv_open_duration)
        TextView tv_open_duration;
        @BindView(R2.id.iv_vip)
        TriangleLabelView iv_vip;
        @BindView(R2.id.tv_scan_flag)
        TextView tv_scan_flag;
        @BindView(R2.id.fl_table_type)
        FrameLayout fl_table_type;
        @BindView(R2.id.tlv_table_type)
        TriangleLabelView tlv_table_type;
        @BindView(R2.id.tv_type_labe)
        TextView tv_type_labe;

        public TableItemHolder(View itemView) {
            super(itemView);
        }

        @Override
        public void setData(TableBean.DataBean item, int position) {

            initItemData(item);
            initItemDispalyMetrics();
            initItemTableClick(item, position);
            initTableBackground(item);

            ll_container.setRadiusAndShadow(mRadius, QMUIDisplayHelper.dp2px(mContext, mShadowElevationDp), mShadowAlpha);
        }

        private void initItemData(TableBean.DataBean item) {

            btn_table.setText(item.getTableName());

//            if (item.getServiceCharge() > 0) {
//                tv_service_fee.setText(item.getServiceCharge() + "%");
//                tv_service_fee.setVisibility(View.VISIBLE);
//            } else {
            tv_service_fee.setVisibility(View.GONE);
//            }
            if (item.getStatus() != 0) {
                int person = 0;
                if (item.getPerson() != 0) {
                    person = item.getPerson();
                }
                tv_people.setVisibility(View.VISIBLE);
                tv_people.setText(person + "人");
                String createDate = item.getCreateTime();
                if (!TextUtils.isEmpty(createDate)) {
                    LogUtil.d(TAG, "tableName: " + item.getTableName() + "  " + "createDate: " + createDate);
                    try {
                        Date date = new Date(createDate);
                        String createTime = TimeUtils.getStringByFormat(date, TimeUtils.DEFAULT_DATE_FORMAT);
                        String currentTime = TimeUtils.getStringByFormat(System.currentTimeMillis(), TimeUtils.DEFAULT_DATE_FORMAT);
                        long[] difference = TimeUtils.getDistanceTimes2(createTime, currentTime);
                        if (difference[0] != 0) {
                            tv_open_duration.setText(difference[0] + ":" + difference[1] + ":" + difference[2]);
                        } else if (difference[1] != 0) {
                            tv_open_duration.setText(difference[1] + ":" + difference[2]);
                        } else if (difference[2] != 0) {
                            tv_open_duration.setText("00:" + difference[2]);
                        } else {
                            tv_open_duration.setText("00:00");
                        }
                        tv_open_duration.setVisibility(View.VISIBLE);
                    } catch (Exception e) {
                        tv_open_duration.setVisibility(View.GONE);
                    }
                } else {
                    tv_open_duration.setVisibility(View.GONE);
                }
                btn_table.setMaxLines(1);
            } else {
                //未開檯空間足夠可換行顯示
                btn_table.setMaxLines(2);
                tv_people.setVisibility(View.GONE);
                tv_open_duration.setVisibility(View.GONE);
            }

            if (item.getStatus() != 0) {
                switch (item.getType()) {
                    case TableManagerItem.TABLE_TYPE_CANTEEN:
                        tv_type_labe.setText("堂");
                        tv_type_labe.setTextColor(Color.parseColor("#249B65"));
                        break;
                    case TableManagerItem.TABLE_TYPE_TAKEAWAY:
                        tv_type_labe.setText("外");
                        tv_type_labe.setTextColor(Color.parseColor("#FF720A"));
                        break;
                    case TableManagerItem.TABLE_TYPE_SELF_FETCHING:
                        tv_type_labe.setText("自");
                        tv_type_labe.setTextColor(Color.parseColor("#00479D"));
                        break;
                }
                fl_table_type.setVisibility(View.VISIBLE);
            } else {
                fl_table_type.setVisibility(View.GONE);
            }
            if (item.getMemberId() > 0) {
                iv_vip.setVisibility(View.VISIBLE);
            } else {
                iv_vip.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(item.getSkyQrCode())) {
                setTableFlagDispalyLayout(item);
                tv_scan_flag.setVisibility(View.VISIBLE);
            } else {
                tv_scan_flag.setVisibility(View.GONE);
            }
        }

        private void initTableBackground(TableBean.DataBean item) {

            if (item.getSplitStatus() != 0) {
                setBackGroundWork(item, ContextCompat.getColor(mContext, R.color.app_color_blue_2), R.color.theme_white_color, R.color.theme_white_color);
            } else {

                ll_container.setBackgroundColor(Color.parseColor("#FFFFFFFF"));

                if (item.getUseStatus() == 1) {
                    setBackGroundWork(item, Color.parseColor("#FFD14141"), R.color.theme_white_color, R.color.theme_black);
                } else {
                    switch (item.getStatus()) {
                        case 0:
                            setBackGroundWork(item, Color.parseColor("#FFFFFFFF"), R.color.black, R.color.theme_black);
                            break;
                        case 1:
//                        setBackGroundWork(item, "2", R.drawable.table_shape_table_send, R.drawable.tablebutton_glassgreen_new, R.color.theme_white_color);                        break;
                        case 2:
                            setBackGroundWork(item, Color.parseColor("#FF249B65"), R.color.theme_white_color, R.color.theme_white_color);
                            break;
                        case 3:
                            setBackGroundWork(item, Color.parseColor("#FFE5AC00"), R.color.theme_white_color, R.color.theme_white_color);
                            break;
                        case 4:
                        case 5:
                        case 6:
                            setBackGroundWork(item, ContextCompat.getColor(mContext, R.color.Violet), R.color.theme_white_color, R.color.theme_white_color);
                            break;
                    }
                }
            }
        }

        private void initItemTableClick(TableBean.DataBean item, int position) {
            rl_table.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (mOnItemClickListener != null) {
//                        RxBindingUtils.setViewClicks(v)
//                                .subscribe(new Consumer<Object>() {
//
//                                    @Override
//                                    public void accept(Object o) throws Exception {
                        mOnItemClickListener.onItemClick(item, position);
//                                    }
//                                });
                    }
                }
            });
        }

        private void initItemDispalyMetrics() {
            if (btn_table.getGravity() != Gravity.CENTER) {
                rl_table.setGravity(Gravity.CENTER);
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) rl_table.getLayoutParams();
                lp.height = ItemColHeight;
                rl_table.setLayoutParams(lp);
            }
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) rl_table.getLayoutParams();
            rl_table.setLayoutParams(lp);

            rl_table.setMinimumHeight(ItemColHeight);

            RelativeLayout.LayoutParams relativeLayout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            relativeLayout.height = ItemColHeight;
            rl_table.setLayoutParams(relativeLayout);
        }

        private void setBackGroundWork(TableBean.DataBean item, int defaultMainback, int defaultFontColor, int serviceFeeFontColor) {
            if (defaultMainback != -1) {
                ll_container.setBackgroundColor(defaultMainback);
            }
            btn_table.setTextColor(mContext.getResources().getColor(defaultFontColor));
            tv_service_fee.setTextColor(mContext.getResources().getColor(serviceFeeFontColor));
        }

        private void setTableFlagDispalyLayout(TableBean.DataBean item) {

            String skyQRCodeTableFlagBackgroupColor = GsaCloudApplication.uiStyleConfiguration.getSkyQRCodeTableFlagBackgroupColorValue();

            GradientDrawable drawable = new GradientDrawable();
            drawable.setColor(Color.parseColor(skyQRCodeTableFlagBackgroupColor));
            tv_scan_flag.setBackground(drawable);

            int skyQRCodeTableFlagHeight = GsaCloudApplication.uiStyleConfiguration.getSkyQRCodeTableFlagHeightValue();
            int skyQRCodeTableFlagWith = GsaCloudApplication.uiStyleConfiguration.getSkyQRCodeTableFlagWithValue();

            RelativeLayout.LayoutParams relativeLayout = (RelativeLayout.LayoutParams) tv_scan_flag.getLayoutParams();
            relativeLayout.height = ArmsUtils.dip2px(mContext, skyQRCodeTableFlagHeight);
            relativeLayout.width = ArmsUtils.dip2px(mContext, skyQRCodeTableFlagWith);
            tv_scan_flag.setLayoutParams(relativeLayout);

            String skyQRCodeTableFlagText = GsaCloudApplication.functionConfiguration.getSkyQRCodeTableFlagTextVaule();
            int skyQRCodeTableFlagTextSize = GsaCloudApplication.uiStyleConfiguration.getSkyQRCodeTableFlagTextSizeValue();

            tv_scan_flag.setText(skyQRCodeTableFlagText);
            tv_scan_flag.setTextSize(skyQRCodeTableFlagTextSize);

            if (item.getMemberId() == 0) {
                //未登入会员
                if (item.getOrderId() != null) {
                    //已送单（橙色底黑色“S”）
                    //橙色底黑色字“S”=SKY ORDER未登錄會員
                    tv_scan_flag.setTextColor(Color.parseColor("#000000"));
                    tv_scan_flag.setBackgroundColor(Color.parseColor("#FF7F04"));
                } else {
                    //未送单（蓝色底黑色“S”）
                    //藍色底黑色字“S”=SKY ORDER未登錄會員
                    tv_scan_flag.setTextColor(Color.parseColor("#000000"));
                    tv_scan_flag.setBackgroundColor(Color.parseColor("#0404FF"));
                }
            } else {
                //已登入会员
                if (item.getOrderId() != null) {
                    //已送单（橙色底白色“S”）
                    tv_scan_flag.setTextColor(Color.parseColor("#FFFFFF"));
                    tv_scan_flag.setBackgroundColor(Color.parseColor("#FF7F04"));
                } else {
                    //未送单（蓝色底白色“S”）
                    tv_scan_flag.setTextColor(Color.parseColor("#FFFFFF"));
                    tv_scan_flag.setBackgroundColor(Color.parseColor("#0404FF"));
                }
            }
        }
    }

    public int getStyle() {
        return style;
    }

    public void setStyle(int style) {
        this.style = style;
    }

    private OnItemClickListener mOnItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {

        void onItemClick(TableBean.DataBean datasBean, int position);

    }
}
