package com.sunzee.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hboxs.serialport.frame.ResponseFrame;
import com.hboxs.serialport.message.Message;
import com.hboxs.serialport.util.AsciiUtils;
import com.orhanobut.hawk.Hawk;
import com.sunzee.R;
import com.sunzee.base.MvpActivity;
import com.sunzee.model.Global;
import com.sunzee.model.Heartbeat;
import com.sunzee.model.HoleInformation;
import com.sunzee.model.domain.CleaningBean;
import com.sunzee.model.domain.HeartbeatBean;
import com.sunzee.model.domain.Name;
import com.sunzee.model.domain.ParameterBean;
import com.sunzee.mvp.homeactivity.HomePageAPresenter;
import com.sunzee.mvp.homeactivity.HomePageAView;
import com.sunzee.service.MyService;
import com.sunzee.thread.advanceparameter.ThreadPoolAdvanceParameter;
import com.sunzee.thread.homepageA.homepage.ThreadPoolHomepageA;
import com.sunzee.utils.AdvacedUtil;
import com.sunzee.utils.GeTuiUtil;
import com.sunzee.utils.HexadecimalUtil;
import com.sunzee.utils.LongClickUtils;
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.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 厕所状态 activity
 */
public class HomePageAActivity extends MvpActivity<HomePageAPresenter> implements HomePageAView {

