package com.genlot.ninglottery.game.qlc;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;

import com.blankj.utilcode.util.ScreenUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.genlot.ninglottery.R;
import com.genlot.ninglottery.game.bet.BetManager;
import com.genlot.ninglottery.game.bet.BetNumber;
import com.genlot.ninglottery.game.bet.IBetBean;
import com.genlot.ninglottery.game.common.CommonFragment;
import com.genlot.ninglottery.game.common.NumberAdapter;
import com.genlot.ninglottery.game.common.SingleView;
import com.genlot.ninglottery.game.qlc.bean.Base7lc;
import com.genlot.ninglottery.game.qlc.bean.Bet7lc;
import com.genlot.ninglottery.game.qlc.bean.Multi7lc;
import com.genlot.ninglottery.game.qlc.bean.Single7lc;
import com.genlot.ninglottery.game.qlc.betview.Base7lcView;
import com.genlot.ninglottery.game.qlc.betview.Multi7lcView;
import com.genlot.ninglottery.model.PlayTypeID;
import com.genlot.ninglottery.toolkit.GameUtil;
import com.genlot.ninglottery.toolkit.LogTool;
import com.genlot.ninglottery.toolkit.StringTool;
import com.genlot.ninglottery.widget.Diaolog.CommonDialog;
import com.genlot.ninglottery.widget.Diaolog.ViewConvertListener;
import com.genlot.ninglottery.widget.KeyboardEditText;
import com.genlot.ninglottery.widget.decoration.GridItemDecoration;

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

import butterknife.BindView;
import butterknife.OnCheckedChanged;

/**
 * @author ZhuYongKang
 * @description 七乐彩游戏界面
 * @date 2019/8/22
 */
public class QLCFragment extends CommonFragment {

    private List<BetNumber> mNumList;
    private NumberAdapter mAdapter;
    private int mDanNum, mTuoNum;

