package com.example.iot_controlhost.ui.activity;

import android.app.Application;
import android.util.Pair;

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.base.BasePresenter;
import com.example.iot_controlhost.model.Device;
import com.example.iot_controlhost.model.Log;
import com.example.iot_controlhost.model.ParameterizedTypeImpl;
import com.example.iot_controlhost.model.SingleLiveEvent;
import com.example.iot_controlhost.model.controller.Controller;
import com.example.iot_controlhost.model.controller.Floor;
import com.example.iot_controlhost.model.controller.relay.Relay;
import com.example.iot_controlhost.model.net.AirConditionList;
import com.example.iot_controlhost.model.net.CommonResponse;
import com.example.iot_controlhost.model.net.WebSet;
import com.example.iot_controlhost.model.sensor.FloorTSensor;
import com.example.iot_controlhost.model.sensor.GasSensor;
import com.example.iot_controlhost.model.sensor.Sensor;
import com.example.iot_controlhost.model.sensor.THSensor;
import com.example.iot_controlhost.model.thread.QueueIOTask;
import com.example.iot_controlhost.model.thread.QueueIOUITask;
import com.example.iot_controlhost.utils.CsvConverter;
import com.example.iot_controlhost.utils.MMKVUtil;
import com.example.iot_controlhost.utils.MyQueue;
import com.example.iot_controlhost.utils.MyUtil;
import com.example.iot_controlhost.utils.database.dynamicSensor.IndoorAmmoniaSensorUtil;
import com.example.iot_controlhost.utils.database.dynamicSensor.IndoorCO2SensorUtil;
import com.example.iot_controlhost.utils.database.dynamicSensor.IndoorFloorTSensorUtil;
import com.example.iot_controlhost.utils.database.dynamicSensor.IndoorTHSensorUtil;
import com.example.iot_controlhost.utils.database.LogDBManager;
import com.example.iot_controlhost.utils.global.HardwareSetting;
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.Variable;
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.example.iot_controlhost.utils.old.OldSet;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.task.RxAsyncTask;

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

import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import android_serialport_api.SerialPortUtil;

public class SetActivityPresenter extends BasePresenter {

    public MutableLiveData<Integer> refreshLiveData = new SingleLiveEvent<>();
    public MutableLiveData<Pair<Integer, List<AirConditionList.DataDTO>>> showImportAirConditionInstructionDialogLiveData = new MutableLiveData<>();
    public MutableLiveData<List<AirConditionList.DataDTO>> showImportDehumidifierInstructionDialogLiveData = new MutableLiveData<>();

    public SetActivityPresenter(@NonNull Application application) {
        super(application);
    }

    public MutableLiveData<Integer> getRefreshLiveData() {
        return refreshLiveData;
    }

    public MutableLiveData<Pair<Integer, List<AirConditionList.DataDTO>>> getShowImportAirConditionInstructionDialogLiveData() {
        return showImportAirConditionInstructionDialogLiveData;
    }

    public MutableLiveData<List<AirConditionList.DataDTO>> getShowImportHumidifierInstructionDialogLiveData() {
        return showImportDehumidifierInstructionDialogLiveData;
    }

