package com.example.iot_controlhost.ui.fragment;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.example.iot_controlhost.base.BasePresenter;
import com.example.iot_controlhost.model.AITHMode;
import com.example.iot_controlhost.model.SingleLiveEvent;
import com.example.iot_controlhost.model.net.AIMode;
import com.example.iot_controlhost.model.thread.QueueIOUITask;
import com.example.iot_controlhost.utils.MMKVUtil;
import com.example.iot_controlhost.utils.MyQueue;
import com.example.iot_controlhost.utils.control.disinfect.DisinfectController;
import com.example.iot_controlhost.utils.control.humidity.HumidityController;
import com.example.iot_controlhost.utils.control.temperature.TemperatureController;
import com.example.iot_controlhost.utils.control.temperature.strategy.GearControl;
import com.example.iot_controlhost.utils.control.ventilator.VentilatorController;
import com.example.iot_controlhost.utils.database.AITHModeDBManager;
import com.example.iot_controlhost.utils.database.MyAIModeUtil;
import com.example.iot_controlhost.utils.global.AIModelSet;
import com.example.iot_controlhost.utils.global.RoomSetting;
import com.example.iot_controlhost.utils.global.RxTag;
import com.example.iot_controlhost.utils.log.UserLog;
import com.example.iot_controlhost.utils.log.MyLog;
import com.example.iot_controlhost.utils.network.Url;
import com.example.iot_controlhost.utils.network.XHttpManager;
import com.example.iot_controlhost.utils.network.XHttpShorthand;
import com.xuexiang.rxutil2.rxbus.RxBusUtils;
import com.xuexiang.rxutil2.rxjava.DisposablePool;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;

import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

public class IntelligenceFragmentPresenter extends BasePresenter {

    private MutableLiveData<Integer> noticeLiveData = new SingleLiveEvent<>();

    public MutableLiveData<Integer> getNoticeLiveData() {
        return noticeLiveData;
    }

    public IntelligenceFragmentPresenter(@NonNull Application application) {
        super(application);
        RxBusUtils.get().onMainThread(RxTag.AI_INFO, Integer.class, i -> notice(7));
    }

    /**
     * 开始硬件操作
     * 能调用这个方法说明已经在共育中，所以不需要判断
     */
    public void startAICultivate() {
        showLoadingDialog("正在刷新模式中，请稍后...");
        if (MyAIModeUtil.getMyAiMode().size() > 0) {
            //有模板
            initAIMode();
        } else {
            //正在共育，但是没有模板，重新获取
            RequestParams params = XHttpManager.getInstance().getRequestParams(Url.getSilkwormTHTemplate);
            params.addParameter("intelligentControlProgramId", AIModelSet.getAiControlProgramId());
            x.http().get(params, new XHttpShorthand<AIMode>() {
                @Override
                public void success(AIMode model) {
                    AIMode.DataDTO data = model.getData();
                    MMKVUtil.put(AIModelSet.AI_SCHEME_NAME, data.getProgramName());
                    List<AITHMode> modes = data.getItems();
                    if (modes.size() > 0) {
                        AITHModeDBManager.insert(modes);
                        MyAIModeUtil.initMyAiMode(AITHModeDBManager.getAllSilkworms());
                        initAIMode();
                    } else {
                        successTips("该批次该蚕种暂无"+(RoomSetting.getType() == 4 ? "催青" : "共育")+"计划");
                    }
                }

                @Override
                public void error(Throwable e) {
                    e.printStackTrace();
                    errorTips("获取模板失败，请检查网络：" + e.getMessage());
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    hideLoadingDialog();
                }
            });
        }
    }

    /**
     * 在有模板的前提下初始化
     */
    private void initAIMode() {
        showLoadingDialog("正在加载模板中");
        MyQueue.start(MyQueue.TYPE_CONTROLLER, new QueueIOUITask<Object>() {
            @Override
            public Object doInQueueThread() throws Exception {
                //智能模式温控使用“分档位控制”算法
                TemperatureController.getInstance(new GearControl()).start();
                HumidityController.getInstance().start();
                VentilatorController.getInstance().start();
                DisinfectController.getInstance().start();
                // 刷新当前显示信息
                pollingTask.startPollingTaskOnIOThread(RxTag.AI_CULTIVATE, 2 * 60 * 60, () -> {
                    notice(7);
                });
//                DisposablePool.get().remove(RxTag.AI_CULTIVATE);
//                DisposablePool.get().add(RxTag.AI_CULTIVATE, RxJavaUtils.polling(2 * 60 * 60, aLong -> notice(7)));
                return null;
            }

            @Override
            public void doInUIThread(Object o) {
                hideLoadingDialog();
            }
        });
    }

    /**
     * 停止智能控制
     */
    public void stopIntelligenceControl() {
        TemperatureController.getInstance().stop();
        HumidityController.getInstance().stop();
        VentilatorController.getInstance().stop();
        DisinfectController.getInstance().stop();
    }

    /**
     * 开始/暂停共育
     */
    public void startStopCultivate() {
        if (AIModelSet.isAiProcessing()) {
            //要停止
            noticeLiveData.setValue(1);
        } else {
            //要进行
            MMKVUtil.put(AIModelSet.AI_PROCESSING, true);
            UserLog.operate("本机屏幕", "智能模式恢复运行");
            startAICultivate();
            noticeLiveData.setValue(8);
        }
    }

    public void confirmPauseCultivate() {
        MMKVUtil.put(AIModelSet.AI_PROCESSING, false);
        UserLog.operate("本机屏幕", "智能模式暂停成功，所有设备已关闭");
        noticeLiveData.postValue(8);
    }

    public void notice(int type) {
        noticeLiveData.postValue(type);
    }

    /**
     * 刷新模板
     */
    public void refreshTemplate() {
        showLoadingDialog("正在下载最新模板，请稍等...");
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.getSilkwormTHTemplate);
        params.addParameter("intelligentControlProgramId", AIModelSet.getAiControlProgramId());
        x.http().get(params, new XHttpShorthand<AIMode>() {
            @Override
            public void success(AIMode model) {
                AIMode.DataDTO data = model.getData();
                MMKVUtil.put(AIModelSet.AI_SCHEME_NAME, data.getProgramName());
                List<AITHMode> modes = data.getItems();
                AITHModeDBManager.insert(modes);
                MyAIModeUtil.initMyAiMode(AITHModeDBManager.getAllSilkworms());
                MMKVUtil.put(AIModelSet.AI_BIAS_TIME, 0);
                UserLog.operate("本机屏幕", "智能模式模板刷新成功：" + data.getProgramName());
                notice(7);
            }

            @Override
            public void error(Throwable e) {
                e.printStackTrace();
                UserLog.operateError("本机屏幕", "智能模式模板刷新失败");
                MyLog.networkError("智能模式模板刷新失败：" + e.getMessage());
                errorTips("模板获取失败，错误信息：\n" + e.getMessage());
            }

            @Override
            public void onFinish() {
                super.onFinish();
                hideLoadingDialog();
            }
        });
    }

}
