package com.example.iot_controlhost.ui.activity;


import android.app.Application;
import android.view.View;

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

import com.blankj.utilcode.util.GsonUtils;
import com.example.iot_controlhost.R;
import com.example.iot_controlhost.adapter.ModelsAdapter;
import com.example.iot_controlhost.base.BasePresenter;
import com.example.iot_controlhost.model.SingleLiveEvent;
import com.example.iot_controlhost.model.net.Token;
import com.example.iot_controlhost.model.net.WorkList;
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.global.HardwareSetting;
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.Variable;
import com.example.iot_controlhost.utils.log.MyLog;
import com.example.iot_controlhost.utils.log.UserLog;
import com.example.iot_controlhost.utils.network.TopicClass;
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.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.task.RxIOTask;

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

import java.util.ArrayList;

public class MainActivityPresenter extends BasePresenter {

    public static final String MODE_SOURCE_LOCAL = "本机屏幕";
    public static final String MODE_SOURCE_REMOTE = "远程控制";
    public static final String MODE_SOURCE_WORKFLOW = "作业流程";
    public static final String MODE_SOURCE_SYSTEM = "系统联动";

    private MutableLiveData<Integer> noticeLiveData = new SingleLiveEvent<>();
    private MutableLiveData<WorkList> workListMutableLiveData = new SingleLiveEvent<>();
    private MutableLiveData<Boolean> workNewListMutableLiveData = new SingleLiveEvent<>();
    public MutableLiveData<String> temperatureStr = new MutableLiveData<>();
    public MutableLiveData<String> temperatureStrOut = new MutableLiveData<>();
    public MutableLiveData<String> humidityStr = new MutableLiveData<>();
    public MutableLiveData<String> humidityStrOut = new MutableLiveData<>();
    public MutableLiveData<Boolean> roomEnable = new MutableLiveData<>(true);
    public MutableLiveData<String> roomName = new MutableLiveData<>("正在加载中");
    public MutableLiveData<Integer> changeMode = new SingleLiveEvent<>();
    public MutableLiveData<String> noticeMessage = new SingleLiveEvent<>();
    public MutableLiveData<Boolean> isNoticeVisible = new MutableLiveData<>(false);

    public MainActivityPresenter(@NonNull Application application) {
        super(application);
        HardwareSetting.refreshMobileIdentifiers(getApplication());
        //更新数据
        RxJavaUtils.doInIOThread(new RxIOTask<>(null) {
            @Override
            public Void doInIOThread(Object x) {
                // 刷新共育状态
                pollingTask.startPollingTaskOnUIThread(RxTag.REFRESH_CUL_STATE,
                        Variable.REFRESH_CULTURE_STATE_TIME, () -> noticeLiveData.setValue(11));
                //更新主界面UI
                pollingTask.startPollingTaskOnIOThread(RxTag.MAIN_UI, 5, () -> {
                    temperatureStr.postValue(String.valueOf(RoomSensor.getAverageIndoorTemperature()));
                    humidityStr.postValue(String.valueOf(RoomSensor.getAverageIndoorHumidity()));
                    temperatureStrOut.postValue(String.valueOf(RoomSensor.outdoorTHSensor.temperature));
                    humidityStrOut.postValue(String.valueOf(RoomSensor.outdoorTHSensor.humidity));
                });
                //上报信息
                pollingTask.startPollingTaskOnIOThread(RxTag.MAIN_UPLOAD, Variable.UPLOAD_SENSOR_DATA_TIME, () -> {
                    TopicClass.uploadSensorData();//上报传感器信息
                    TopicClass.uploadAreaCustomData();//上传传感器细则信息
                    TopicClass.uploadDeviceState(false);//每隔10s 自动上报（不同的）设备状态
                    TopicClass.areaEnergyData();//上报能耗数据
                });
                //更新主界面UI
                RxBusUtils.get().onMainThread(RxTag.UPDATE_MAIN, Integer.class, i -> {
                    switch (i) {
                        case 1 -> {
                            //设置为区域可用性
                            MyLog.app("远程设置房间：" + (RoomSetting.isRoomEnable() ? "可用" : "不可用"));
                            roomEnable.setValue(RoomSetting.isRoomEnable());
                            // 更新房间名
                            roomName.setValue(RoomSetting.getRoomName());
                            if (!RoomSetting.isRoomEnable()) {
                                //刷新切换为手动模式
                                initMode(0, MODE_SOURCE_REMOTE + "-区域禁用联动");
                            }
                        }
                        case 3 -> //刷新切换为自动模式
                                initMode(1, MODE_SOURCE_WORKFLOW);
                        case 5 -> //刷新切换为手动模式
                                initMode(0, MODE_SOURCE_WORKFLOW);
                        case 6 -> //刷新切换为智能模式
                                initMode(2, MODE_SOURCE_SYSTEM);
                        case 13 -> //远程切换为自动模式
                                initMode(1, MODE_SOURCE_REMOTE);
                        case 15 -> //远程切换为手动模式
                                initMode(0, MODE_SOURCE_REMOTE);
                        case 16 -> //远程切换为智能模式
                                initMode(2, MODE_SOURCE_REMOTE);
                        case 7 -> //刷新共育信息 并刷新模式
                                noticeLiveData.setValue(10);
                    }
                });
                RxBusUtils.get().onMainThread(RxTag.UPDATE_MAIN_MSG, String.class, msg -> {
                    noticeMessage(msg);
                });
                return null;
            }
        });
        roomName.setValue(RoomSetting.getRoomName());
        refreshToken();
    }

