package com.example.iot_controlhost.ui.fragment;

import android.graphics.Color;
import android.transition.Fade;
import android.transition.TransitionManager;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;

import com.example.iot_controlhost.R;
import com.example.iot_controlhost.adapter.AutoControllerAdapter;
import com.example.iot_controlhost.base.BaseFragment;
import com.example.iot_controlhost.base.BaseMode;
import com.example.iot_controlhost.databinding.FragmentModelAutoBinding;
import com.example.iot_controlhost.databinding.ItemControllerAutoBinding;
import com.example.iot_controlhost.model.controller.AirConditionInfrared;
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.ui.dialog.AirDialog;
import com.example.iot_controlhost.ui.dialog.SetAutoParamDialog;
import com.example.iot_controlhost.ui.dialog.FloorDialog;
import com.example.iot_controlhost.utils.control.infrared.MyInfraredUtils;
import com.example.iot_controlhost.utils.global.AutoModelSet;
import com.example.iot_controlhost.utils.global.RoomController;
import com.example.iot_controlhost.utils.global.RoomSetting;

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

import es.dmoral.toasty.Toasty;

/**
 * 自动模式
 */
public class AutoFragment extends BaseFragment<FragmentModelAutoBinding, AutoFragmentPresenter> implements BaseMode {
    private static AutoControllerAdapter manualControllerAdapter;
    private static AutoControllerAdapter manualControllerAdapterTwo;
//    private static AutoFragment INSTANCE = new AutoFragment();

    public AutoFragment() {
    }

//    public static AutoFragment getInstance() {
//        return INSTANCE;
//    }

    @Override
    public void init() {
        binding.setVm(presenter);
        presenter.getSetAutoParamLiveData().observe(this, integer -> {
            switch (integer) {
                case 0 -> //设置自动模式温度
                        new SetAutoParamDialog(mContext, 0, new String[]{String.valueOf(AutoModelSet.getTargetTemperature()),
                                String.valueOf(AutoModelSet.getMaxTemperature()), String.valueOf(AutoModelSet.getMinTemperature())}).show();
                case 1 -> //设置自动模式湿度
                        new SetAutoParamDialog(mContext, 1, new String[]{String.valueOf(AutoModelSet.getTargetHumidity()),
                                String.valueOf(AutoModelSet.getMaxHumidity()), String.valueOf(AutoModelSet.getMinHumidity())}).show();
                case 2 -> //设置自动模式换气
                        new SetAutoParamDialog(mContext, 2, new String[]{String.valueOf(AutoModelSet.getCycleStart()),
                                String.valueOf(AutoModelSet.getCycleStop()), String.valueOf(AutoModelSet.getMaxDensityCO2())}).show();
                case 6 ->//刷新手动温度控制状态
                        refreshAutoView();
            }
        });
        manualControllerAdapter = new AutoControllerAdapter(mContext, null, ItemControllerAutoBinding.class);
        manualControllerAdapterTwo = new AutoControllerAdapter(mContext, null, ItemControllerAutoBinding.class);
        binding.recycleView.setAdapter(manualControllerAdapter);
        binding.recycleView.setLayoutManager(new GridLayoutManager(mContext, 2));
        binding.recycleView2.setAdapter(manualControllerAdapterTwo);
        binding.recycleView2.setLayoutManager(new GridLayoutManager(mContext, 4));
        List<Controller> devices = RoomController.getAllControlDevices();
        // 第一排显示2个设备
        if (devices.size() <= 2) {
            int missingCount = 2 - devices.size();
            for (int i = 0; i < missingCount; i++) {
                devices.add(new Relay("未配置"));
            }
        }
        manualControllerAdapter.setDataList(devices);
        // 第二排显示剩下的设备
        List<Controller> remainingDevices = new ArrayList<>();
        if (devices.size() > 2) {
            List<Controller> tempDevices = devices.subList(2, devices.size());
            remainingDevices.addAll(tempDevices);
        }
        if (remainingDevices.size() < 4) {
            int missingCount = 4 - remainingDevices.size();
            for (int i = 0; i < missingCount; i++) {
                remainingDevices.add(new Relay("未配置"));
            }
        }
        manualControllerAdapterTwo.setDataList(remainingDevices);
        refreshAutoView();
        if (RoomSetting.getMode() == 1) {
            initMode();
        }
    }

    @Override
    public void initListener() {
        super.initListener();
        binding.cardFloor.setOnClickListener(v -> {
            if (AutoModelSet.isAutoTemperature()) {
                Toasty.info(mContext, "该设备由自动控制系统接管中").show();
            } else {
                new FloorDialog(mContext).show();
            }
        });
        binding.cardAir.setOnClickListener(v -> {
            if (AutoModelSet.isAutoTemperature()) {
                Toasty.info(mContext, "该设备由自动控制系统接管中").show();
            } else {
                new AirDialog(mContext,MyInfraredUtils.getInstances()).show();
            }
        });
    }

    @Override
    public void initMode() {
        presenter.startAutoControl();
        presenter.updateUI();
        presenter.updateParamUI();
    }

    @Override
    public void stopMode() {
        presenter.stopAutoControl();
        RoomController.closeAllControllers();
    }