    @OnCheckedChanged({R.id.radio_single, R.id.radio_multi, R.id.radio_base})
    public void playTypeChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            frameBet.removeAllViews();
            switch (buttonView.getId()) {
                case R.id.radio_single:
                    mPlayType = PlayTypeID.STAR_7_SINGLE;
                    mBetView = new SingleView(activity, Single7lc.class);
                    btRandom5.setVisibility(View.VISIBLE);
                    break;
                case R.id.radio_multi:
                    mPlayType = PlayTypeID.STAR_7_MULTI;
                    mBetView = new Multi7lcView(activity);
                    btRandom5.setVisibility(View.GONE);
                    break;
                case R.id.radio_base:
                    mPlayType = PlayTypeID.STAR_7_BASE_ROUND;
                    mBetView = new Base7lcView(activity);
                    btRandom5.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
            BetManager.getInstance().setPlayType(mPlayType);
            frameBet.addView(mBetView);
            clearUI();
            if (isRandom) {
                clearRandom();
            }
        }
    }

    @Override
    public void changePlayType(int playTypeId) {
        if (mPlayType == playTypeId) {
            return;
        }
        LogTool.logD("changePlayType: " + playTypeId);
        switch (playTypeId) {
            case PlayTypeID.STAR_7_SINGLE:
                radioSingle.setChecked(true);
                break;
            case PlayTypeID.STAR_7_MULTI:
                radioMulti.setChecked(true);
                break;
            case PlayTypeID.STAR_7_BASE_ROUND:
                radioBase.setChecked(true);
                break;
        }
    }

    /**
     * 红球点击响应
     * @param position 位置
     */
    private void onNumberClick(int position) {
        BetNumber betNumber = mNumList.get(position);
        int type = betNumber.getType();
        switch (mPlayType) {
            case PlayTypeID.STAR_7_SINGLE:
                Single7lc bean = (Single7lc) ((SingleView) mBetView).getCurrentBet();
                if (type == BetNumber.NORMAL) {
                    if (bean.mRedList.size() == 7) {
                        return;
                    }
                    betNumber.setType(BetNumber.CHECKED);
                    bean.add(betNumber);
                } else {
                    bean.remove(betNumber);
                    betNumber.setType(BetNumber.NORMAL);
                }
                ((SingleView) mBetView).refreshRow(mBetView.mCurrentRow);
                if (bean.isFull() && mBetView.mCurrentRow < 4) {
                    mBetView.rowChange(mBetView.mCurrentRow + 1);
                    refreshAdapter(((SingleView) mBetView).getCurrentBet());
                }
                break;
            case PlayTypeID.STAR_7_MULTI:
                Multi7lc multiBean = (Multi7lc) mBetView.mBetList.get(0);
                if (type == BetNumber.NORMAL) {
                    if (multiBean.mRedList.size() == QlcConfig.MULTI_RED_MAX) {
                        return;
                    }
                    betNumber.setType(BetNumber.CHECKED);
                    multiBean.add(betNumber);
                } else {
                    multiBean.remove(betNumber);
                    betNumber.setType(BetNumber.NORMAL);
                }
                ((Multi7lcView) mBetView).refresh();
                break;
            case PlayTypeID.STAR_7_BASE_ROUND:
                Base7lc baseRoundBean = (Base7lc) mBetView.mBetList.get(0);
                if (mBetView.mCurrentRow == 0) {
                    if (type == BetNumber.NORMAL || type == BetNumber.CHECKED) {
                        if (baseRoundBean.mDanList.size() == QlcConfig.BASEROUND_DAN_MAX) {
                            return;
                        }
                        betNumber.setType(BetNumber.DAN);
                        if (type == BetNumber.NORMAL) {
                            baseRoundBean.add(betNumber);
                        } else {
                            baseRoundBean.change(betNumber);
                        }
                        ((Base7lcView) mBetView).refreshDan();
                        ((Base7lcView) mBetView).refreshTuo();
                    }else {
                        baseRoundBean.remove(betNumber);
                        betNumber.setType(BetNumber.NORMAL);
                        ((Base7lcView) mBetView).refreshDan();
                    }
                } else if (mBetView.mCurrentRow == 1) {
                    if (type == BetNumber.NORMAL || type == BetNumber.DAN) {
                        if (baseRoundBean.mRedList.size() == QlcConfig.BASEROUND_TUO_MAX) {
                            return;
                        }
                        betNumber.setType(BetNumber.CHECKED);
                        if (type == BetNumber.NORMAL) {
                            baseRoundBean.add(betNumber);
                        } else {
                            baseRoundBean.change(betNumber);
                        }
                        ((Base7lcView) mBetView).refreshDan();
                        ((Base7lcView) mBetView).refreshTuo();
                    } else {
                        baseRoundBean.remove(betNumber);
                        betNumber.setType(BetNumber.NORMAL);
                        ((Base7lcView) mBetView).refreshTuo();
                    }
                }
                break;
            default:
                break;
        }
        mAdapter.notifyDataSetChanged();
        refreshMoney();
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_7lc;
    }

    @Override
    public void initData() {
        mNumList = new ArrayList<>();
        //红球
        for (int i = 0; i < 30; i++) {
            BetNumber number = new BetNumber(StringTool.format2(i + 1));
            mNumList.add(number);
        }
    }

    @Override
    public void initAdapter() {
        rvRed.setLayoutManager(new GridLayoutManager(activity,8));
        rvRed.addItemDecoration(new GridItemDecoration(20,10));
        mAdapter = new NumberAdapter(R.layout.item_number, mNumList);
        rvRed.setAdapter(mAdapter);
        rvRed.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                onNumberClick(position);
            }
        });
    }

    @Override
    public void initViews() {
        if (!isFromCopy) {
            radioSingle.setChecked(true);
        }
    }

    @Override
    public int getMaxTimes() {
        return QlcConfig.MAX_TIMES;
    }

    @Override
    public int getOneBetMoney() {
        return QlcConfig.MONEY_OF_BET;
    }

    @Override
    public long getValidBets() {
        long num = 0;
        switch (mPlayType) {
            case PlayTypeID.STAR_7_SINGLE:
                for (IBetBean bean : mBetView.mBetList) {
                    if (bean.isFull()) {
                        num++;
                    }
                }
                break;
            case PlayTypeID.STAR_7_MULTI:
                Multi7lc bean = (Multi7lc) mBetView.mBetList.get(0);
                if (bean.isFull()) {
                    num = GameUtil.C(bean.mRedList.size(), 7);
                }
                break;
            case PlayTypeID.STAR_7_BASE_ROUND:
                Base7lc baseRoundBean = (Base7lc) mBetView.mBetList.get(0);
                if (baseRoundBean.isFull()) {
                    num = GameUtil.C(baseRoundBean.mRedList.size(), 7 - baseRoundBean.mDanList.size());
                }
                break;
        }
        return num;
    }

    @Override
    public void refreshAdapter(IBetBean betBean) {
        mAdapter.change7lcBet((Bet7lc) betBean);
    }

    @Override
    public void clearAdapter() {
        mAdapter.clear();
    }

    @Override
    public void random() {
        switch (mPlayType) {
            case PlayTypeID.STAR_7_SINGLE:
                if (isRandom) {
                    randomNum(mRandomNum);
                } else {
                    showSingleRandomDialog();
                }
                break;
            case PlayTypeID.STAR_7_MULTI:
                if (isRandom) {
                    randomMulti();
                } else {
                    showMultiRandomDialog();
                }
                break;
            case PlayTypeID.STAR_7_BASE_ROUND:
                if (isRandom) {
                    randomBaseRound();
                } else {
                    showBaseRoundRandomDialog();
                }
                break;
        }
    }

    public void showMultiRandomDialog() {
        CommonDialog.newInstance().setLayoutId(R.layout.dialog_random_single)
                .setConvertListener((ViewConvertListener) (holder, dialog) -> {
                    holder.setViewVisibility(R.id.textView6, false);
                    holder.setText(R.id.textView5, "包号数");
                    KeyboardEditText etNum= holder.getView(R.id.et_bets);
                    etNum.setFilters(new InputFilter[]{new InputFilter.LengthFilter(2)});
                    holder.setOnClickListener(R.id.bt_cancel, v -> dialog.dismiss());
                    holder.setOnClickListener(R.id.bt_confirm, v -> {
                        String num = etNum.getText().toString().trim();
                        if (TextUtils.isEmpty(num) || Integer.parseInt(num) < QlcConfig.MULTI_RED_MIN
                                || Integer.parseInt(num) > QlcConfig.MULTI_RED_MAX) {
                            showTips("包个数超界 个数范围[" + QlcConfig.MULTI_RED_MIN + "-" + QlcConfig.MULTI_RED_MAX + "]");
                            dialog.dismiss();
                            return;
                        }
                        isRandom = true;
                        mRandomNum = Integer.parseInt(num);
                        randomMulti();
                        showTips("");
                        dialog.dismiss();
                    });
                })
                .setSize(ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight())
                .setOutCancel(false)
                .show(activity.getSupportFragmentManager());
    }

    public void showBaseRoundRandomDialog() {
        CommonDialog.newInstance().setLayoutId(R.layout.dialog_random_comom)
                .setConvertListener((ViewConvertListener) (holder, dialog) -> {
                    holder.setViewVisibility(R.id.ll_random3, false);
                    KeyboardEditText etDan = holder.getView(R.id.et_dan);
                    KeyboardEditText etTuo= holder.getView(R.id.et_tuo);
                    holder.setOnClickListener(R.id.bt_cancel, v -> dialog.dismiss());
                    holder.setOnClickListener(R.id.bt_confirm, v -> {
                        String dan = etDan.getText().toString().trim();
                        String tuo = etTuo.getText().toString().trim();
                        if (TextUtils.isEmpty(dan) || Integer.parseInt(dan) < QlcConfig.BASEROUND_DAN_MIN
                                || Integer.parseInt(dan) > QlcConfig.BASEROUND_DAN_MAX) {
                            showTips("胆个数超界 个数范围[" + QlcConfig.BASEROUND_DAN_MIN + "-" + QlcConfig.BASEROUND_DAN_MAX + "]");
                            return;
                        }
                        if (TextUtils.isEmpty(tuo)|| Integer.parseInt(tuo) < QlcConfig.BASEROUND_TUO_MIN
                                || Integer.parseInt(tuo) > QlcConfig.BASEROUND_TUO_MAX) {
                            showTips("拖个数超界 个数范围[" + QlcConfig.BASEROUND_TUO_MIN + "-" + QlcConfig.BASEROUND_TUO_MAX + "]");
                            return;
                        }
                        if ((Integer.parseInt(dan) + Integer.parseInt(tuo)) < QlcConfig.BASEROUND_RED_MIN) {
                            showTips("胆+拖包个数超界 个数范围[" + QlcConfig.BASEROUND_RED_MIN + "-" + 30 + "]");
                            return;
                        }
                        isRandom = true;
                        mDanNum = Integer.parseInt(dan);
                        mTuoNum = Integer.parseInt(tuo);
                        randomBaseRound();
                        showTips("");
                        dialog.dismiss();
                    });
                })
                .setSize(ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight())
                .setOutCancel(false)
                .show(activity.getSupportFragmentManager());
    }

    private void randomMulti() {
        Multi7lc bean = (Multi7lc) mBetView.mBetList.get(0);
        bean.random(mRandomNum);
        ((Multi7lcView) mBetView).refresh();
        refreshAdapter(bean);
        refreshMoney();
    }

    private void randomBaseRound() {
        Base7lc bean = (Base7lc) mBetView.mBetList.get(0);
        bean.random(mDanNum, mTuoNum);
        ((Base7lcView) mBetView).refreshDan();
        ((Base7lcView) mBetView).refreshTuo();
        refreshAdapter(bean);
        refreshMoney();
    }

    @BindView(R.id.rv_red)
    RecyclerView rvRed;
    @BindView(R.id.radio_single)
    RadioButton radioSingle;
    @BindView(R.id.radio_multi)
    RadioButton radioMulti;
    @BindView(R.id.radio_base)
    RadioButton radioBase;
}