    /**
     * 进入新模式
     *
     * @param targetMode 新模式
     */
    public void initMode(int targetMode) {
        initMode(targetMode, MODE_SOURCE_SYSTEM);
    }

    public void initMode(int targetMode, String source) {
        int previousMode = RoomSetting.getMode();
        String previousModeName = getModeName(previousMode);
        String modeName = getModeName(targetMode);
        if (previousMode == targetMode) {
            MyLog.app("模式切换未执行：来源=" + source + "，当前已是" + modeName);
            return;
        }
        showLoadingDialog("正在切换为" + modeName + "中");
        MyQueue.start(MyQueue.TYPE_CONTROLLER, new QueueIOUITask<ModeChangeResult>() {
            @Override
            public ModeChangeResult doInQueueThread() {
                try {
                    ModelsAdapter.getModeByPosition(previousMode).stopMode();
                    MMKVUtil.put(RoomSetting.MODE, targetMode);
                    return ModeChangeResult.success();
                } catch (Exception e) {
                    return ModeChangeResult.failure(e.getMessage());
                }
            }

            @Override
            public void doInUIThread(ModeChangeResult result) {
                if (result.success) {
                    try {
                        changeMode.setValue(targetMode);
                        ModelsAdapter.getModeByPosition(targetMode).initMode();
                        UserLog.operate(source, "模式切换成功：" + previousModeName + " → " + modeName);
                    } catch (Exception e) {
                        UserLog.operateError(source, "模式切换失败：" + previousModeName + " → " + modeName);
                        MyLog.appError("模式切换后初始化失败：来源=" + source + "，" + previousModeName
                                + " → " + modeName + "，原因=" + e.getMessage());
                        errorTips("模式初始化失败，请检查设备状态");
                    }
                } else {
                    UserLog.operateError(source, "模式切换失败：" + previousModeName + " → " + modeName);
                    MyLog.appError("模式切换失败：来源=" + source + "，" + previousModeName + " → "
                            + modeName + "，原因=" + result.message);
                    errorTips("模式切换失败，请稍后重试");
                }
                hideLoadingDialog();
            }
        });
    }

    private String getModeName(int mode) {
        return switch (mode) {
            case 0 -> "手动模式";
            case 1 -> "自动模式";
            case 2 -> "智能模式";
            default -> "未知模式(" + mode + ")";
        };
    }

