package xn.xxp.home.window;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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

import core.ui.fragment.RcBaseFragment;
import http.client.ApiRepository;
import http.vo.response.LaboratoryVo;
import http.vo.response.SafeClassify;
import io.reactivex.rxjava3.functions.Consumer;
import xn.xxp.R;
import xn.xxp.databinding.FragmentWindowBinding;
import xn.xxp.app.LabApp;
import xn.xxp.mqtt.event.UpdateUiEvent;
import xn.xxp.room.RoomTool;
import xn.xxp.room.bean.DeviceConfig;
import xn.xxp.room.bean.LabConfig;
import xn.xxp.utils.Constants;
import xn.xxp.utils.QrTool;
import xn.xxp.utils.Tool;

public class WindowFragment extends RcBaseFragment<FragmentWindowBinding> {
    private FragmentWindowBinding binding;
    private WindowVerticalAdapter windowVerticalAdapter;
    private WindowTextlAdapter windowTextlAdapter;
    private DeviceConfig deviceConfig;
    private LabConfig labConfig;


    @NonNull
    @Override
    protected FragmentWindowBinding createViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        return binding = FragmentWindowBinding.inflate(inflater, container, false);
    }

    @Override
    protected void initViews(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
        labConfig = RoomTool.getInstance().labConfigDao().getLabConfig();
        initData();
    }

    private void initData() {
        if (null == LabApp.laboratory) {
            showToast("暂无实验室信息，即将重新获取");
            Tool.INSTANCE.reStartApp("暂无实验室信息，即将重新获取");
            return;
        }
        initLaboratoryInfo(LabApp.laboratory);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUiEvent(UpdateUiEvent updateUiEvent) {
        // 中部更新
        if (Constants.MqttConfig.Topic.MIDDLE_INFO.equals(updateUiEvent.getType())) {
            addDisposable(ApiRepository.INSTANCE.laboratoryInfo(true, String.valueOf(labConfig.getLabId())).subscribe(new Consumer<LaboratoryVo>() {
                @Override
                public void accept(LaboratoryVo laboratoryVo) throws Exception {
                    LabApp.laboratory = laboratoryVo;
                    initData();
                }
            }, throwable -> {
                LogUtils.e(Log.getStackTraceString(throwable));
                showNetError(throwable);
            }));
        }
    }

    private void initLaboratoryInfo(LaboratoryVo lab) {
        // 实验室安全分级
        GradientDrawable dangerShapeDrawable = (GradientDrawable) ContextCompat.getDrawable(requireContext(), R.drawable.shape_rect_round_20px_ll);
        dangerShapeDrawable.setColor(TextUtils.isEmpty(lab.dangerColor) ? Color.parseColor("#FF15CA48") : Color.parseColor(lab.dangerColor));
        binding.dangerLL.setBackground(dangerShapeDrawable);
        binding.dangerLevelTV.setText(TextUtils.isEmpty(lab.dangerLevel) ? "安全分级" : lab.dangerLevel);
        binding.dangerTypeTV.setText(TextUtils.isEmpty(lab.dangerName) ? "安全分类" : lab.dangerName);

        // 单位名称
        binding.unitNameTV.setText(TextUtils.isEmpty(lab.deptName) ? "" : lab.deptName);
        // 实验室名称
        binding.labNameTV.setText(TextUtils.isEmpty(lab.subName) ? "" : lab.subName);
        // 实验室负责人
        binding.labLeaderTV.setText(TextUtils.isEmpty(lab.adminName) ? "" : lab.adminName);
        // 楼宇
        binding.buildingNameTV.setText(TextUtils.isEmpty(lab.buildName) ? "" : lab.buildName);
        // 房间号
        binding.roomNOTV.setText(TextUtils.isEmpty(lab.room) ? "" : lab.room);
        // 实验室负责人电话
        binding.leaderPhoneTV.setText(TextUtils.isEmpty(lab.adminPhone) ? "" : lab.adminPhone);
        // 实验室二维码
        if (!TextUtils.isEmpty(lab.qrCodeUrl)) {
            ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Bitmap>() {
                @Override
                public Bitmap doInBackground() throws Throwable {
                    return QrTool.generateQRCode(lab.qrCodeUrl, 175);
                }

                @Override
                public void onSuccess(Bitmap result) {
                    if (null != result) {
                        Glide.with(requireContext()).asBitmap().load(result).error(R.mipmap.img_error).into(binding.labQrIV);
                    }
                }
            });
        }
        List<SafeClassify> safeClassifyList = lab.safeClassifyList;
        List<SafeClassify> imageSafeClassifyList = new ArrayList<>();
        List<SafeClassify> textSsafeClassifyList = new ArrayList<>();
        for (int i = 0; i < safeClassifyList.size(); i++) {
            SafeClassify safeClassify = safeClassifyList.get(i);
            if (safeClassify.classifyType == 1) {
                textSsafeClassifyList.add(safeClassify);
            } else if (safeClassify.classifyType == 2) {
                imageSafeClassifyList.add(safeClassify);
            }
        }
        // 图标布局
        if (null == windowVerticalAdapter) {
            windowVerticalAdapter = new WindowVerticalAdapter(requireContext(), imageSafeClassifyList);
            LinearLayoutManager verticalImageLayoutManager = new LinearLayoutManager(requireContext());
            binding.safeClassifyImageRV.setLayoutManager(verticalImageLayoutManager);
            binding.safeClassifyImageRV.setAdapter(windowVerticalAdapter);
        } else {
            windowVerticalAdapter.update(imageSafeClassifyList);
        }

        // 文字布局
        if (null == windowTextlAdapter) {
            windowTextlAdapter = new WindowTextlAdapter(requireContext(), textSsafeClassifyList);
            LinearLayoutManager verticalTextLayoutManager = new LinearLayoutManager(requireContext());
            binding.safeClassifyTextRV.setLayoutManager(verticalTextLayoutManager);
            binding.safeClassifyTextRV.setAdapter(windowTextlAdapter);
        } else {
            windowTextlAdapter.update(textSsafeClassifyList);
        }

    }
}
