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.databinding.DialogAirConditionAddBinding;
import com.example.iot_controlhost.databinding.DialogDehumidityAddBinding;
import com.example.iot_controlhost.model.controller.AirConditionInfrared;
import com.example.iot_controlhost.model.controller.DehumidifierInfrared;
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.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 DehumidityAddDialog extends Dialog {
    /**
     * 当前设置的指令类型
     */
    private int type;
    DialogDehumidityAddBinding binding;
    Context mContext;

    DehumidifierInfrared mAirConditionInfrared;

    public DehumidityAddDialog(@NonNull Context mContext, DehumidifierInfrared dehumidityAddDialog) {
        super(mContext);
        this.mContext = mContext;
        this.mAirConditionInfrared = dehumidityAddDialog;
        binding = DialogDehumidityAddBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        //初始除湿机指令设置类型为200：开机
        type = 200;
        binding.tvTitle.setText("除湿机指令学习与测试" + dehumidityAddDialog.getName());
        //基础模式
        View.OnClickListener baseListener = v -> {
            int id = v.getId();
            binding.toggleButton1.check(id);
            if (id == R.id.btn_cancel_learn) {
                type = 0;
            } else if (id == R.id.btn_power_on) {
                type = 200;
            } else if (id == R.id.btn_power_off) {
                type = 201;
            }
        };

        getWindow().setGravity(Gravity.CENTER);
        binding.ivDialogClose.setOnClickListener(view -> dismiss());
        binding.btnPowerOn.setOnClickListener(baseListener);
        binding.btnPowerOff.setOnClickListener(baseListener);
        //刷新/读取
        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.btnYes.setOnClickListener(view -> dismiss());
        if (!SerialPortUtil.getInstance(SerialPortUtil.TYPE_CONTROLLER).openSerialPort()) {
            Toasty.error(mContext, "串口打开失败，请检查设置->控制器配置->串口配置").show();
        }
        //上传服务器
        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();
        });
    }

    /**
     * 上传除湿机指令
     */
    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 = 200; i <= 201; 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();
    }
}