    private static final String TAG = "AdvertisingActivity";
    private GeTuiUtil mGeTuiUtil;
    private TextView mTvTime;
    private MyHandler myHandler;
    private TextView mTvEquipmentNo;
    private ThreadPoolAdvanceParameter mPoolAdvanceParameter = new ThreadPoolAdvanceParameter();
    private ThreadPoolHomepageA threadPoolHomepageA = new ThreadPoolHomepageA();
    private TextView tvDate;
    private TextView tvWcToilets;
    private TextView tvWcUser;
    private TextView tvWcEmpty;
    private int use;
    private int empty;
    private CleaningBean cleaningBean;
    private TextView tvWashingTime;
    private TextView tvIn;
    private TextView tvOut;
    private TextView tvToiletdiagram1;
    private TextView tvToiletdiagram2;
    private TextView tvAmmonia;
    private TextView tvHumidity;
    private TextView tvTemperature;
    private CleaningBean yesterdayBean;
    private TextView tvYesterday;
    private List<String> useLastToiletsStatus;//上一次厕所的使用状态
    private TextView tvCompany;
    private TextView tvContacts;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homeactivity);
        EventBus.getDefault().register(this);
        //打开个推
        mGeTuiUtil = new GeTuiUtil(this);
        mGeTuiUtil.geTui();
        initView();
        initEvent();
        //获取实际屏幕参数
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
    }

    private void initEvent() {
        //长按事件
        LongClickUtils.setLongClick(new Handler(), tvDate, 2000, new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent intent = new Intent(HomePageAActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
                return false;
            }
        });
    }

    private void initView() {
        myHandler = new MyHandler(this);
        mTvTime = findViewById(R.id.tv_time1);
        tvDate = findViewById(R.id.tv_date);
        tvWcToilets = findViewById(R.id.tv_wctoilets);
        tvWcToilets.setText(MyService.TOTAL_SUM + "");
        tvWcUser = findViewById(R.id.tv_wcuser);
        tvWcEmpty = findViewById(R.id.tv_wcempty);
        tvWashingTime = findViewById(R.id.tv_washingtime);
        tvIn = findViewById(R.id.tv_in);
        tvYesterday = findViewById(R.id.tv_yesterday);
        tvOut = findViewById(R.id.tv_out);
        tvToiletdiagram1 = findViewById(R.id.tv_toiletdiagram1);
        tvToiletdiagram2 = findViewById(R.id.tv_toiletdiagram2);
        tvAmmonia = findViewById(R.id.tv_ammonia);
        tvHumidity = findViewById(R.id.tv_humidity);
        tvTemperature = findViewById(R.id.tv_temperature);
        tvCompany = findViewById(R.id.tv_company);
        tvContacts = findViewById(R.id.tv_contacts);
        //设备编号只显示6位
        mTvEquipmentNo = findViewById(R.id.tv_equipment_no1);
        if (Heartbeat.deviceId != null && Heartbeat.deviceId.length() > 7) {
            mTvEquipmentNo.setText(UiUtil.getStringRes(R.string.equipment) + (Heartbeat.deviceId != null ? Heartbeat.deviceId.substring(Heartbeat.deviceId.length() - 6) : ""));

        }
        //关闭RefreshTime、UserState
        stopRefreshTime();
        startRefreshime();
        startUserState();
        UpdatetUserState();
        //读取进阶参数
        mPoolAdvanceParameter.stopAll();
        mPoolAdvanceParameter.startALLRead();
        mPoolAdvanceParameter.stopReadD403();
        mPoolAdvanceParameter.startReadD403();
        threadPoolHomepageA.stopAll();
        threadPoolHomepageA.startAll();
        mvpPresenter.createBox(MyService.TOTAL_SUM);
        tvCompany.setText("公司："+Hawk.get(Name.COMPANY,""));
        tvContacts.setText("联系人："+Hawk.get(Name.WAYCONTACTS,""));
    }


    @Override
    public void updateTime(CharSequence sysTimeStr) {
        mTvTime.setText(sysTimeStr);
    }

    @Override
    public void getDataSuccess() {
        String[] values = mPoolAdvanceParameter.getValues();
        ArrayList<ParameterBean> parameterBeans = new ArrayList<>();
        String[] paraAddress = {
                "D426", "D427", "D428", "D429",
                "D430", "D431"};
        for (int i = 0; i < paraAddress.length; i++) {
            parameterBeans.add(new ParameterBean(paraAddress[i], values[i]));
        }
        mvpPresenter.updateAdvanced(parameterBeans);
    }

    @Override
    protected void onStop() {
        super.onStop();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        stopRefreshTime();
        mPoolAdvanceParameter.stopAll();
        threadPoolHomepageA.stopALLRead();
        myHandler.removeCallbacksAndMessages(null);
        myHandler = null;
    }

    private long mPressTime = 0L;

    /**
     * 两次点击才能退出
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mPressTime < 1000) {
                finish();
            } else {
                ToastUtil.showToast("再按一次退出");
                mPressTime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(Message messageEvent) {
        switch (messageEvent.getType()) {
            case connected:
            case sendError:
            case ack:
                break;
            case nak:
                break;
            case disconnected:
                break;
            case response:
                ResponseFrame responseFrame = (ResponseFrame) messageEvent.getContent();
                String name = messageEvent.getName();
                if ("M600".equals(name)) {
                    return;
                }
                if (responseFrame.isValidSum()) {
                    //通过校验
                    Log.d(TAG, "11event: " + name);
                    String result = AsciiUtils.asciiByteArray2HexStr(responseFrame.getData());
                    ArrayList<String> results = HexadecimalUtil.flipString(result);
                    if ("D403".equals(name)) {
                        mPoolAdvanceParameter.stopReadD403();
                        Log.d(TAG, "11event: " + (int) HexadecimalUtil.hex2dec(results.get(0)));
                        mvpPresenter.sendPositionNum((int) HexadecimalUtil.hex2dec(results.get(0)));
                    } else if ("D169".equals(name)) {
                        Heartbeat.cabinetTm = String.valueOf(HexadecimalUtil.hex2dec(results.get(0)) / 10);
                        tvTemperature.setText(Heartbeat.cabinetTm + "°C");
                    } else if ("D170".equals(name)) {
                        Heartbeat.cabinetHd = String.valueOf(HexadecimalUtil.hex2dec(results.get(0)) / 10);
                        tvHumidity.setText(Heartbeat.cabinetHd + "%");
                    } else if ("D172".equals(name)) {
                        try {
                            Integer integer = Integer.valueOf(getRealData(results));
                            if (integer < 0) {
                                Heartbeat.odorConcentration = 0;
                            } else {
                                Heartbeat.odorConcentration = integer;
                            }
                        } catch (Exception e) {
                        }
                        ;
                        tvAmmonia.setText(Heartbeat.odorConcentration + "");
                    } else {
                        mvpPresenter.setAdvanced(name, results, mPoolAdvanceParameter);
                    }
                }
                break;
        }
    }
    //变化的时候，有没有超过30秒

    private String getRealData(ArrayList<String> results) {
        String realData = "";
        String s = String.valueOf(HexadecimalUtil.hex2dec(results.get(0)));
        Integer integer = Integer.valueOf(s);
        long l = HexadecimalUtil.hex2dec(results.get(0));
        //2进制
        String s1 = Integer.toBinaryString(integer);
        if (s1.length() < 16) {
            //正数
            realData = String.valueOf(Math.round((l / Global.num) * 10));
        } else {
            //负数
            realData = AdvacedUtil.getRealData(s1);
        }
        return realData;
    }

    @Override
    protected HomePageAPresenter createPresenter() {
        HomePageAPresenter advertisingPresenter = new HomePageAPresenter(this);
        advertisingPresenter.requstCleanRule();
        advertisingPresenter.requestCleanTimeAndRemaining();
        return advertisingPresenter;
    }

    /**
     * 主要用于更新系统时间
     */
    public static class MyHandler extends Handler {
        //持有弱引用HandlerActivity,GC回收时会被回收掉.
        private final WeakReference<HomePageAActivity> mActivty;

        public MyHandler(HomePageAActivity activity) {
            mActivty = new WeakReference<HomePageAActivity>(activity);
        }

        @SuppressLint("ResourceAsColor")
        @Override
        public void handleMessage(android.os.Message msg) {
            HomePageAActivity activity = mActivty.get();
            switch (msg.what) {
                case 1:
                    long sysTime = System.currentTimeMillis();//获取系统时间
                    SimpleDateFormat myFmt = new SimpleDateFormat("yyyy年MM月dd日 EEEE HH:mm:ss");//时间显示格式
                    String sysTimeStr = myFmt.format(sysTime);
                    activity.tvDate.setText(sysTimeStr);
                    break;
                case 2://厕所的使用状态。
                    //使用个数，空置个数
                    activity.tvWcUser.setText(activity.use + "");
                    activity.tvWcEmpty.setText(activity.empty + "");
                    //厕所示意图
                    if (MyService.sHoleInformationList.size() >= 0) {
                        if (MyService.sHoleInformationList.get(0).isUserAndEmpty()) {
                            activity.tvToiletdiagram1.setBackgroundResource(R.drawable.shape_home_mannedtoilet);
                            activity.tvToiletdiagram1.setText("有人");
                            activity.tvToiletdiagram1.setTextColor(Color.WHITE);
                        } else {
                            activity.tvToiletdiagram1.setBackgroundResource(R.drawable.icon9);
                            activity.tvToiletdiagram1.setText("无人");
                            activity.tvToiletdiagram1.setTextColor(activity.getResources().getColor(R.color.state_green));
                        }
                        if (MyService.sHoleInformationList.get(1).isUserAndEmpty()) {
                            activity.tvToiletdiagram2.setBackgroundResource(R.drawable.shape_home_mannedtoilet);
                            activity.tvToiletdiagram2.setText("有人");
                            activity.tvToiletdiagram2.setTextColor(Color.WHITE);
                        } else {
                            activity.tvToiletdiagram2.setBackgroundResource(R.drawable.icon9);
                            activity.tvToiletdiagram2.setText("无人");
                            activity.tvToiletdiagram2.setTextColor(activity.getResources().getColor(R.color.state_green));
                        }
                    }
                    break;
                case 3://清洗次数的读取。
                    activity.tvIn.setText(activity.cleaningBean.getInCount());
                    activity.tvOut.setText(activity.cleaningBean.getOutCount());
                    if (activity.yesterdayBean != null) {
                        activity.tvYesterday.setText("昨日合计”进“：" + activity.yesterdayBean.getInCount());
                    }
                    activity.tvWashingTime.setText(activity.cleaningBean.getCleanCount());

                    break;
            }
        }
    }

    private Timer timerGetTime;
    private TimerTask timerGetTimerTak;

    //时间日期的更新
    private void startRefreshime() {
        timerGetTime = new Timer();
        timerGetTimerTak = new TimerTask() {
            @Override
            public void run() {
                if (myHandler != null) {
                    myHandler.sendEmptyMessage(1);
                }
            }
        };
        timerGetTime.schedule(timerGetTimerTak, 0, 1000);
    }


    private Timer timerUseState;
    private TimerTask timerUseStateTimerTak;

    //厕所使用状态的更新
    private void startUserState() {
        timerUseState = new Timer();
        timerUseStateTimerTak = new TimerTask() {
            @Override
            public void run() {
                //查看使用状态和空置状态
                showUseEmptyWC();
                //初始化数据 //取出数据 --- 查询数据库数据----- 取出今天的清洗次数
                queryTodayCleanCount();
            }
        };
        timerUseState.schedule(timerUseStateTimerTak, 0, 2000);
    }


    private Timer timerUpdateUseState;
    private TimerTask timerUpdateUseStateTimerTak;

    //上传厕所使用状态的更新
    private void UpdatetUserState() {
        timerUpdateUseState = new Timer();
        timerUpdateUseStateTimerTak = new TimerTask() {
            @Override
            public void run() {
                //上传厕所状态

                if (useLastToiletsStatus==null) {
                    useLastToiletsStatus = new ArrayList<>();
                    for (int i = 0; i < MyService.TOTAL_SUM; i++) {
                        useLastToiletsStatus.add("5");
                    }
                   return;
                }
                synchronized (MyService.sCleaningLocationList) {
                    if (MyService.sHoleInformationList != null&& MyService.sHoleInformationList.size()>0) {
                        for (int i = 0; i < MyService.TOTAL_SUM; i++) {
                            String userStates = MyService.sHoleInformationList.get(i).getUserStates();
                            Log.d(TAG, "useLastToiletsStatusrun1: "+useLastToiletsStatus.get(i));
                            Log.d(TAG, "userStatesrun1: "+userStates);
                            if (!useLastToiletsStatus.get(i).equals(userStates)) {
                                mvpPresenter.sendStatusOfToiletUse((i+1)+"号",userStates);
                                useLastToiletsStatus.add(i,userStates);
                            }
                        }
                    }
                }
            }
        };
        timerUpdateUseState.schedule(timerUpdateUseStateTimerTak, 0, 3000);
    }


    /**
     * 查询今天的使用次数
     */
    private void queryTodayCleanCount() {
        CleaningBean bean = mvpPresenter.queryTodayCleanCount(0, 1);
        CleaningBean yesterday = mvpPresenter.queryTodayCleanCount(-1, 0);
        if (bean != null) {
            this.yesterdayBean = yesterday;
            cleaningBean = bean;
            if (myHandler != null) {
                myHandler.sendEmptyMessage(3);
            }
        }


    }

    /**
     * 查看使用状态和空置状态
     */
    private void showUseEmptyWC() {
        if (MyService.sHoleInformationList != null) {
            use = 0;
            empty = 0;
            if (MyService.sCleaningLocationList != null) {
                synchronized (MyService.sCleaningLocationList) {
                    for (int i = 0; i < MyService.sHoleInformationList.size(); i++) {
                        HoleInformation holeInformation = MyService.sHoleInformationList.get(i);
                        if (holeInformation.isUserAndEmpty()) {//有人
                            use++;
                        } else {                                  //无人
                            empty++;
                        }
                        //发送太过频繁会导致出现问题。
                        //mvpPresenter.sendStatusOfToiletUse((i+1)+"号",holeInformation.getUserStates());
                    }
                    if (myHandler != null) {
                        myHandler.sendEmptyMessage(2);
                    }
                }
            }
        }
    }


    private void stopRefreshTime() {
        if (timerGetTime != null) {
            timerGetTime.cancel();
            timerGetTime = null;
        }
        if (timerGetTimerTak != null) {
            timerGetTimerTak.cancel();
            timerGetTimerTak = null;
        }

        if (timerUseState != null) {
            timerUseState.cancel();
            timerUseState = null;
        }

        if (timerUseStateTimerTak != null) {
            timerUseStateTimerTak.cancel();
            timerUseStateTimerTak = null;
        }

        if (timerUpdateUseState != null) {
            timerUpdateUseState.cancel();
            timerUpdateUseState = null;
        }
        if (timerUpdateUseStateTimerTak != null) {
            timerUpdateUseStateTimerTak.cancel();
            timerUpdateUseStateTimerTak = null;
        }
    }
}
