package com.example.iot_controlhost.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.example.iot_controlhost.R;
import com.example.iot_controlhost.base.BaseDialog;
import com.example.iot_controlhost.databinding.DialogAirConditionAddBinding;
import com.example.iot_controlhost.model.controller.AirConditionInfrared;
import com.example.iot_controlhost.model.net.CommonResponse;
import com.example.iot_controlhost.model.thread.QueueIOUITask;
import com.example.iot_controlhost.utils.DialogUtil;
import com.example.iot_controlhost.utils.MyQueue;
import com.example.iot_controlhost.utils.MyUtil;
import com.example.iot_controlhost.utils.global.RoomController;
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 org.xutils.http.RequestParams;
import org.xutils.x;

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

import android_serialport_api.SerialPortUtil;
import es.dmoral.toasty.Toasty;

/**
 * @Description 增加新空调弹窗
 * @Author DuanKaiji
 * @CreateTime 2024年04月10日 09:29:35
 */
public class AirConditionAddDialog  extends Dialog {
    /**
     * 当前设置的空调指令类型
     */
    private int type = 0;
    DialogAirConditionAddBinding binding;
    Context mContext;

    AirConditionInfrared mAirConditionInfrared;

    public AirConditionAddDialog(@NonNull Context mContext, AirConditionInfrared airConditionInfrared) {
        super(mContext);
        this.mContext = mContext;
        this.mAirConditionInfrared = airConditionInfrared;
        binding = DialogAirConditionAddBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        //初始空调指令设置类型为1：开机
        type = 1;
        binding.tvTitle.setText("新空调指令学习测试与导出——" + airConditionInfrared.getName());
        //基础模式
        View.OnClickListener baseListener = v -> {
            int id = v.getId();
            binding.toggleButton2.clearChecked();
            binding.toggleButton1.check(id);
            if (id == R.id.btn_cancel_learn) {
                type = 0;
            } else if (id == R.id.btn_power_on) {
                type = 1;
            } else if (id == R.id.btn_power_off) {
                type = 2;
            } else if (id == R.id.btn_heat) {
                type = 3;
            } else if (id == R.id.btn_refrigeration) {
                type = 4;
            }

        };

        getWindow().setGravity(Gravity.CENTER);
        binding.ivDialogClose.setOnClickListener(view -> dismiss());
        binding.btnPowerOn.setOnClickListener(baseListener);
        binding.btnPowerOff.setOnClickListener(baseListener);
        binding.btnHeat.setOnClickListener(baseListener);
        binding.btnRefrigeration.setOnClickListener(baseListener);
        binding.btnDehumidify.setOnClickListener(baseListener);
        //温度模式
        View.OnClickListener modeListener = v -> {
            binding.toggleButton1.clearChecked();
            binding.toggleButton2.check(v.getId());
            int temperature = Integer.parseInt(binding.btnTemperature.getText().toString());
            int id = v.getId();
            if (id == R.id.btn_temperature_heat) {
                type = temperature - 12;
            } else if (id == R.id.btn_temperature_refrigeration) {
                type = temperature + 2;
            } else if (id == R.id.btn_temperature_auto) {
                type = temperature + 16;
            } else if (id == R.id.btn_dehumidify) {
                type = temperature + 30;
            }
        };
        binding.btnTemperatureHeat.setOnClickListener(modeListener);
        binding.btnTemperatureAuto.setOnClickListener(modeListener);
        binding.btnTemperatureRefrigeration.setOnClickListener(modeListener);
        binding.btnDehumidify.setOnClickListener(modeListener);
        //加减温度
        View.OnClickListener temperatureListener = v -> {
            //获得toggleButtonGroup2选中的项
            int checkedId = binding.toggleButton2.getCheckedButtonId();
            int temperature = Integer.parseInt(binding.btnTemperature.getText().toString());
            if (checkedId == -1) {
                Toasty.info(mContext, "请先选择左侧温度模式").show();
                return;
            }
            int id = v.getId();
            if (id == R.id.btn_plus) {
                temperature += 1;
            } else if (id == R.id.btn_minus) {
                temperature -= 1;
            }

            if (temperature <= 30 && temperature >= 17) {
                binding.btnTemperature.setText(String.valueOf(temperature));
            } else {
                Toasty.info(mContext, mContext.getText(R.string.min_max_error_temperature)).show();
                return;
            }

            if (checkedId == R.id.btn_temperature_heat) {
                type = temperature - 12;
            } else if (checkedId == R.id.btn_temperature_refrigeration) {
                type = temperature + 2;
            } else if (checkedId == R.id.btn_temperature_auto) {
                type = temperature + 16;
            } else if (checkedId == R.id.btn_dehumidify) {
                type = temperature + 30;
            }

        };
        binding.btnPlus.setOnClickListener(temperatureListener);
        binding.btnMinus.setOnClickListener(temperatureListener);
        //刷新/读取
        binding.btnRefresh.setOnClickListener(view -> binding.tvInstruction.setText(mAirConditionInfrared.readInstruction(type)));
        //测试
        binding.btnTest.setOnClickListener(view -> {
            if (mAirConditionInfrared.executeInstruction(type)) {
                Toasty.success(mContext, "测试成功").show();
            } else {
                Toasty.error(mContext, "测试失败").show();
            }
        });
        //学习
        binding.btnLearn.setOnClickListener(view -> mAirConditionInfrared.learnInstruction(type));
        binding.btnCancelLearn.setOnClickListener(view -> mAirConditionInfrared.learnInstruction(0));
        //上传服务器
        binding.btnUpload.setOnClickListener(view -> {
            if (StringUtils.isEmpty(binding.etAirConditionModel.getText().toString())) {
                Toasty.info(mContext, "请输入空调型号").show();
                return;
            }
            if (StringUtils.isEmpty(binding.etAirConditionBrand.getText().toString())) {
                Toasty.info(mContext, "请输入空调品牌").show();
                return;
            }
            new ConfirmDialog(mContext, mContext.getString(R.string.tip), "确定要上传至服务器吗？", () ->
                    uploadAirConditionInstruction(binding.etAirConditionBrand.getText().toString(), binding.etAirConditionModel.getText().toString())).show();
        });
        binding.btnYes.setOnClickListener(view -> dismiss());
        if (!SerialPortUtil.getInstance(SerialPortUtil.TYPE_CONTROLLER).openSerialPort()) {
            Toasty.error(mContext, "串口打开失败，请检查设置->控制器配置->串口配置").show();
        }
    }

