package com.sunzee.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.hboxs.serialport.SerialPortDevice;
import com.hboxs.serialport.SerialPortManager;
import com.hboxs.serialport.SerialPortSendQueue;
import com.hboxs.serialport.frame.ResponseFrame;
import com.hboxs.serialport.frame.WriteCommandFrame;
import com.hboxs.serialport.message.Message;
import com.hboxs.serialport.util.HexUtils;
import com.orhanobut.hawk.Hawk;
import com.sunzee.R;
import com.sunzee.base.MvpFragment;
import com.sunzee.mvp.homepage.HomePagePresenter;
import com.sunzee.mvp.homepage.HomePageView;
import com.sunzee.thread.homepage.ThreadPoolHomepage;
import com.sunzee.ui.dialog.StartCleaningDialog;
import com.sunzee.ui.view.CustomViewGrounp;
import com.sunzee.utils.PreventSpeedClickUtil;
import com.sunzee.utils.ToastUtil;

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

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

/**
 * 后台首页界面 fragment
 */
public class HomepageFragment extends MvpFragment<HomePagePresenter> implements HomePageView, CustomViewGrounp.onClickCleaning {

    private CustomViewGrounp mCustomViewGrounp;
    private TextView mTvCommit;
    private StartCleaningDialog mStartCleaningDialog;
    private PreventSpeedClickUtil mPreventSpeedClickUtil;
    private ThreadPoolHomepage mThreadPoolHomepage = new ThreadPoolHomepage();
    private int cleaningLocation = 1;

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

    private void initEvent() {
        mTvCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //保存位置
                Map<String, List<Float>> integerMap = mCustomViewGrounp.getIntegerMap1();
                if (integerMap.size() == 0) {
                    return;
                }
                Map<String, List<Float>> location = Hawk.get("location", null);
                Log.d(TAG, "onClick: "+location);
                if (location != null) {
                    //给控件新位置，替换之前的位置。
                    for (String s : location.keySet()) {
                        Log.d(TAG, "onClick: "+s );
                        if (integerMap.containsKey(s)) {
                            location.put(s, integerMap.get(s));
                        }
                    }
                    //没有变化过位置的也加进去。
                    for (String s : integerMap.keySet()) {
                        Log.d(TAG, "onClick: "+s );
                        if (!location.containsKey(s)) {
                            location.put(s, integerMap.get(s));
                        }
                    }
                    Hawk.put("location", location);
                } else {
                    Hawk.put("location", integerMap);
                }
                ToastUtil.showToast("保存成功");
            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mThreadPoolHomepage.stopALLRead();
        EventBus.getDefault().unregister(this);
    }

    private static final String TAG = "HomepageFragment";

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(Message messageEvent) {
        switch (messageEvent.getType()) {
            case connected:
                Log.d(TAG, "event: connected");
                break;
            case sendError:
                Log.d(TAG, "event: sendError");
                break;
            case ack:
                Log.d(TAG, "event: 写入成功" + messageEvent.getName());
                if (messageEvent.getName().equals("D120")) {
                    mThreadPoolHomepage.stopWriteD120();
                    mThreadPoolHomepage.stopSetM8();
                    mThreadPoolHomepage.startSetM8();
                } else if (messageEvent.getName().equals("M8")) {
                    mThreadPoolHomepage.stopSetM8();
                }
                break;
            case nak:
                Log.d(TAG, "event: nak");
                break;
            case disconnected:
                SerialPortDevice device = new SerialPortDevice("/dev/ttyS2", "9600");
                SerialPortManager.getInstance().open(device);
                Log.d(TAG, "event: disconnected");
                break;
            case response:
                ResponseFrame responseFrame = (ResponseFrame) messageEvent.getContent();
                String name = messageEvent.getName();
                if ("M600".equals(name)) {
                    return;
                }
                break;
        }
    }

    private void initView(View inflate) {
        //为控件设置数据
        mCustomViewGrounp = inflate.findViewById(R.id.cv_custom);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            if (i == 6) {
                list.add("走廊");
                continue;
            } else if (i == 7) {
                list.add("洗手台");
                continue;
            }
            list.add(i + 1 + "号厕所");
        }
        mCustomViewGrounp.setTextList(list);
        Map<String, List<Float>> location = Hawk.get("location", null);
        if (location != null) {
            for (int i = 0; i < mCustomViewGrounp.getChildCount(); i++) {
                List list1 = location.get(i + "");
                if (list1 == null) {
                    continue;
                }
                View childAt = mCustomViewGrounp.getChildAt(i);
                childAt.setX(Float.valueOf(String.valueOf(list1.get(0))));
                childAt.setY(Float.valueOf(String.valueOf(list1.get(1))));
            }
        }
        mCustomViewGrounp.setOnClickCleaning(this);
        mTvCommit = inflate.findViewById(R.id.tv_commit);
        mPreventSpeedClickUtil = new PreventSpeedClickUtil();
    }

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

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    //弹出对话框，是否要开始清洗。
    @Override
    public void setOnCLickCleaning(final int cleaningLocation) {
        //防止快速点击
        if (!mPreventSpeedClickUtil.isFastClick()) {
            return;
        }
        this.cleaningLocation = cleaningLocation;

        if (mStartCleaningDialog == null) {
            mStartCleaningDialog = new StartCleaningDialog(this.getContext());
        }
        mStartCleaningDialog.setListener(new StartCleaningDialog.DialogClickListener() {
            @Override
            public void onClickListener(int type) {
                switch (type) {
                    case R.id.btn_confirm:
                        //防止快速点击
                        if (!mPreventSpeedClickUtil.isFastClick500()) {
                            return;
                        }
                        //判断是否过期，或者是否次数以到。
                        showLoading();
                        mvpPresenter.isCanWrite();
                        mStartCleaningDialog.dismiss();
                        break;
                    case R.id.btn_cancel:
                        ToastUtil.showToast("取消");
                        mStartCleaningDialog.dismiss();
                        break;
                }
            }
        });
        mStartCleaningDialog.setBtnText(R.string.start_cleaning, R.string.start_cleaning_content, R.string.confirm, R.string.cancel);
        mStartCleaningDialog.show();

    }


    //开始写入清洗那个位置。
    private void startClean(int i) {
        //todo 判断是否过期和是否有次数。
        mThreadPoolHomepage.stopWriteD120();
        mThreadPoolHomepage.startWriteD120("D120", "000" + i);
    }

    @Override
    public void startClean() {
        hideLoading();
        startClean(cleaningLocation);
    }

    @Override
    public void haveExpired() {
        ToastUtil.showToast("已过期，请充值后使用哦。");
    }
}
