package com.genlot.ninglottery.game.ssq;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
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.IBetBean;
import com.genlot.ninglottery.game.bet.BetManager;
import com.genlot.ninglottery.game.bet.BetNumber;
import com.genlot.ninglottery.game.common.CommonFragment;
import com.genlot.ninglottery.game.common.NumberAdapter;
import com.genlot.ninglottery.game.ssq.bean.BaseSSQ;
import com.genlot.ninglottery.game.ssq.bean.BetSSQ;
import com.genlot.ninglottery.game.ssq.bean.MultiSSQ;
import com.genlot.ninglottery.game.ssq.bean.SingleSSQ;
import com.genlot.ninglottery.game.ssq.betview.BaseSSQView;
import com.genlot.ninglottery.game.ssq.betview.MultiSSQView;
import com.genlot.ninglottery.game.common.SingleView;
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 SSQFragment extends CommonFragment {

    private List<BetNumber> mRedList, mBlueList;
    private NumberAdapter mRedAdapter,mBlueAdapter;

    private int mRedNum, mBlueNum;
    private int mTuoNum, mDanNum;

    @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.SSQ_SINGLE;
                    mBetView = new SingleView(activity, SingleSSQ.class);
                    btRandom5.setVisibility(View.VISIBLE);
                    break;
                case R.id.radio_multi:
                    mPlayType = PlayTypeID.SSQ_MULTI;
                    mBetView = new MultiSSQView(activity);
                    btRandom5.setVisibility(View.GONE);
                    break;
                case R.id.radio_base:
                    mPlayType = PlayTypeID.SSQ_BASE;
                    mBetView = new BaseSSQView(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) {
        switch (playTypeId) {
            case PlayTypeID.SSQ_SINGLE:
                radioSingle.setChecked(true);
                break;
            case PlayTypeID.SSQ_MULTI:
                radioMulti.setChecked(true);
                break;
            case PlayTypeID.SSQ_BASE:
            case PlayTypeID.SSQ_BASE_MULTI:
                radioBase.setChecked(true);
                break;
        }
    }

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

    /**
     * 红球点击响应
     * @param position 位置
     */
    private void onRedNumberClick(int position) {
        BetNumber betNumber = mRedList.get(position);
        int type = betNumber.getType();
        switch (mPlayType) {
            case PlayTypeID.SSQ_SINGLE:
                SingleSSQ bean = (SingleSSQ) ((SingleView) mBetView).getCurrentBet();
                if (type == BetNumber.NORMAL) {
                    if (bean.mRedList.size() == 6) {
                        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.SSQ_MULTI:
                MultiSSQ multiSSQ = (MultiSSQ) mBetView.mBetList.get(0);
                if (type == BetNumber.NORMAL) {
                    if (multiSSQ.mRedList.size() == SSQConfig.MULTI_RED_MAX) {
                        return;
                    }
                    betNumber.setType(BetNumber.CHECKED);
                    multiSSQ.add(betNumber);
                } else {
                    multiSSQ.remove(betNumber);
                    betNumber.setType(BetNumber.NORMAL);
                }
                ((MultiSSQView) mBetView).refreshRed();
                if (mBetView.mCurrentRow != 0) {
                    mBetView.rowChange(0);
                }
                break;
            case PlayTypeID.SSQ_BASE:
            case PlayTypeID.SSQ_BASE_MULTI:
                BaseSSQ baseSSQ = (BaseSSQ) mBetView.mBetList.get(0);
                if (mBetView.mCurrentRow == 0) {
                    if (type == BetNumber.NORMAL || type == BetNumber.CHECKED) {
                        if (baseSSQ.mDanList.size() == baseSSQ.getMaxDan()) {
                            return;
                        }
                        betNumber.setType(BetNumber.DAN);
                        if (type == BetNumber.NORMAL) {
                            baseSSQ.add(betNumber);
                        } else {
                            baseSSQ.change(betNumber);
                        }
                        ((BaseSSQView) mBetView).refreshDan();
                        ((BaseSSQView) mBetView).refreshTuo();
                    }else {
                        baseSSQ.remove(betNumber);
                        betNumber.setType(BetNumber.NORMAL);
                        ((BaseSSQView) mBetView).refreshDan();
                    }
                } else if (mBetView.mCurrentRow == 1) {
                    if (type == BetNumber.NORMAL || type == BetNumber.DAN) {
                        if (baseSSQ.mRedList.size() == baseSSQ.getMaxTuo()) {
                            return;
                        }
                        betNumber.setType(BetNumber.CHECKED);
                        if (type == BetNumber.NORMAL) {
                            baseSSQ.add(betNumber);
                        } else {
                            baseSSQ.change(betNumber);
                        }
                        ((BaseSSQView) mBetView).refreshDan();
                        ((BaseSSQView) mBetView).refreshTuo();
                    } else {
                        LogTool.logD("row = 1 红球取消");
                        baseSSQ.remove(betNumber);
                        betNumber.setType(BetNumber.NORMAL);
                        ((BaseSSQView) mBetView).refreshTuo();
                    }
                } else {
                    if (type == BetNumber.NORMAL) {
                        mBetView.rowChange(1);
                        if (baseSSQ.mRedList.size() == baseSSQ.getMaxTuo()) {
                            return;
                        }
                        betNumber.setType(BetNumber.CHECKED);
                        baseSSQ.add(betNumber);
                        ((BaseSSQView) mBetView).refreshTuo();
                    } else if (type == BetNumber.CHECKED) {
                        mBetView.rowChange(1);
                        baseSSQ.remove(betNumber);
                        betNumber.setType(BetNumber.NORMAL);
                        ((BaseSSQView) mBetView).refreshTuo();
                    } else {
                        mBetView.rowChange(0);
                        baseSSQ.remove(betNumber);
                        betNumber.setType(BetNumber.NORMAL);
                        ((BaseSSQView) mBetView).refreshDan();
                    }
                }
                break;
            default:
                break;
        }
        mRedAdapter.notifyDataSetChanged();
        refreshMoney();
    }

    /**
     * 蓝球点击响应
     * @param position  位置
     */
    private void onBlueNumberClick(int position) {
        BetNumber betNumber = mBlueList.get(position);
        int type = betNumber.getType();
        switch (mPlayType) {
            case PlayTypeID.SSQ_SINGLE:
                SingleSSQ bean = (SingleSSQ) ((SingleView) mBetView).getCurrentBet();
                if (type == BetNumber.NORMAL) {
                    if (bean.mBlueList.size() == 1) {
                        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.SSQ_MULTI:
                MultiSSQ multiSSQ = (MultiSSQ) mBetView.mBetList.get(0);
                if (type == BetNumber.NORMAL) {
                    if (multiSSQ.mBlueList.size() == SSQConfig.MULTI_BLUE_MAX) {
                        return;
                    }
                    betNumber.setType(BetNumber.CHECKED);
                    multiSSQ.add(betNumber);
                } else {
                    multiSSQ.remove(betNumber);
                    betNumber.setType(BetNumber.NORMAL);
                }
                ((MultiSSQView) mBetView).refreshBlue();
                if (mBetView.mCurrentRow != 1) {
                    mBetView.rowChange(1);
                }
                break;
            case PlayTypeID.SSQ_BASE:
            case PlayTypeID.SSQ_BASE_MULTI:
                BaseSSQ baseSSQ = (BaseSSQ) mBetView.mBetList.get(0);
                if (type == BetNumber.NORMAL) {
                    betNumber.setType(BetNumber.CHECKED);
                    baseSSQ.add(betNumber);
                }else {
                    baseSSQ.remove(betNumber);
                    betNumber.setType(BetNumber.NORMAL);
                }
                ((BaseSSQView) mBetView).refreshBlue();
                if (mBetView.mCurrentRow != 2) {
                    mBetView.rowChange(2);
                }
                break;
            default:
                break;
        }
        mBlueAdapter.notifyDataSetChanged();
        refreshMoney();
    }


    @Override
    public void initData() {
        mRedList = new ArrayList<>();
        mBlueList = new ArrayList<>();
        //红球
        for (int i = 0; i < 33; i++) {
            BetNumber number = new BetNumber(StringTool.format2(i + 1));
            mRedList.add(number);
        }
        //篮球
        for (int i = 0; i < 16; i++) {
            BetNumber number = new BetNumber(StringTool.format2(i + 1));
            number.setRed(false);
            mBlueList.add(number);
        }
    }

    @Override
    public void initAdapter() {
        rvRed.setLayoutManager(new GridLayoutManager(activity,8));
        rvRed.addItemDecoration(new GridItemDecoration(20,10));
        rvBlue.setLayoutManager(new GridLayoutManager(activity,8));
        rvBlue.addItemDecoration(new GridItemDecoration(20,10));
        mRedAdapter = new NumberAdapter(R.layout.item_number, mRedList);
        mBlueAdapter = new NumberAdapter(R.layout.item_number, mBlueList);
        rvRed.setAdapter(mRedAdapter);
        rvBlue.setAdapter(mBlueAdapter);
        rvRed.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                onRedNumberClick(position);
            }
        });
        rvBlue.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                onBlueNumberClick(position);
            }
        });
    }

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

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

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

    @Override
    public void refreshAdapter(IBetBean betBean) {
        mRedAdapter.changeSSQBet((BetSSQ) betBean, true);
        mBlueAdapter.changeSSQBet((BetSSQ) betBean, false);
    }

    @Override
    public void random() {
        switch (mPlayType) {
            case PlayTypeID.SSQ_SINGLE:
                if (isRandom) {
                    randomNum(mRandomNum);
                } else {
                    showSingleRandomDialog();
                }
                break;
            case PlayTypeID.SSQ_MULTI:
                if (isRandom) {
                    randomMulti();
                } else {
                    showMultiRandomDialog();
                }
                break;
            case PlayTypeID.SSQ_BASE:
            case PlayTypeID.SSQ_BASE_MULTI:
                if (isRandom) {
                    randomBaseRound();
                } else {
                    showBaseRoundRandomDialog();
                }
                break;
        }
    }

    @Override
    public long getValidBets() {
        long num = 0;
        switch (mPlayType) {
            case PlayTypeID.SSQ_SINGLE:
                for (IBetBean bean : mBetView.mBetList) {
                    if (bean.isFull()) {
                        num++;
                    }
                }
                break;
            case PlayTypeID.SSQ_MULTI:
                MultiSSQ multiSSQ = (MultiSSQ) mBetView.mBetList.get(0);
                if (multiSSQ.isFull()) {
                    num = multiSSQ.mBlueList.size() * GameUtil.C(multiSSQ.mRedList.size(), 6);
                }
                break;
            case PlayTypeID.SSQ_BASE:
            case PlayTypeID.SSQ_BASE_MULTI:
                BaseSSQ baseSSQ = (BaseSSQ) mBetView.mBetList.get(0);
                if (baseSSQ.isFull()) {
                    num = baseSSQ.mBlueList.size() *
                            GameUtil.C(baseSSQ.mRedList.size(), 6 - baseSSQ.mDanList.size());
                }
                break;
        }
        return num;
    }

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

    public void showMultiRandomDialog() {
        CommonDialog.newInstance().setLayoutId(R.layout.dialog_random_multi)
                .setConvertListener((ViewConvertListener) (holder, dialog) -> {
                    KeyboardEditText etRed = holder.getView(R.id.et_red);
                    KeyboardEditText etBlue= holder.getView(R.id.et_blue);
                    holder.setOnClickListener(R.id.bt_cancel, v -> dialog.dismiss());
                    holder.setOnClickListener(R.id.bt_confirm, v -> {
                        String red = etRed.getText().toString().trim();
                        String blue = etBlue.getText().toString().trim();
                        if (TextUtils.isEmpty(red) || Integer.parseInt(red) < SSQConfig.MULTI_RED_MIN
                                || Integer.parseInt(red) > SSQConfig.MULTI_RED_MAX) {
                            showTips("红球个数超界 个数范围[" + SSQConfig.MULTI_RED_MIN + "-" + SSQConfig.MULTI_RED_MAX + "]");
                            return;
                        }
                        if (TextUtils.isEmpty(blue) || Integer.parseInt(blue) < SSQConfig.MULTI_BLUE_MIN
                                || Integer.parseInt(blue) > SSQConfig.MULTI_BLUE_MAX) {
                            showTips("蓝球个数超界 个数范围[" + SSQConfig.MULTI_BLUE_MIN + "-" + SSQConfig.MULTI_BLUE_MAX + "]");
                            return;
                        }
                        if ((Integer.parseInt(blue) + Integer.parseInt(red))< SSQConfig.MULTI_TOTAL_MIN) {
                            showTips("总球个数超界 个数范围[" + SSQConfig.MULTI_TOTAL_MIN + "-" + SSQConfig.MULTI_TOTAL_MAX + "]");
                            return;
                        }
                        isRandom = true;
                        mRedNum = Integer.parseInt(red);
                        mBlueNum = Integer.parseInt(blue);
                        showTips("");
                        randomMulti();
                        dialog.dismiss();
                    });
                })
                .setSize(ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight())
                .setOutCancel(false)
                .show(activity.getSupportFragmentManager());
    }

    public void showBaseRoundRandomDialog() {
        BaseSSQ bean = (BaseSSQ) mBetView.mBetList.get(0);
        CommonDialog.newInstance().setLayoutId(R.layout.dialog_random_comom)
                .setConvertListener((ViewConvertListener) (holder, dialog) -> {
                    KeyboardEditText etDan = holder.getView(R.id.et_dan);
                    KeyboardEditText etTuo = holder.getView(R.id.et_tuo);
                    KeyboardEditText etBlue= holder.getView(R.id.et_blue);
                    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();
                        String blue = etBlue.getText().toString().trim();
                        if (TextUtils.isEmpty(dan) || Integer.parseInt(dan) < bean.getMinDan()
                                || Integer.parseInt(dan) > bean.getMaxDan()) {
                            showTips("胆球个数超界 个数范围[" + bean.getMinDan() + "-" + bean.getMaxDan() + "]");
                            return;
                        }
                        if (TextUtils.isEmpty(tuo) || Integer.parseInt(tuo) < bean.getMinTuo()
                                || Integer.parseInt(tuo) > bean.getMaxTuo()) {
                            showTips("拖球个数超界 个数范围[" + bean.getMinTuo() + "-" + bean.getMaxTuo() + "]");
                            return;
                        }
                        if (TextUtils.isEmpty(blue) || Integer.parseInt(blue) < bean.getMinBlue()
                                || Integer.parseInt(blue) > bean.getMaxBlue()) {
                            showTips("蓝球个数超界 个数范围[" + bean.getMinBlue() + "-" + bean.getMaxBlue() + "]");
                            return;
                        }
                        if ((Integer.parseInt(dan) + Integer.parseInt(tuo)) < bean.getMinRed()) {
                            showTips("红球个数超界 个数范围[" + bean.getMinRed() + "-" + bean.getMaxRed() + "]");
                            return;
                        }
                        isRandom = true;
                        mDanNum = Integer.parseInt(dan);
                        mTuoNum = Integer.parseInt(tuo);
                        mBlueNum = Integer.parseInt(blue);
                        showTips("");
                        randomBaseRound();
                        dialog.dismiss();
                    });
                })
                .setSize(ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight())
                .setOutCancel(false)
                .show(activity.getSupportFragmentManager());
    }

    private void randomMulti() {
        MultiSSQ bean = (MultiSSQ) mBetView.mBetList.get(0);
        bean.random(mRedNum, mBlueNum);
        ((MultiSSQView) mBetView).refreshRed();
        ((MultiSSQView) mBetView).refreshBlue();
        refreshAdapter(bean);
        refreshMoney();
    }

    private void randomBaseRound() {
        BaseSSQ bean = (BaseSSQ) mBetView.mBetList.get(0);
        bean.random(mDanNum, mTuoNum, mBlueNum);
        ((BaseSSQView) mBetView).refreshDan();
        ((BaseSSQView) mBetView).refreshTuo();
        ((BaseSSQView) mBetView).refreshBlue();
        refreshAdapter(bean);
        refreshMoney();
    }

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

}
