package com.example.iot_controlhost.ui.dialog;

import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;

import androidx.annotation.NonNull;

import com.example.iot_controlhost.R;
import com.example.iot_controlhost.base.BaseDialog;
import com.example.iot_controlhost.databinding.DialogFloorBinding;
import com.example.iot_controlhost.model.controller.Floor;
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.global.RoomController;
import com.example.iot_controlhost.utils.global.RoomSetting;
import com.example.iot_controlhost.utils.global.RxTag;
import com.example.iot_controlhost.utils.log.UserLog;
import com.google.android.material.slider.RangeSlider;
import com.xuexiang.rxutil2.rxbus.RxBusUtils;

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

/**
 * 地暖遥控器
 */
public class FloorDialog extends BaseDialog<DialogFloorBinding> {
    Floor floor;

    public FloorDialog(Context mContext) {
        super(mContext);
        floor = RoomController.floor;
        preGear = floor.getGear();
        binding.tvTitle.setText(RoomSetting.getFloorName());
        //打开串口
        if (!SerialPortUtil.getInstance(SerialPortUtil.TYPE_CONTROLLER).openSerialPort()) {
            Toasty.error(mContext, "串口打开失败").show();
        }
        binding.rs.setCustomThumbDrawable(R.mipmap.sel_floor_1);
        binding.rs.setThumbRadius(40);
        binding.rs.setTickVisible(false);
        binding.rs.addOnChangeListener((slider, value, fromUser) -> binding.rs.setCustomThumbDrawable(getThumbView((int) value)));
        binding.rs.addOnSliderTouchListener(new RangeSlider.OnSliderTouchListener() {
            @Override
            public void onStartTrackingTouch(@NonNull RangeSlider slider) {
            }

            @Override
            public void onStopTrackingTouch(@NonNull RangeSlider slider) {
                changeFloor(slider.getValues().get(0).intValue());
            }
        });
        binding.rs.setValues(preGear);
        binding.rs.setTrackHeight(50);
        // 设置导轨为透明
        binding.rs.setTrackInactiveTintList(ColorStateList.valueOf(Color.parseColor("#00000000")));
        binding.rs.setTrackActiveTintList(ColorStateList.valueOf(Color.parseColor("#00000000")));
    }

    /**
     * 调节前的档位，用于操作失败时回溯
     */
    private float preGear;

    private int getThumbView(int target) {
        int result = R.mipmap.sel_floor_0;
        switch (target) {
            case 0 -> result = R.mipmap.sel_floor_0;
            case 1 -> result = R.mipmap.sel_floor_1;
            case 2 -> result = R.mipmap.sel_floor_2;
            case 3 -> result = R.mipmap.sel_floor_3;
            case 4 -> result = R.mipmap.sel_floor_4;
            case 5 -> result = R.mipmap.sel_floor_5;
        }
        return result;
    }

    private void changeFloor(int gear) {
        DialogUtil.showLoadingDialog(mContext,"正在操作"  + RoomSetting.getFloorName() + "中");
        MyQueue.start(MyQueue.TYPE_CONTROLLER, new QueueIOUITask<Boolean>() {
            @Override
            public Boolean doInQueueThread() throws Exception {
                if (gear > floor.getMaxGear()) {
                    return false;
                } else {
                    return floor.setGear(gear);
                }
            }

            @Override
            public void doInUIThread(Boolean aBoolean) {
                if (aBoolean) {
                    preGear = floor.getGear();
                    successTips(floor.getState());
                    UserLog.operate("本机屏幕", "地暖档位切换成功：" + floor.getGear() + "档");
                } else {
                    binding.rs.setValues(preGear);
                    if (gear > floor.getMaxGear()) {
                        errorTips("目标档位大于设定最大档位，切换失败");
                    } else {
                        UserLog.operateError("本机屏幕", "地暖档位切换失败：" + gear + "档");
                        errorTips("切换档位失败");
                    }
                }
                DialogUtil.hideLoadingDialog();
            }
        });
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (RoomSetting.getMode() == 0) {
            //更新手动模式UI
            RxBusUtils.get().post(RxTag.UPDATE_MANUAL, 0);
        } else if (RoomSetting.getMode() == 1) {
            //更新自动模式UI
            RxBusUtils.get().post(RxTag.UPDATE_AUTO, 2);
        }
    }
}