    /**
     * 地暖-自动设置PWM
     */
    public void autoSetFloorPWM() {
        showLoadingDialog("正在自动设置中，请耐心等待");
        //打开传感器与控制器串口
        if (SerialPortUtil.getInstance(SerialPortUtil.TYPE_SENSOR).openSerialPort() && SerialPortUtil.getInstance(SerialPortUtil.TYPE_CONTROLLER).openSerialPort()) {
            // 持续采集能耗信息
            pollingTask.startPollingTaskOnIOThread(RxTag.TAG_COLLECT_SENSOR_SET, 1, () -> RoomSensor.consumptionSensor.getAllSensorData());
        } else {
            MyLog.controllerError("串口打开失败，无法设置" + RoomSetting.getFloorName());
        }
        RxJavaUtils.executeAsyncTask(new RxAsyncTask<String, Boolean>(null) {
            @Override
            public Boolean doInIOThread(String str) {// 清空能耗传感器数据
                try {
                    RoomSensor.consumptionSensor.initData();
                    //获取当前最低功率
                    double minPower = RoomSensor.consumptionSensor.getPower();
                    int maxPWM = RoomController.floor.getMaxPower();
                    MyLog.controller(RoomSetting.getFloorName() + "打开最高功率，PWM值：" + maxPWM);
                    showLoadingDialogInIO("打开" + RoomSetting.getFloorName() + "最高功率，PWM值：" + maxPWM);
                    MyQueue.getInstance(MyQueue.TYPE_CONTROLLER).addTask(new QueueIOTask(() -> RoomController.floor.setGearByPWM(maxPWM)));
                    Thread.sleep(5000);
                    double maxPower = RoomSensor.consumptionSensor.getPower();
                    showLoadingDialogInIO("获取当前最高功率：" + maxPower + "\t最低功率：" + minPower);
                    MyLog.controller("获取当前最高功率：" + maxPower + "\t最低功率：" + minPower);
                    if (minPower >= maxPower || maxPower == 0) {
                        MyLog.controllerError("采集到的最高功率异常，已提前结束匹配。");
                        return false;
                    }
                    RoomController.floor.getPwm(5).setPwm(maxPWM);
                    RoomController.floor.getPwm(5).setPower(maxPower - minPower);
                    //获取调节功率偏差
                    double powerBias = maxPower * Variable.FLOOR_GEAR_BIAS;
                    MyLog.controller("获取调节功率偏差：" + powerBias);
                    //获得每级档位应该增加的功率
                    double avg = (maxPower - minPower) / 5.0;
                    MyLog.controller("获得每级档位应该增加的功率：" + avg);
                    //PWM逐渐增加 设置PWM
                    int PWM = 1000;
                    int temp = maxPWM / 30;
                    for (int i = 1; i < 5; i++) {
                        double targetPower = minPower + i * avg;
                        showLoadingDialogInIO(i + "档目标功率：" + targetPower);
                        MyLog.controller(i + "档目标功率：" + targetPower);
                        for (int pwm = PWM; pwm < maxPWM; pwm += temp) {
                            int finalPwm = pwm;
                            MyQueue.getInstance(MyQueue.TYPE_CONTROLLER).addTask(new QueueIOTask(() -> RoomController.floor.setGearByPWM(finalPwm)));
                            showLoadingDialogInIO("逐级增加等待读取最新功率，当前PWM值：" + pwm);
                            MyLog.controller("逐级增加等待读取最新功率，当前PWM值：" + pwm);
                            Thread.sleep(4000);
                            double curPower = RoomSensor.consumptionSensor.getPower();
                            MyLog.controller("最新功率：" + curPower);
                            showLoadingDialogInIO("最新功率：" + curPower);
                            if (curPower > targetPower - powerBias) {
                                //功率符合条件，则记录当前PWM和功率到对应档位信息中
                                showLoadingDialogInIO(curPower + "W功率符合条件，记录当前PWM和功率到" + i + "档信息中");
                                MyLog.controller("功率符合条件，记录当前PWM和功率到" + i + "档信息中");
                                RoomController.floor.getPwm(i).setPwm(pwm);
                                RoomController.floor.getPwm(i).setPower(curPower - minPower);
                                PWM = pwm;
                                break;
                            } else {
                                showLoadingDialogInIO("当前PWM值：" + pwm + "\t当前功率：" + curPower + "不符合要求\n" +
                                        "要求最小功率：" + (targetPower - powerBias));
                                MyLog.controller("当前PWM值：" + pwm + "\t当前功率：" + curPower + "不符合要求\n" +
                                        "要求最小功率：" + (targetPower - powerBias));
                            }
                        }
                    }
                    showLoadingDialogInIO("自动匹配完成");
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    return false;
                }
                pollingTask.stopPollingTask(RxTag.TAG_COLLECT_SENSOR_SET);
                RoomController.floor.setGear(0);
                MyLog.controller(RoomSetting.getFloorName() + "PWM自动匹配成功");
                return true;
            }

            @Override
            public void doInUIThread(Boolean success) {
                hideLoadingDialog();
                if (success) {
                    successTips(RoomSetting.getFloorName() + "PWM自动匹配成功");
                } else {
                    errorTips("采集到的最高功率异常，已提前结束匹配。\n请检查能耗传感器配置或" + RoomSetting.getFloorName() + "配置");
                }
                refreshLiveData.setValue(0);
            }
        });
    }

