package com.sunzee.ui.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;

import com.hboxs.serialport.SerialPortDevice;
import com.hboxs.serialport.SerialPortManager;
import com.hboxs.serialport.frame.ResponseFrame;
import com.hboxs.serialport.message.Message;
import com.hboxs.serialport.util.AsciiUtils;
import com.sunzee.R;
import com.sunzee.adapter.DebugParameterAdapter;
import com.sunzee.adapter.DebugParameterXAdapter;
import com.sunzee.adapter.DebugParameterYAdapter;
import com.sunzee.base.BaseApplication;
import com.sunzee.base.MvpFragment;
import com.sunzee.mvp.debug.DebugPresenter;
import com.sunzee.mvp.debug.DebugView;
import com.sunzee.thread.debugparameter.ThreadPoolDebugParameter;
import com.sunzee.utils.CustomDecoration;
import com.sunzee.utils.PreventSpeedClickUtil;
import com.sunzee.utils.ToastUtil;
import com.sunzee.utils.UiUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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

/**
 * 调试页界面 fragment
 */
public class DebugFragment extends MvpFragment<DebugPresenter> implements DebugView {
    private RecyclerView mRvDebugList;
    private DebugParameterAdapter mDebugParameterAdapter;
    private ThreadPoolDebugParameter mPoolDebugParameter = new ThreadPoolDebugParameter();
    private RecyclerView mRvDebugListX;
    private RecyclerView mRvDebugListY;
    private DebugParameterXAdapter mDebugParameterXAdapter;
    private DebugParameterYAdapter mDebugParameterYAdapter;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_debug, container, false);
        initView(inflate);
        initEvent();
        return inflate;
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        showLoading();
        mPoolDebugParameter.stopAll();
        mPoolDebugParameter.startALLRead();
    }

    @Override
    public void onDestroyView() {
        if (mPoolDebugParameter != null) {
            mPoolDebugParameter.stopAll();
        }
        Log.d(TAG, "onDestroyView: ");
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    private static final String TAG = "DebugFragment";

    private void initEvent() {
        mDebugParameterAdapter.setItemListener(new DebugParameterAdapter.ItemParaClickListener() {
            @Override
            public void onItemListener(View view, int position, String address) {
                showLoading();
                //点击的时候就开始写入
                //final String address = paraAddress[position];
                CheckBox checkBox = (CheckBox) view;
                if (!checkBox.isChecked()) {
                    mPoolDebugParameter.stopRst();
                    mPoolDebugParameter.startRst(address);
                } else {
                    mPoolDebugParameter.stopSet();
                    mPoolDebugParameter.startSet(address);
                }
            }
        });
    }

    private void initView(View inflate) {
        mRvDebugList = inflate.findViewById(R.id.rv_degbuglist);
        mRvDebugList.setItemViewCacheSize(29);
        mDebugParameterAdapter = new DebugParameterAdapter();
        GridLayoutManager layoutManager = new GridLayoutManager(BaseApplication.getContext(), 14, GridLayoutManager.HORIZONTAL, false);
        mRvDebugList.setAdapter(mDebugParameterAdapter);
        mRvDebugList.setLayoutManager(layoutManager);
        mRvDebugListX = inflate.findViewById(R.id.rv_x);
        mRvDebugListY = inflate.findViewById(R.id.rv_y);
        LinearLayoutManager layoutManagerx = new LinearLayoutManager(BaseApplication.getContext());
        LinearLayoutManager layoutManagery = new LinearLayoutManager(BaseApplication.getContext());
        mRvDebugListX.setLayoutManager(layoutManagerx);
        mRvDebugListX.addItemDecoration(new CustomDecoration(BaseApplication.getContext(), LinearLayoutManager.VERTICAL, 2));
        mRvDebugListY.setLayoutManager(layoutManagery);
        mRvDebugListY.addItemDecoration(new CustomDecoration(BaseApplication.getContext(), LinearLayoutManager.VERTICAL, 2));
        mDebugParameterXAdapter = new DebugParameterXAdapter();
        mDebugParameterYAdapter = new DebugParameterYAdapter();
        //缓存多少个才进行重新获取数据呢？ 23,24,可以进行设置
        mRvDebugListX.setItemViewCacheSize(27);
        mRvDebugListY.setItemViewCacheSize(24);
        mRvDebugListX.setAdapter(mDebugParameterXAdapter);
        mRvDebugListY.setAdapter(mDebugParameterYAdapter);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(Message messageEvent) {
        switch (messageEvent.getType()) {
            case connected:
                break;
            case sendError:
                break;
            case ack:
                mPoolDebugParameter.stopRst();
                mPoolDebugParameter.stopSet();
                Log.d(TAG, "event: 写入成功");
                hideLoading();
                break;
            case nak:
                break;
            case disconnected:
                SerialPortDevice device = new SerialPortDevice("/dev/ttyS2", "9600");
                SerialPortManager.getInstance().open(device);
                break;
            case response:
                ResponseFrame responseFrame = (ResponseFrame) messageEvent.getContent();
                String name = messageEvent.getName();
                if ("M600".equals(name)) {
                    return;
                }
                if (responseFrame.isValidSum()) {
                    String result = AsciiUtils.asciiByteArray2HexStr(responseFrame.getData());
                    mvpPresenter.setData(messageEvent, responseFrame, result, mPoolDebugParameter);
                    break;
                }
        }
    }

    @Override
    public void getDataSuccess() {
        getValue(mPoolDebugParameter.getValues());
    }

    @Override
    public void setXStatu(ArrayList<String> list2) {
        for (int i = 0; i < list2.size(); i++) {
            getXValue(list2, i, i, mRvDebugListX);
        }
    }

    @Override
    public void setYStatu(ArrayList<String> list2) {
        Log.d(TAG, "setYStatu: " + list2);
        for (int i = 0; i < list2.size(); i++) {
            getYValue(list2, i, i, mRvDebugListY);
        }
    }

    /**
     * 改变对应的状态
     *
     * @param lis      读取lpc返回值列表
     * @param index    lis对应的值
     * @param position 要改变的图片的位置
     */
    private void getXValue(final List<String> lis, final int index, int position, RecyclerView recyclerView) {
        //通过RecyclerView getChildAt();是不能正确获取item的view的，前几个获取可能还是正常的，往后滑后面的获取就不正常了
        //View view = recyclerView.getChildAt(position+1);
        View view = recyclerView.getLayoutManager().findViewByPosition(position + 1);
        if (view == null) {
            Log.d("空1", "getXYValue: p=" + position + "  index=" + index);
        } else {
            DebugParameterXAdapter.ViewHolder viewHolder = (DebugParameterXAdapter.ViewHolder) recyclerView.getChildViewHolder(view);
            if (lis.get(index).equals("1")) {
                viewHolder.ivState.setImageDrawable(UiUtil.getDrawableRes(R.drawable.shape_circle_oragnge));
            } else {
                viewHolder.ivState.setImageDrawable(UiUtil.getDrawableRes(R.drawable.shape_circle));
            }

        }


    }

    /**
     * 改变对应的状态
     *
     * @param lis      读取lpc返回值列表
     * @param index    lis对应的值
     * @param position 要改变的图片的位置
     */
    private void getYValue(final List<String> lis, final int index, int position, RecyclerView recyclerView) {
        View view = recyclerView.getLayoutManager().findViewByPosition(position + 1);
        if (view == null) {
            Log.d("空1", "getXYValue: p=" + position + "  index=" + index);
        } else {
            DebugParameterYAdapter.ViewHolder viewHolder = (DebugParameterYAdapter.ViewHolder) recyclerView.getChildViewHolder(view);
            if (lis.get(index).equals("1")) {
                viewHolder.ivState.setImageDrawable(UiUtil.getDrawableRes(R.drawable.shape_circle_oragnge));
            } else {
                viewHolder.ivState.setImageDrawable(UiUtil.getDrawableRes(R.drawable.shape_circle));
            }

        }


    }

    /**
     * 改变对应的状态
     *
     * @param value
     */
    @SuppressLint("ResourceAsColor")
    private void getValue(ArrayList<String> value) {
        //311-318
        for (int i = 0; i < value.size(); i++) {
            View view = mRvDebugList.getChildAt(i);
            if (null != mRvDebugList.getChildViewHolder(view)) {
                DebugParameterAdapter.ViewHolder viewHolder = (DebugParameterAdapter.ViewHolder) mRvDebugList.getChildViewHolder(view);
                if (i==1||i ==0) {
                    viewHolder.cbManual.setChecked(!viewHolder.cbManual.isChecked());
                    continue;
                }
                if (!value.get(i).equals("0")) {
                    //当它为选择状态时，无需设置，避免闪硕
                    if (!viewHolder.cbManual.isChecked()) {
                        viewHolder.cbManual.setChecked(true);
                    }
                } else {
                    if (viewHolder.cbManual.isChecked()) {
                        viewHolder.cbManual.setChecked(false);
                    }
                }

            }
        }

    }

    @Override
    protected DebugPresenter createPresenter() {
        return new DebugPresenter(this);
    }

    @Override
    public void showLoading() {
        showProgressDialog();
    }

    @Override
    public void hideLoading() {
        dismissProgressDialog();
    }

    public ProgressDialog progressDialog;

    public ProgressDialog showProgressDialog() {
        progressDialog = new ProgressDialog(mActivity);
        progressDialog.setMessage("加载中");
        progressDialog.show();
        return progressDialog;
    }

    public void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            // progressDialog.hide();会导致android.view.WindowLeaked
            progressDialog.dismiss();
        }
    }
}
