package com.example.iot_controlhost.utils.control.humidity;

import com.example.iot_controlhost.model.thread.QueueIOTask;
import com.example.iot_controlhost.utils.MyQueue;
import com.example.iot_controlhost.utils.MyUtil;
import com.example.iot_controlhost.utils.control.Control;
import com.example.iot_controlhost.utils.global.AIModelSet;
import com.example.iot_controlhost.utils.global.AutoModelSet;
import com.example.iot_controlhost.utils.global.RoomController;
import com.example.iot_controlhost.utils.global.RoomSensor;
import com.example.iot_controlhost.utils.global.RoomSetting;
import com.example.iot_controlhost.utils.global.RxTag;
import com.example.iot_controlhost.utils.global.SpinnerList;
import com.example.iot_controlhost.utils.global.Variable;
import com.example.iot_controlhost.utils.log.MyLog;
import com.example.iot_controlhost.utils.log.UserLog;
import com.xuexiang.rxutil2.rxjava.DisposablePool;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;

/**
 * @Description 自动模式-控制逻辑-湿度
 * @Author DuanKaiji
 * @CreateTime 2023年11月09日 10:25:43
 */
public class HumidityController extends Control {
    /**
     * 是否需要开启加湿器直到达到目标湿度
     */
    private static boolean needOpenToTarget = false;
    /**
     * 目标湿度
     */
    double target = 50;
    private static HumidityController instance;

    public static HumidityController getInstance() {
        if (instance == null) {
            synchronized (HumidityController.class) {
                if (instance == null) {
                    instance = new HumidityController();
                }
            }
        }
        return instance;
    }

    @Override
    protected boolean startMethod() {
        if (!RoomController.humidifier.isAvailable()) {
            MyLog.autoError("加湿器不可用，无法自动控制");
            return false;
        }
        pollingTask.startPollingTaskOnIOThread(RxTag.AUTO_HUMIDITY, Variable.AUTO_CHECK_TIME, () -> {
            double cur = RoomSensor.getAverageIndoorHumidity();
            double min = 0;
            double max = 0;
            if (RoomSetting.getMode() == 1) {
                target = AutoModelSet.getTargetHumidity();
                min = AutoModelSet.getMinHumidity();
                max = AutoModelSet.getMaxHumidity();
            } else if (RoomSetting.getMode() == 2) {
                target = AIModelSet.getTargetHumidity();
                min = target - Variable.AUTO_DO_NOTHING_HUMIDITY;
                max = target + Variable.AUTO_DO_NOTHING_HUMIDITY;
            }
            boolean needHumidify = false;
            boolean needDehumidify = false;
            if (cur < min //当前小于用户规定最小湿度
                    || cur < target - Variable.AUTO_DO_NOTHING_HUMIDITY //小于系统要求最小湿度
                    || cur < target && needOpenToTarget) { // 需要急剧加湿到目标湿度
                needOpenToTarget = true;
                needHumidify = true;
            } else {
                needOpenToTarget = false;
                needHumidify = false;
            }

            // 除湿逻辑（新增）
            if (cur > max) {
                needDehumidify = true;
            }
            // === 互斥处理 ===
            if (needHumidify && needDehumidify) {
                // 理论不会发生，保险处理
                needDehumidify = false;
            }
            boolean humidifierState = needHumidify;
            boolean dehumidifierState = needDehumidify;

            if (RoomController.humidifier.isPowerSupply() == humidifierState && RoomController.dehumidifier.isPowerSupply() == dehumidifierState) {
                MyLog.auto("湿度-控制维持当前状态");
            } else {
                // 加湿器控制
                if (RoomController.humidifier.isAvailable()) {
                    MyLog.auto("自动：" + (humidifierState ? "开启" : "关闭") + "加湿器--");
                    MyQueue.getInstance(MyQueue.TYPE_CONTROLLER).addTask(new QueueIOTask(() -> {
                        MyUtil.autoControlOperateThird(RoomController.humidifier, humidifierState);
                        String airExchangeMode = AutoModelSet.getAirExchangeMode();
                        if (RoomController.airExchange.isAvailable() && airExchangeMode.equals(SpinnerList.AIR_EXCHANGE_MODES[2])) {
                            MyUtil.autoControlOperateThird(RoomController.airExchange, humidifierState);
                        }
                    }));
                }
                // 除湿器控制（新增）
                if (RoomController.dehumidifier.isAvailable()) {
                    MyQueue.getInstance(MyQueue.TYPE_CONTROLLER).addTask(new QueueIOTask(() -> {
                        MyLog.auto("自动：" + (dehumidifierState ? "开启" : "关闭") + "除湿机--");
                        MyUtil.autoControlOperateThird(RoomController.dehumidifier, dehumidifierState);
                    }));
                }
            }
        });
        return true;
    }

    @Override
    protected void stopMethod() {
        MyQueue.getInstance(MyQueue.TYPE_CONTROLLER).addTask(new QueueIOTask(() -> {
            MyUtil.autoControlOperateThird(RoomController.humidifier);
            String airExchangeMode = AutoModelSet.getAirExchangeMode();
            if (RoomController.airExchange.isAvailable() && airExchangeMode.equals(SpinnerList.AIR_EXCHANGE_MODES[2])) {
                MyUtil.autoControlOperateThird(RoomController.airExchange, false);
            }
        }));
        MyLog.auto("停止自动控制湿度————————————————————————————————————————————————————");
        UserLog.operate("自动：停止自动控制湿度");
    }

}