    /**
     * 获得空调型号列表
     *
     * @param airId 空调Id 第几个空调 为-1的时候是除湿机
     */
    public void getAirConditionModelList(int airId) {
        showLoadingDialog(getString(R.string.in_get_air_condition_model_list));
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.getAirConditionerModelList);
        x.http().get(params, new XHttpShorthand<AirConditionList>() {
            @Override
            public void success(AirConditionList model) {
                hideLoadingDialog();
                if (airId == -1) {
                    showImportDehumidifierInstructionDialogLiveData.setValue(model.getData());
                } else {
                    showImportAirConditionInstructionDialogLiveData.setValue(new Pair(airId, model.getData()));
                }
            }

            @Override
            public void error(Throwable e) {
                //获取空调型号列表失败
                errorTips("获取空调型号列表失败");
                hideLoadingDialog();
            }
        });
    }

    /**
     * 导入空调指令
     *
     * @param list               空调指令列表
     * @param targetAirCondition 目标空调型号
     * @param airId              空调Id
     */
    public void importAirConditionInstruction(List<AirConditionList.DataDTO> list, String targetAirCondition, int airId) {
        showLoadingDialog(getString(R.string.in_import_air_condition_instruction));
        String targetId = null;
        for (AirConditionList.DataDTO dataDTO : list) {
            if ((dataDTO.getBrand() + "-" + dataDTO.getModel()).equals(targetAirCondition)) {
                targetId = dataDTO.getId();
                break;
            }
        }

        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.getAirConditionerCommandList);
        params.addParameter("id", targetId);
        x.http().get(params, new XHttpShorthand<CommonResponse>() {
            @Override
            public void success(CommonResponse model) {
                String json = model.getData().toString();
                String unescapedJsonString = json.replace("\\\"", "\"");
                //成功获得列表
                List<String> instructions = GsonUtils.fromJson(unescapedJsonString, new ParameterizedTypeImpl(json.getClass()));
                //开始导入空调指令
                MyQueue.start(MyQueue.TYPE_CONTROLLER, new QueueIOUITask<Boolean>() {
                    @Override
                    public Boolean doInQueueThread() throws Exception {
                        boolean result = true;
                        if (!SerialPortUtil.getInstance(SerialPortUtil.TYPE_CONTROLLER).openSerialPort()) {
                            return false;
                        }
                        int size = instructions.size();
                        for (int i = 1; i <= size; i++) {
                            String instruction = instructions.get(i - 1);
                            if (MyUtil.checkInstruction(instruction)) {
                                if (airId == 1) {
                                    result = RoomController.airConditionInfrared.writeInstruction(i, instruction) && result;
                                } else {
                                    result = RoomController.airConditionInfrared2.writeInstruction(i, instruction) && result;
                                }
                                showLoadingDialogInIO("正在导入" + targetAirCondition + "型空调\n第" + i + "/" + size + "条指令");
                                MyLog.controller("正在导入第" + i + "/" + size + "条指令:" + instruction);
                            } else {
                                showLoadingDialogInIO("正在导入" + targetAirCondition + "型空调\n第" + i + "条，指令错误！！！");
                                MyLog.controller("正在导入第" + i + "条指令:" + "，云端指令有误");
                                Thread.sleep(100);
                            }
                        }
                        if (airId == 1) {
                            RoomController.airCondition.setAirConditionModel(targetAirCondition);
                        } else {
                            RoomController.airCondition.setAirConditionModel2(targetAirCondition);
                        }
                        return result;
                    }

                    @Override
                    public void doInUIThread(Boolean b) {
                        hideLoadingDialog();
                        if (b) {
                            successTips("成功导入所有空调指令");
                        } else {
                            errorTips("导入空调指令失败");
                        }
                        refreshLiveData.setValue(2);
                    }
                });
            }

            @Override
            public void error(Throwable e) {
                //获取空调指令列表失败
                hideLoadingDialog();
                errorTips("获取空调指令列表失败");
            }
        });
    }

    /**
     * 导入除湿机指令
     *
     * @param list               指令列表
     * @param targetAirCondition 目标空调型号
     */
    public void importDehumidifierInstruction(List<AirConditionList.DataDTO> list, String targetAirCondition) {
        showLoadingDialog(getString(R.string.in_import_air_condition_instruction));
        String targetId = null;
        for (AirConditionList.DataDTO dataDTO : list) {
            if ((dataDTO.getBrand() + "-" + dataDTO.getModel()).equals(targetAirCondition)) {
                targetId = dataDTO.getId();
                break;
            }
        }

        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.getAirConditionerCommandList);
        params.addParameter("id", targetId);
        x.http().get(params, new XHttpShorthand<CommonResponse>() {
            @Override
            public void success(CommonResponse model) {
                String json = model.getData().toString();
                String unescapedJsonString = json.replace("\\\"", "\"");
                //成功获得列表
                List<String> instructions = GsonUtils.fromJson(unescapedJsonString, new ParameterizedTypeImpl(json.getClass()));
                //开始导入指令
                MyQueue.start(MyQueue.TYPE_CONTROLLER, new QueueIOUITask<Boolean>() {
                    @Override
                    public Boolean doInQueueThread() throws Exception {
                        if (!SerialPortUtil.getInstance(SerialPortUtil.TYPE_CONTROLLER).openSerialPort()) {
                            return false;
                        }
                        // 只有开机关机两条指令
                        String openInstruction = instructions.get(0);
                        boolean result = RoomController.dehumidifierInfrared.writeInstruction(200, openInstruction);
                        if (!result) {
                            showLoadingDialogInIO("导入" + targetAirCondition + "型空调\n开机指令，指令错误！！！");
                            MyLog.controller("导入开机指令，云端指令有误");
                            Thread.sleep(100);
                            return false;
                        }
                        String closeInstruction = instructions.get(1);
                        result = RoomController.dehumidifierInfrared.writeInstruction(201, closeInstruction);
                        if (!result) {
                            showLoadingDialogInIO("导入" + targetAirCondition + "型空调\n关机指令，指令错误！！！");
                            MyLog.controller("导入关机指令，云端指令有误");
                            Thread.sleep(100);
                            return false;
                        }
                        RoomController.dehumidifierInfrared.setModel(targetAirCondition);
                        return result;
                    }

                    @Override
                    public void doInUIThread(Boolean b) {
                        hideLoadingDialog();
                        if (b) {
                            successTips("成功导入所有空调指令");
                        } else {
                            errorTips("导入空调指令失败");
                        }
                        refreshLiveData.setValue(4);
                    }
                });
            }

            @Override
            public void error(Throwable e) {
                //获取空调指令列表失败
                hideLoadingDialog();
                errorTips("获取空调指令列表失败");
            }
        });
    }

    /**
     * 导入配置
     */
    public void importSet(String selection) {
        if (selection.equals("预设")) {
            importDefaultSet();
        } else if (selection.equals("基地")) {
            importBaseSet();
        } else if (selection.equals("会东")) {
            importBaseSetHD();
        } else if (selection.equals("旧版本")) {
            OldSet.importOldSet(getApplication());
        } else if (selection.equals("兴文石海")) {
            importXWSKSet();
        } else if (selection.equals("主干继电器-从机模式")) {
            importBBITRelaySet();
        }
        successTips("成功导入<" + selection + ">配置");
    }

    /**
     * 主干继电器配置
     */
    private void importBBITRelaySet() {
        HardwareSetting.setSensorSerialCom("/dev/ttyS0");
        HardwareSetting.setSensorSerialComBaud("9600");
        HardwareSetting.setControllerSerialCom("/dev/ttyS8");
        HardwareSetting.setControllerSerialBaud("9600");
        //继电器配置
        RoomController.relay.setEnable(true);
        RoomController.relay.setAddress("01");
        RoomController.relay.setModel(RoomController.relay.getModels()[2]);
        RoomController.intakeFan.clearAndSetPort(1);
        RoomController.evenFan.clearAndSetPort(2);
        RoomController.airCondition.clearAndSetPort(3);
        RoomController.humidifier.clearAndSetPort(4);
        RoomController.relayFloor.clearAndSetPort(5);
        //空调默认配置
        RoomController.airConditionInfrared.setEnable(true);
        RoomController.airConditionInfrared.setModel(RoomController.airConditionInfrared.getModels()[0]);
        RoomController.airConditionInfrared.setAddress("02");
        //空调2默认配置
        RoomController.airConditionInfrared2.setEnable(false);
        RoomController.airConditionInfrared2.setModel(RoomController.airConditionInfrared2.getModels()[0]);
        RoomController.airConditionInfrared2.setAddress("02");
        //地暖默认配置
        RoomController.floor.setEnable(true);
        MMKVUtil.put(RoomSetting.FLOOR_NAME, "升温板");
        Floor.importDefaultPWMToFloor();
        //传感器配置
        THSensor thSensor1 = new THSensor("室内温湿度传感器1");
        thSensor1.setAddress("01");
        thSensor1.setEnable(true);
        IndoorTHSensorUtil.insert(thSensor1);
        THSensor thSensor2 = new THSensor("室内温湿度传感器2");
        thSensor2.setAddress("02");
        thSensor2.setEnable(true);
        IndoorTHSensorUtil.insert(thSensor2);
        RoomSensor.outdoorTHSensor.setAddress("03");
        RoomSensor.outdoorTHSensor.setEnable(true);
        GasSensor gasSensor = new GasSensor("室内CO2传感器1");
        gasSensor.setAddress("05");
        gasSensor.setEnable(true);
        IndoorCO2SensorUtil.insert(gasSensor);
    }

    /**
     * 兴文石海配置
     */
    private void importXWSKSet() {
        HardwareSetting.setControllerSerialCom("/dev/ttyS8");
        HardwareSetting.setSensorSerialCom("/dev/ttyS0");
        //继电器配置
        RoomController.relay.setEnable(true);
        RoomController.relay.setAddress("02");
        RoomController.relay.setModel(RoomController.relay.getModels()[1]);
        RoomController.intakeFan.clearAndSetPort(1);
        RoomController.humidifier.clearAndSetPort(2);
        RoomController.airCondition.clearAndSetPort(3);
        RoomController.exhaustFan.clearAndSetPort(4);
        RoomController.relayFloor.clearAndSetPort(5);
        //空调默认配置
        RoomController.airConditionInfrared.setEnable(true);
        RoomController.airConditionInfrared.setModel(RoomController.airConditionInfrared.getModels()[0]);
        RoomController.airConditionInfrared.setAddress("01");
        RoomController.airConditionInfrared2.setEnable(false);
        RoomController.airConditionInfrared2.setModel(RoomController.airConditionInfrared2.getModels()[0]);
        RoomController.airConditionInfrared2.setAddress("01");
        //地暖默认配置
        RoomController.floor.setEnable(true);
        Floor.importDefaultPWMToFloor();
        //传感器配置
        THSensor thSensor1 = new THSensor("室内温湿度传感器1");
        thSensor1.setAddress("01");
        thSensor1.setEnable(true);
        IndoorTHSensorUtil.insert(thSensor1);
        THSensor thSensor2 = new THSensor("室内温湿度传感器2");
        thSensor2.setAddress("02");
        thSensor2.setEnable(true);
        IndoorTHSensorUtil.insert(thSensor2);
        RoomSensor.outdoorTHSensor.setAddress("03");
        RoomSensor.outdoorTHSensor.setEnable(true);
        RoomSensor.consumptionSensor.setAddress("04");
        RoomSensor.consumptionSensor.setEnable(true);
        GasSensor gasSensor = new GasSensor("室内CO2传感器1");
        gasSensor.setAddress("05");
        gasSensor.setEnable(true);
        IndoorCO2SensorUtil.insert(gasSensor);
        FloorTSensor floorTSensor = new FloorTSensor("地面温度传感器");
        floorTSensor.setAddress("06");
        floorTSensor.setEnable(true);
        IndoorFloorTSensorUtil.insert(floorTSensor);
    }

    /**
     * 旧系统配置-公司
     */
    public void importDefaultSet() {
        //控制器默认配置
        Controller.setControllerModel(Controller.CONTROLLER_MODEL[0]);
        HardwareSetting.setWorkMode(HardwareSetting.CONTROLLER_WORK_MODE[0]);
        HardwareSetting.setControllerSerialCom("/dev/ttyS5");
        HardwareSetting.setControllerSerialBaud("9600");
        HardwareSetting.setSensorSerialCom("/dev/ttyS1");
        HardwareSetting.setSensorSerialComBaud("9600");
        //继电器配置
        RoomController.relay.setEnable(true);
        RoomController.relay.setAddress("02");
        RoomController.relay.setModel(RoomController.relay.getModels()[0]);
        RoomController.relayFloor.clearAllPort();
        RoomController.airCondition.clearAndSetPort(1);
        RoomController.humidifier.clearAndSetPort(2);
        RoomController.intakeFan.clearAndSetPort(3);
        RoomController.evenFan.clearAndSetPort(4);
        RoomController.exhaustFan.clearAndSetPort(5);
        RoomController.redLight.clearAndSetPort(6);
        RoomController.whiteLight.clearAndSetPort(7);
        RoomController.uvLight.clearAndSetPort(8);
        //空调默认配置
        RoomController.airConditionInfrared.setEnable(true);
        RoomController.airConditionInfrared.setModel(RoomController.airConditionInfrared.getModels()[0]);
        RoomController.airConditionInfrared.setAddress("01");
        //地暖默认配置
        RoomController.floor.setEnable(true);
        RoomController.floor.setModel(RoomController.floor.getModels()[0]);
        RoomController.floor.setAddress("05");
        RoomController.floor.setMaxGear(5);
        Floor.importDefaultPWMToFloor();
        //初始化传感器型号为默认型号
        for (Sensor sensor : RoomSensor.getAllSensors()) {
            sensor.setModel(sensor.getModels()[0]);
        }
        //传感器配置
        THSensor thSensor1 = new THSensor("室内温湿度传感器1");
        thSensor1.setAddress("01");
        thSensor1.setEnable(true);
        IndoorTHSensorUtil.insert(thSensor1);
        THSensor thSensor2 = new THSensor("室内温湿度传感器2");
        thSensor2.setAddress("02");
        thSensor2.setEnable(true);
        IndoorTHSensorUtil.insert(thSensor2);
        RoomSensor.outdoorTHSensor.setAddress("03");
        RoomSensor.outdoorTHSensor.setEnable(true);
        RoomSensor.consumptionSensor.setAddress("04");
        RoomSensor.consumptionSensor.setEnable(true);
        GasSensor gasSensor = new GasSensor("室内CO2传感器1");
        gasSensor.setAddress("05");
        gasSensor.setEnable(true);
        IndoorCO2SensorUtil.insert(gasSensor);
        FloorTSensor floorTSensor = new FloorTSensor("地面温度传感器");
        floorTSensor.setAddress("06");
        floorTSensor.setEnable(true);
        IndoorFloorTSensorUtil.insert(floorTSensor);
        GasSensor gasSensor2 = new GasSensor("氨气传感器1");
        gasSensor.setAddress("07");
        gasSensor.setEnable(true);
        IndoorAmmoniaSensorUtil.insert(gasSensor2);
        RoomSensor.airTHSensor.setEnable(false);
    }

    public void importBaseSetHD() {
        //控制器默认配置
        Controller.setControllerModel(Controller.CONTROLLER_MODEL[0]);
        HardwareSetting.setWorkMode(HardwareSetting.CONTROLLER_WORK_MODE[0]);
        HardwareSetting.setControllerSerialCom("/dev/ttyS8");
        HardwareSetting.setControllerSerialBaud("9600");
        HardwareSetting.setSensorSerialCom("/dev/ttyS0");
        HardwareSetting.setSensorSerialComBaud("9600");
        //继电器配置
        RoomController.relay.setEnable(true);
        RoomController.relay.setAddress("01");
        RoomController.relay.setModel(RoomController.relay.getModels()[2]);
        RoomController.relayFloor.clearAndSetPort(3);
        RoomController.airCondition.clearAndSetPort(4);
        RoomController.redLight.clearAndSetPort(5);
        RoomController.humidifier.clearAndSetPort(2);
        RoomController.intakeFan.clearAndSetPort(1);
        //地暖默认配置
        RoomController.floor.setEnable(true);
        RoomController.floor.setModel(RoomController.floor.getModels()[0]);
        RoomController.floor.setAddress("01");
        RoomController.floor.setMaxGear(5);
        Floor.importDefaultPWMToFloor();
        //空调默认配置
        RoomController.airConditionInfrared.setEnable(true);
        RoomController.airConditionInfrared.setModel(RoomController.airConditionInfrared.getModels()[0]);
        RoomController.airConditionInfrared.setAddress("01");
        //初始化传感器型号为默认型号
        for (Sensor sensor : RoomSensor.getAllSensors()) {
            sensor.setModel(sensor.getModels()[0]);
        }
        //传感器配置
        THSensor thSensor1 = new THSensor("室内温湿度传感器1");
        thSensor1.setAddress("01");
        thSensor1.setEnable(true);
        IndoorTHSensorUtil.insert(thSensor1);
        THSensor thSensor2 = new THSensor("室内温湿度传感器2");
        thSensor2.setAddress("02");
        thSensor2.setEnable(true);
        IndoorTHSensorUtil.insert(thSensor2);
        RoomSensor.outdoorTHSensor.setAddress("03");
        RoomSensor.outdoorTHSensor.setEnable(true);
        GasSensor gasSensor = new GasSensor("室内CO2传感器1");
        gasSensor.setAddress("05");
        gasSensor.setEnable(true);
        IndoorCO2SensorUtil.insert(gasSensor);

        RoomSensor.consumptionSensor.setEnable(false);
        RoomSensor.airTHSensor.setEnable(false);
    }

    /**
     * 旧系统配置-基地
     */
    public void importBaseSet() {
        importDefaultSet();
        HardwareSetting.setControllerSerialCom("/dev/ttyS1");
        HardwareSetting.setSensorSerialCom("/dev/ttyS0");
        RoomController.relay.setAddress("01");
        RoomController.intakeFan.clearAndSetPort(1);
        RoomController.humidifier.clearAndSetPort(2);
        RoomController.airCondition.clearAndSetPort(3);
        RoomController.evenFan.clearAllPort();
        RoomController.exhaustFan.clearAllPort();
        RoomController.redLight.clearAllPort();
        RoomController.whiteLight.clearAllPort();
        RoomController.uvLight.clearAllPort();
        RoomController.floor.setAddress("01");
        RoomSensor.airTHSensor.setEnable(false);
    }

    public static String getCurrentSetJsonString() {
        Map<String, Object> map = new LinkedHashMap<>();
        //基础信息
        map.put(RoomSetting.USER_NAME, RoomSetting.getUserName());
        //系统配置
        map.put(RoomSetting.SET_PASSWORD, RoomSetting.getSetPassword());
        map.put(RoomSetting.MAIN_ACTIVITY_LOCK, RoomSetting.getMainActivityLock());
        map.put(RoomSetting.MAIN_ACTIVITY_OPERATE_LOCK_TIMEOUT, RoomSetting.getMainActivityOperateLockTimeOut());
        map.put(RoomSetting.NOTICE_TYPE, RoomSetting.getNoticeType());
        //控制器配置
        map.put(Device.MY_CONTROLLER_MODEL, Controller.getControllerModel());
        map.put(HardwareSetting.MY_CONTROLLER_WORK_MODE, HardwareSetting.getWorkMode());
        //集成式
        map.put(HardwareSetting.CONTROLLER_SERIAL_COM, HardwareSetting.getControllerSerialCom());
        map.put(HardwareSetting.CONTROLLER_SERIAL_BAUD, HardwareSetting.getControllerSerialBaud());
        map.put(HardwareSetting.SENSOR_SERIAL_COM, HardwareSetting.getSensorSerialCom());
        map.put(HardwareSetting.SENSOR_SERIAL_COM_BAUD, HardwareSetting.getSensorSerialComBaud());
        //装配式
        map.put(HardwareSetting.COMMON_ADDRESS, HardwareSetting.getCommonAddress());
        //继电器配置
        map.put(Relay.TAG + Device.ENABLE, RoomController.relay.isEnable());
        map.put(Relay.TAG + Device.MODEL, RoomController.relay.getModel());
        map.put(Relay.TAG + Device.ADDRESS, RoomController.relay.getAddress());
        for (Relay relay : RoomController.getAllRelayDevice()) {
            map.put(relay.PORT, MMKVUtil.get(relay.PORT, "[]"));
        }
        //空调配置
        map.put(RoomController.DEVICE_NAME[9] + Device.ENABLE, RoomController.airConditionInfrared.isEnable());
        map.put(RoomController.DEVICE_NAME[9] + Device.MODEL, RoomController.airConditionInfrared.getModel());
        map.put(RoomController.DEVICE_NAME[9] + Device.ADDRESS, RoomController.airConditionInfrared.getAddress());
        //除湿器配置
        map.put(RoomController.DEVICE_NAME[15] + Device.ENABLE, RoomController.dehumidifierInfrared.isEnable());
        map.put(RoomController.DEVICE_NAME[15] + Device.MODEL, RoomController.dehumidifierInfrared.getModel());
        map.put(RoomController.DEVICE_NAME[15] + Device.ADDRESS, RoomController.dehumidifierInfrared.getAddress());
        //485除湿机配置
        map.put(RoomController.dehumidifier485.getName() + Device.ENABLE, RoomController.dehumidifier485.isEnable());
        map.put(RoomController.dehumidifier485.getName() + Device.MODEL, RoomController.dehumidifier485.getModel());
        map.put(RoomController.dehumidifier485.getName() + Device.ADDRESS, RoomController.dehumidifier485.getAddress());
        //空调2配置
        map.put(RoomController.DEVICE_NAME[14] + Device.ENABLE, RoomController.airConditionInfrared2.isEnable());
        map.put(RoomController.DEVICE_NAME[14] + Device.MODEL, RoomController.airConditionInfrared2.getModel());
        map.put(RoomController.DEVICE_NAME[14] + Device.ADDRESS, RoomController.airConditionInfrared2.getAddress());
        //地暖配置
        map.put(RoomController.DEVICE_NAME[0] + Device.ENABLE, RoomController.floor.isEnable());
        map.put(RoomController.DEVICE_NAME[0] + Device.MODEL, RoomController.floor.getModel());
        map.put(RoomController.DEVICE_NAME[0] + Device.ADDRESS, RoomController.floor.getAddress());
        map.put(Floor.MAX_GEAR, RoomController.floor.getMaxGear());
        for (int i = 1; i <= 5; i++) {
            Floor.PWM pwm = RoomController.floor.getPwm(i);
            map.put(RoomController.DEVICE_NAME[0] + i + "档PWM", pwm.getPwm());
            map.put(RoomController.DEVICE_NAME[0] + i + "档功率", pwm.getPower());
        }
        //传感器配置
        for (Sensor sensor : RoomSensor.getAllSensors()) {
            map.put(sensor.getName() + Device.ENABLE, sensor.isEnable());
            map.put(sensor.getName() + Device.MODEL, sensor.getModel());
            map.put(sensor.getName() + Device.ADDRESS, sensor.getAddress());
        }
        return GsonUtils.toJson(new WebSet(System.currentTimeMillis(), map));
    }

    /**
     * 上传当前APP所有配置至服务器
     */
    public void uploadSet() {
        showLoadingDialog("正在上传配置，请稍等...");
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.uploadConfig);
        params.addParameter("ConfigJson", getCurrentSetJsonString());
        params.addParameter("hostCode", HardwareSetting.getHostId());
        x.http().post(params, new XHttpShorthand<CommonResponse>() {
            @Override
            public void success(CommonResponse model) {
                MyLog.network("配置已上传");
                successTips("配置已上传");
            }

            @Override
            public void error(Throwable e) {
                errorTips("配置上传失败");
                MyLog.networkError("配置上传失败");
            }

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

    /**
     * 验证运维密码
     */
    public void checkDevOpsPassword(String pwd) {
        showLoadingDialog("正在验证运维密码，请稍等...");
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.checkDevOpsPassword);
        params.addParameter("AreaCode", RoomSetting.getAreaCode());
        params.addParameter("Secret", pwd);
        x.http().post(params, new XHttpShorthand<CommonResponse>() {
            @Override
            public void success(CommonResponse model) {
                MyLog.network("运维密码验证通过");
                String msg = model.getMessage();
                if ("验证通过".equals(msg)) {
                    successTips(msg);
                    refreshLiveData.setValue(3);
                } else {
                    errorTips(msg);
                }
            }

            @Override
            public void onSuccessError(CommonResponse data) {
                super.onSuccessError(data);
                errorTips(data.getMessage());
            }

            @Override
            public void error(Throwable e) {
                errorTips("运维密码验证失败");
                MyLog.networkError("运维密码验证失败");
            }

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

    public void uploadLog() {
        showLoadingDialog("正在上传日志");
        RxJavaUtils.executeAsyncTask(new RxAsyncTask<Object, File>(null) {
            @Override
            public File doInIOThread(Object o) {
                List<Log> myObjects = LogDBManager.queryAllList(); // 获取对象列表
                return CsvConverter.writeLogToCsvFile(myObjects);
//               CsvConverter.saveSensorDataToCsv();
            }

            @Override
            public void doInUIThread(File file) {
                RequestParams params = XHttpManager.getInstance().getRequestParams(Url.uploadLog);
                params.addParameter("hostCode", HardwareSetting.getHostId());
                params.addParameter("log", file);
                x.http().post(params, new XHttpShorthand<CommonResponse>() {
                    @Override
                    public void success(CommonResponse model) {
                        MyLog.network("日志已上传");
                        successTips("日志已上传");
                    }

                    @Override
                    public void error(Throwable e) {
                        errorTips("日志上传失败");
                        MyLog.networkError("日志上传失败");
                    }

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