    /**
     * 刷新自动视图
     */
    private void refreshAutoView() {
        TransitionManager.beginDelayedTransition(binding.ll, new Fade());
        //初始化自动模式参数显示
        binding.llTemAuto.setVisibility(AutoModelSet.isAutoTemperature() ? View.VISIBLE : View.GONE);
        binding.llTemManual.setVisibility(AutoModelSet.isAutoTemperature() ? View.GONE : View.VISIBLE);
        binding.llHumAuto.setVisibility(AutoModelSet.isAutoHumidity() ? View.VISIBLE : View.GONE);
        binding.llHumManual.setVisibility(AutoModelSet.isAutoHumidity() ? View.GONE : View.VISIBLE);
        binding.llVenAuto.setVisibility(AutoModelSet.isAutoVentilator() ? View.VISIBLE : View.GONE);
        binding.llVenManual.setVisibility(AutoModelSet.isAutoVentilator() ? View.GONE : View.VISIBLE);
        //初始化空调地暖视图
        changeFloorState();
        changeAirState();
        //初始化手动控制器显示
        manualControllerAdapter.notifyDataSetChanged();
        manualControllerAdapterTwo.notifyDataSetChanged();
    }

    private void changeFloorState() {
        Floor floor = RoomController.floor;
        binding.tvFloor.setText(RoomSetting.getFloorName());
        binding.tvStateFloor.setText(floor.getState());
        if (floor.isPowerSupply()) {
            binding.ivControllerFloor.setImageResource(R.mipmap.floor_open);
            binding.cardFloor.setBackgroundColor(Color.parseColor("#FF9C00"));
            binding.tvStateFloor.setTextColor(Color.parseColor("#FFFFFF"));
            binding.tvFloor.setTextColor(Color.parseColor("#FFFFFF"));
            binding.ivPowerFloor.setBackground(mContext.getDrawable(R.drawable.bg_controller_open));
            binding.ivPowerFloor.setImageDrawable(mContext.getDrawable(R.mipmap.switch_on));
            binding.tvPowerFloor.setTextColor(Color.parseColor("#FFFFFF"));
            binding.tvFloorT.setTextColor(Color.parseColor("#FFFFFF"));
        } else {
            binding.ivControllerFloor.setImageResource(R.mipmap.floor_close);
            binding.cardFloor.setBackgroundColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#33DCE3E3" : "#F2F0F1"));
            binding.tvStateFloor.setTextColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#FFFFFF" : "#3A3A3A"));
            binding.ivPowerFloor.setBackground(mContext.getDrawable(R.drawable.bg_controller_close));
            binding.ivPowerFloor.setImageDrawable(mContext.getDrawable(R.mipmap.switch_off));
            binding.tvFloor.setTextColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#FFFFFF" : "#3A3A3A"));
            binding.tvPowerFloor.setTextColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#FFFFFF" : "#3A3A3A"));
            binding.tvFloorT.setTextColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#FFFFFF" : "#3A3A3A"));
        }
        binding.tvPowerFloor.setVisibility(RoomController.relay.getModel().equals(RoomController.relay.getModels()[2]) ? View.VISIBLE : View.GONE);
        binding.tvPowerFloor.setText("实时功率：" + RoomController.relayFloor.getPower() + "w");
    }

    private void changeAirState() {
        AirConditionInfrared air = MyInfraredUtils.getInstances();
        binding.tvStateAir.setText(air.getState());
        if (air.isPowerSupply()) {
            binding.ivControllerAir.setImageResource(R.mipmap.air_open);
            binding.cardAir.setBackgroundColor(Color.parseColor(air.getMode() == AirConditionInfrared.HEAT ? "#FF9C00" :
                    air.getMode() == AirConditionInfrared.COLD?"#00A1FF":"#7DFA5B"));
            binding.tvStateAir.setTextColor(Color.parseColor("#FFFFFF"));
            binding.tvAir.setTextColor(Color.parseColor("#FFFFFF"));
            binding.tvPowerAir.setTextColor(Color.parseColor("#FFFFFF"));
            binding.ivPowerAir.setBackground(mContext.getDrawable(R.drawable.bg_controller_open));
            binding.ivPowerAir.setImageDrawable(mContext.getDrawable(R.mipmap.switch_on));
        } else {
            binding.ivControllerAir.setImageResource(R.mipmap.air_close);
            binding.cardAir.setBackgroundColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#33DCE3E3" : "#F2F0F1"));
            binding.tvStateAir.setTextColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#FFFFFF" : "#3A3A3A"));
            binding.tvAir.setTextColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#FFFFFF" : "#3A3A3A"));
            binding.tvPowerAir.setTextColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#FFFFFF" : "#3A3A3A"));
            binding.ivPowerAir.setBackground(mContext.getDrawable(R.drawable.bg_controller_close));
            binding.ivPowerAir.setImageDrawable(mContext.getDrawable(R.mipmap.switch_off));
        }
        binding.tvPowerAir.setVisibility(RoomController.relay.getModel().equals(RoomController.relay.getModels()[2]) ? View.VISIBLE : View.GONE);
        binding.tvPowerAir.setText("实时功率：" + RoomController.airCondition.getPower() + "w");
    }

}