    /**
     * 上传空调指令
     */
    public void uploadAirConditionInstruction(String brand, String model) {
        DialogUtil.showLoadingDialog(mContext,mContext.getString(R.string.in_read_air_condition_instruction));
        MyQueue.start(MyQueue.TYPE_CONTROLLER, new QueueIOUITask<List<String>>() {
            @Override
            public List<String> doInQueueThread() {
                List<String> instructions = new ArrayList<>();
                for (int i = 1; i <= 60; i++) {
                    DialogUtil.showLoadingDialogInIO(mContext,"正在读取第" + i + "条指令");
                    String instruction = mAirConditionInfrared.readInstruction(i);
                    if (MyUtil.checkInstruction(instruction)) {
                        instructions.add(instruction);
                    } else {
                        instructions.add("0000");
                    }
                }
                return instructions;
            }

            @Override
            public void doInUIThread(List<String> instructions) {
                if (instructions == null) {
                    //存在指令错误，有全0全F出现
                    errorTips("存在指令错误");
                    return;
                }
                DialogUtil.showLoadingDialog(mContext,mContext.getString(R.string.in_upload_air_condition_instruction));
                RequestParams params = XHttpManager.getInstance().getRequestParams(Url.uploadAirConditioner);
                params.addParameter("Brand", brand);
                params.addParameter("Model", model);
                params.addParameter("Instruct", GsonUtils.toJson(instructions));
                x.http().post(params, new XHttpShorthand<CommonResponse>() {
                    @Override
                    public void success(CommonResponse model) {
                        DialogUtil.hideLoadingDialog();
                        new ConfirmDialog(mContext, mContext.getString(R.string.tip), "成功上传空调指令",null).show();
                        successTips(model.getMessage());
                    }

                    @Override
                    public void error(Throwable e) {
                        //上传空调指令失败
                        errorTips("上传空调指令失败");
                        DialogUtil.hideLoadingDialog();
                    }
                });
            }
        });
    }

    protected void successTips(String msg) {
        Toasty.success(mContext, msg).show();
    }

    protected void errorTips(String msg) {
        Toasty.error(mContext, msg).show();
    }
}