    private static class ModeChangeResult {
        private final boolean success;
        private final String message;

        private ModeChangeResult(boolean success, String message) {
            this.success = success;
            this.message = message;
        }

        private static ModeChangeResult success() {
            return new ModeChangeResult(true, null);
        }

        private static ModeChangeResult failure(String message) {
            return new ModeChangeResult(false, message == null ? "未知异常" : message);
        }
    }


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

    public MutableLiveData<WorkList> getWorkListMutableLiveData() {
        return workListMutableLiveData;
    }

    public MutableLiveData<Boolean> getNewWorkListMutableLiveData() {
        return workNewListMutableLiveData;
    }

    public MutableLiveData<Integer> getChangeMode() {
        return changeMode;
    }

    public void notice(View view) {
        int viewId = view.getId();
        if (viewId == R.id.main_lock) {
            // 锁屏
            noticeLiveData.setValue(2);
        } else if (viewId == R.id.btn_info) {
            // 基础信息
            noticeLiveData.setValue(5);
        } else if (viewId == R.id.btn_sign) {
            // 操作登记
            if (RoomSetting.getWorkState() == null) {
                // 开始登记
                getWorkList();
            } else {
                // 结束登记
                noticeLiveData.setValue(4);
                // MyLog.test("当前作业名：" + RoomSetting.getWorkState().get("name"));
                // MyLog.test("当前作业码：" + RoomSetting.getWorkState().get("data"));
            }
        } else if (viewId == R.id.btn_sign_new) {
                // 开始登记
                workNewListMutableLiveData.setValue(true);
        } else if (viewId == R.id.btn_set) {
            // 设置
            noticeLiveData.setValue(3);
        } else if (viewId == R.id.btn_manual) {
            // 切换为手动模式 核心
            if (RoomSetting.getMode() != 0) {
                noticeLiveData.setValue(7);
            }
        } else if (viewId == R.id.btn_auto) {
            // 切换为自动模式
            if (RoomSetting.getMode() != 1) {
                noticeLiveData.setValue(8);
            }
        } else if (viewId == R.id.btn_intelligence) {
            // 切换为智能模式
            if (RoomSetting.getMode() != 2) {
                noticeLiveData.setValue(9);
            }
        }
    }

    /**
     * 通知方法，更新主界面下方通知内容
     *
     * @param msg 消息
     */
    private void noticeMessage(String msg) {
        isNoticeVisible.setValue(true);
        noticeMessage.setValue(msg);
    }

    /**
     * 获取工作登记列表-网络请求
     */
    public void getWorkList() {
        showLoadingDialog("正在读取作业列表中...");
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.getWorkList);
        params.addParameter("areaCode", RoomSetting.getAreaCode());
        x.http().get(params, new XHttpShorthand<WorkList>() {
            @Override
            public void success(WorkList model) {
                // json转对象
                workListMutableLiveData.setValue(model);
            }

            @Override
            public void error(Throwable e) {
                errorTips("作业列表获取失败，请检查网络");
                UserLog.taskError("作业列表获取失败");
                MyLog.networkError("作业列表获取失败：" + e.getMessage());
            }

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

    /**
     * 获取Token
     */
    public void refreshToken() {
        pollingTask.startPollingTaskOnIOThread(RxTag.GET_TOKEN, 60 * 60, () -> {
            RequestParams params = XHttpManager.getInstance().getRequestParams(Url.getToken);
            params.addParameter("Account", "bbitiotcontrol");
            params.addParameter("Password", "jA7@mD1?");
            x.http().post(params, new XHttpShorthand<Token>() {
                @Override
                public void success(Token model) {
                    MyLog.app("Token获取成功");
                    MMKVUtil.put(RoomSetting.TOKEN, model.getTokenType() + " " + model.getAccessToken());
                }

                @Override
                public void error(Throwable e) {
                    MyLog.appError("Token获取失败");
                }

            });
        });
    }

}
