package xn.xxp;

import android.os.CountDownTimer;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;

import org.greenrobot.eventbus.EventBus;

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

import http.client.ApiRepository;
import http.vo.request.NoticeReq;
import http.vo.response.HomeRightResp;
import http.vo.response.LabBulletinBoardVo;
import http.vo.response.LabWarnVo;
import io.reactivex.rxjava3.functions.Consumer;
import xn.xxp.home.adapter.HomeBoardAdapter;
import xn.xxp.app.LabApp;
import xn.xxp.mqtt.event.WarningEvent;
import xn.xxp.room.RoomTool;
import xn.xxp.room.bean.NoticeSummary;
import xn.xxp.room.dao.NoticeSummaryDao;
import xn.xxp.utils.Tool;

public class HomeActivityHelp {
    private HomeActivity activity;
    // 心跳
    private CountDownTimer heartbeatCountDownTimer;

    public HomeActivityHelp(HomeActivity homePageActivity) {
        activity = homePageActivity;

        heartbeatCountDownTimer = new CountDownTimer(3000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                activity.addDisposable(ApiRepository.INSTANCE.heartbeat(activity.deviceConfig.getDevId()).subscribe(aBoolean -> {
                }, throwable -> {
                }));
                heartbeatCountDownTimer.start();
            }
        };
        heartbeatCountDownTimer.start();
    }

    public void onDestroy() {
        if (null != heartbeatCountDownTimer) {
            heartbeatCountDownTimer.cancel();
        }
    }

    /**
     * 刷卡响应
     */
    public void dispatchReadCardResult(String s) {
        activity.showLoading("加载中...");
        activity.addDisposable(ApiRepository.INSTANCE.getCardIsOpen(String.valueOf(activity.labConfig.getLabId()), s).subscribe(userVo -> {
            activity.dismissLoading();
            LabApp.userVo = userVo;
            Tool.INSTANCE.openDoor();
        }, onError));
    }


    /**
     * 查询首页右侧人员信息
     * 值班人员
     * 实验室人员
     * 准入人员
     */
    public void queryPerson() {
        activity.addDisposable(ApiRepository.INSTANCE.homeRightInfo(String.valueOf(activity.labConfig.getLabId())).subscribe(this::dispatchLabPerson, onError));
    }

    /**
     * 查询底部物联设备
     */
    public void queryBulletinBoard() {
        activity.addDisposable(ApiRepository.INSTANCE.functionList(String.valueOf(activity.labConfig.getLabId())).subscribe(this::dispatchLabDevice, throwable -> {
            activity.dismissLoading();
            LogUtils.e(Log.getStackTraceString(throwable));
            activity.showNetError(throwable);
            activity.homeBoardAdapter.setEmptyView(R.layout.view_list_empty);
        }));
    }

    public void queryWarnList() {
        activity.addDisposable(ApiRepository.INSTANCE.warnList(String.valueOf(activity.labConfig.getLabId())).subscribe(new Consumer<List<LabWarnVo>>() {
            @Override
            public void accept(List<LabWarnVo> labWarnVos) throws Throwable {
                EventBus.getDefault().post(new WarningEvent(labWarnVos));
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Throwable {
                LogUtils.e(Log.getStackTraceString(throwable));
            }
        }));
    }

    /**
     * 查询通知消息
     */
    public void queryNoticeMsgList() {
        NoticeReq noticeReq = new NoticeReq();
        List<Long> businessTypeList = new ArrayList<>() {
            {
                add(0L);
                add(1L);
                add(13L);
            }
        };
        noticeReq.setBusinessTypeList(businessTypeList);
        noticeReq.setSubIds(String.valueOf(activity.labConfig.getLabId()));
        noticeReq.setPage(1);
        noticeReq.setPageSize(100);
        activity.addDisposable(ApiRepository.INSTANCE.newMsgGroup(noticeReq).subscribe(noticeSummaryVoList -> {
            if (null != noticeSummaryVoList && !noticeSummaryVoList.isEmpty()) {
                NoticeSummaryDao noticeSummaryDao = RoomTool.getInstance().noticeSummaryDao();
                noticeSummaryDao.insert(noticeSummaryVoList.toArray(new NoticeSummary[0]));
            }
            activity.binding.titleBar.updateNotice(noticeSummaryVoList);
        }, onError));

    }

    private void queryWarning() {
        activity.addDisposable(ApiRepository.INSTANCE.warnList(String.valueOf(activity.labConfig.getLabId())).subscribe(new Consumer<List<LabWarnVo>>() {
            @Override
            public void accept(List<LabWarnVo> labWarnVos) throws Exception {
                activity.homeBoardAdapter.updateWaringValue(labWarnVos);
            }
        }, onError));
    }


    private void dispatchLabDevice(List<LabBulletinBoardVo> labBulletinBoardVos) {
        if (null != labBulletinBoardVos && !labBulletinBoardVos.isEmpty()) {
            if (null == activity.homeBoardAdapter) {
                activity.homeBoardAdapter = new HomeBoardAdapter();
            }
            activity.homeBoardAdapter.setNewInstance(labBulletinBoardVos);
            activity.binding.bulletinBoardView.initTimer(4, labBulletinBoardVos.size());
            activity.binding.bulletinBoardView.startAuto(3000);
            queryWarning();
        } else {
            activity.homeBoardAdapter.setEmptyView(R.layout.view_list_empty);
        }
    }


    private void dispatchLabPerson(HomeRightResp data) {
        // 值班人员
        if (null != data.dutyUser && !data.dutyUser.isEmpty()) {
            activity.personList.clear();
            activity.personList.addAll(data.dutyUser);
            activity.personFlipperAdapter.notifyDataSetChanged();
            activity.binding.dutyPerson.startFlipping();
        } else {
            activity.personList.clear();
            activity.personFlipperAdapter.notifyDataSetChanged();
            activity.binding.dutyPerson.stopFlipping();
        }
        // 实验人员
        if (null != data.tentativeUser && !data.tentativeUser.isEmpty()) {
            activity.experimentList.clear();
            activity.experimentList.addAll(data.tentativeUser);
            activity.experimentAdapter.notifyDataSetChanged();
            activity.binding.experimentPerson.startFlipping();
        } else {
            activity.experimentList.clear();
            activity.experimentAdapter.notifyDataSetChanged();
            activity.binding.experimentPerson.stopFlipping();
        }
        // 准入人员
        if (null != data.securityUser && !data.securityUser.isEmpty()) {
            activity.accessList.clear();
            activity.accessList.addAll(data.securityUser);
            activity.accessAdapter.notifyDataSetChanged();
            activity.binding.accessPerson.startFlipping();
        } else {
            activity.accessList.clear();
            activity.accessAdapter.notifyDataSetChanged();
            activity.binding.accessPerson.stopFlipping();
        }
    }


    private final Consumer<Throwable> onError = new Consumer<Throwable>() {
        @Override
        public void accept(Throwable throwable) throws Exception {
            activity.dismissLoading();
            activity.showNetError(throwable);
            LogUtils.e(Log.getStackTraceString(throwable));
        }
    };
}
