package com.rdiot.yx485.fragment;

import static com.rdiot.yx485.http.Url.BASE_URL2;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.tabs.TabLayout;
import com.king.zxing.util.LogUtils;
import com.rdiot.yx485.InviteActivity;
import com.rdiot.yx485.R;
import com.rdiot.yx485.adapter.TopDeviceAdapter;
import com.rdiot.yx485.adapter.TopDevicegridAdapter;
import com.rdiot.yx485.adapter.TopModelAdapter;
import com.rdiot.yx485.base.BaseFragment;
import com.rdiot.yx485.bean.HomeBase;
import com.rdiot.yx485.bean.HomeDefBean;
import com.rdiot.yx485.databinding.FragmentTopBinding;
import com.rdiot.yx485.device.view.DeviceManageActivity;
import com.rdiot.yx485.home.HomeCreateActivity;
import com.rdiot.yx485.main.MainActivityTab;
import com.rdiot.yx485.main.MainViewModel;
import com.rdiot.yx485.message.MessageListActivity;
import com.rdiot.yx485.message.MessageViewModel;
import com.rdiot.yx485.util.IntentUtils;
import com.rdiot.yx485.util.LocalCache;
import com.rdiot.yx485.webview.WebViewActivity;
import com.rdiot.yx485.widget.CommonPopupWindow;
import com.zcolin.frame.util.DisplayUtil;

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

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TopFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TopFragment extends BaseFragment {

    // 添加Handler用于定时刷新
    private static final long REFRESH_INTERVAL = 3000; // 3秒刷新间隔
    private final Handler autoRefreshHandler = new Handler(Looper.getMainLooper());
    private final List<HomeDefBean.DataBean.RoomBean> mRoomList = new ArrayList<>();
    private FragmentTopBinding mBinding;
    private int position;
    private TopDevicegridAdapter gradapter;
    private TopDeviceAdapter listadapter;
    private TopModelAdapter modelAdapter;
    private HomeBase mHomeBase;
    private String mCurrentCity;
    private String mSelectedRoomId;
    private int type = LocalCache.getDeviceListType();//1是list 2 是 grid
    private MainViewModel mViewModel;
    private MessageViewModel mMessageViewModel;
    private final Runnable autoRefreshRunnable = new Runnable() {
        @Override
        public void run() {
            if (isAdded() && !isDetached()) {
                mViewModel.loadDefaultHome();
                mMessageViewModel.loadMessageCount();
                mViewModel.loadHomeList();
                autoRefreshHandler.postDelayed(this, REFRESH_INTERVAL);
            }
        }
    };
    private CommonPopupWindow addMenuPopupWindow;

    public TopFragment() {
        // Required empty public constructor
    }

    public static TopFragment newInstance(String param1, String param2) {
        TopFragment fragment = new TopFragment();
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mBinding = FragmentTopBinding.inflate(inflater, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mViewModel = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
        mMessageViewModel = new ViewModelProvider(requireActivity()).get(MessageViewModel.class);
        initView();
        observeViewModel();
    }

    @SuppressLint("NotifyDataSetChanged")
    private void observeViewModel() {
        mViewModel.getErrorMessage().observe(getViewLifecycleOwner(), this::showMessage);
        mViewModel.getSelectedHome().observe(getViewLifecycleOwner(), home -> {
            mHomeBase = home;
            mBinding.jiating.setText(mHomeBase.getName());
            reloadData();
        });
        mViewModel.getHomeDef().observe(getViewLifecycleOwner(), data -> {
            if (data == null) {
                return;
            }

            if (TextUtils.isEmpty(mCurrentCity) && !TextUtils.isEmpty(data.city)) {
                mCurrentCity = data.city;
                reloadData();
                return;
            }

            mCurrentCity = data.city;
            if (!TextUtils.isEmpty(mCurrentCity)) {
                mBinding.diqu.setText(mCurrentCity);
                mBinding.diqu.setOnClickListener(v -> {
                });
            } else {
                mBinding.diqu.setText("点击设置位置");
                mBinding.diqu.setOnClickListener(v -> HomeCreateActivity.initHomeAddress(requireContext()));
            }

            //如果房间列表不为空
            if (data.room != null && !data.room.isEmpty()) {
                boolean changed = false;
                //如果现有的房间列表和新获取的房间列表数量不同，则直接刷新列表页签。
                if (mRoomList.size() == data.room.size()) {
                    for (int i = 0; i < data.room.size(); i++) {
                        HomeDefBean.DataBean.RoomBean newRoom = data.room.get(i);
                        HomeDefBean.DataBean.RoomBean oldRoom = mRoomList.get(i);
                        if (oldRoom.record_id.equals(newRoom.record_id) && oldRoom.name.equals(newRoom.name)) {
                            continue;
                        }

                        changed = true;
                        break;
                    }
                } else {
                    changed = true;
                }

                mRoomList.clear();
                mRoomList.addAll(data.room);
                if (changed) {
                    position = 0;
                    mBinding.toptabLayout.removeAllTabs();
                    for (int i = 0; i < data.room.size(); i++) {
                        TabLayout.Tab tab = mBinding.toptabLayout.newTab();
                        tab.setText(data.room.get(i).name);
                        mBinding.toptabLayout.addTab(tab);
                        mBinding.toptabLayout.clearDisappearingChildren();
                        if (!TextUtils.isEmpty(mSelectedRoomId) && mSelectedRoomId.equals(data.room.get(i).record_id)) {
                            position = i;
                            tab.select();
                        }
                    }
                    LogUtils.d("tabList发生改变，需要刷新tabList，当前选择的tab为：" + position);
                } else {
                    LogUtils.d("tabList未发生改变，不需要刷新tabList，当前position为：" + position);
                }

                setDeviceAdapter(mRoomList.get(position).devices);
            } else {
                if (gradapter != null) {
                    listadapter = new TopDeviceAdapter(new ArrayList<>(), null);
                    mBinding.device.setAdapter(listadapter);
                    gradapter.notifyDataSetChanged();
                } else if (listadapter != null) {
                    gradapter = new TopDevicegridAdapter(new ArrayList<>(), null);
                    mBinding.device.setAdapter(gradapter);
                    listadapter.notifyDataSetChanged();
                }
            }
        });

        mViewModel.getWeatherInfo().observe(getViewLifecycleOwner(), data -> {
            if (data != null && !TextUtils.isEmpty(data.temperature) && !TextUtils.isEmpty(data.humidity)) {
                mBinding.wendu.setVisibility(View.VISIBLE);
                mBinding.shidu.setVisibility(View.VISIBLE);
                mBinding.wendu.setText(data.temperature + "℃");
                mBinding.shidu.setText(data.humidity + "%");
            } else {
                mBinding.wendu.setVisibility(View.GONE);
                mBinding.shidu.setVisibility(View.GONE);
            }
        });

        mViewModel.getModelList().observe(getViewLifecycleOwner(), data -> {
            if (data != null) {
                mBinding.moshi.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
                modelAdapter = new TopModelAdapter(data, id -> mViewModel.doScene(id));
                mBinding.moshi.setAdapter(modelAdapter);
                modelAdapter.notifyDataSetChanged();
            }
        });

        mViewModel.getDeviceControlResult().observe(getViewLifecycleOwner(), success -> {
            if (success) {
                showMessage("操作成功");
                if (mHomeBase != null) {
                    //获取场景信息
                    mViewModel.loadScenes(mHomeBase.getId());
                }
            }
        });
        mMessageViewModel.getMessageCount().observe(getViewLifecycleOwner(), listBean -> {
            if (listBean == null) {
                return;
            }

            mBinding.tvRedPoint.setVisibility(listBean.unread_total > 0 ? View.VISIBLE : View.GONE);
        });
    }

    private void initView() {
        // 初始化下拉刷新控件
        mBinding.swipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light
        );

        mBinding.swipeRefreshLayout.setOnRefreshListener(this::reloadData);

        mBinding.addmeun.setOnClickListener(v -> {
            if (addMenuPopupWindow == null) {
                addMenuPopupWindow = new CommonPopupWindow(requireActivity());
                addMenuPopupWindow.addMenuItem("添加设备", R.drawable.ic_add_device, view ->
                        IntentUtils.intentToAddDevice(requireContext()));
                addMenuPopupWindow.addMenuItem("创建场景", R.drawable.ic_create_scene, v1 ->
                        WebViewActivity.newIntent(requireContext(), BASE_URL2 + "/#/scene/:" + LocalCache.getDefaultHomeId(), null));
//                addMenuPopupWindow.addMenuItem("扫描二维码", R.drawable.ic_scan_qr, v1 ->
//                        WebViewActivity.newIntent(requireContext(), "file:///android_asset/index.html", null));
                addMenuPopupWindow.addMenuItem("邀请家人", R.drawable.ic_invite_family, v1 -> {
                    Intent intent = new Intent(getActivity(), InviteActivity.class);
                    intent.putExtra("homeid", LocalCache.getDefaultHomeId());
                    intent.putExtra("home_name", mHomeBase.getName());
                    requireContext().startActivity(intent);
                });
            }
            addMenuPopupWindow.show(mBinding.addmeun, 0, DisplayUtil.dip2px(requireContext(), 16));
        });

        mBinding.listmeun.setOnClickListener(v -> showListPopupWindow());

        mBinding.jiating.setOnClickListener(v -> {
            if (getActivity() instanceof MainActivityTab) {
                ((MainActivityTab) getActivity()).showHomeListWindow(mBinding.jiating);
            }
        });
        mBinding.message.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), MessageListActivity.class);
            requireContext().startActivity(intent);
        });

        mBinding.toptabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                position = tab.getPosition();
                LogUtils.d("tab.position: " + position + " " + tab.isSelected());
                if (mRoomList.size() > position) {
                    mSelectedRoomId = mRoomList.get(position).record_id;
                    setDeviceAdapter(mRoomList.get(position).devices);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    private void showListPopupWindow() {
        CommonPopupWindow listMenuPopupWindow = new CommonPopupWindow(requireActivity());
        listMenuPopupWindow.addMenuItem(type == 1 ? "宫格显示" : "列表显示",
                type == 1 ? R.drawable.ic_grid : R.drawable.ic_list, v1 -> {
                    type = type == 1 ? 2 : 1;
                    LocalCache.saveDeviceListType(type);
//                    mBinding.listmeun.setImageDrawable(ContextCompat.getDrawable(requireContext(), type == 2 ? R.drawable.ic_grid : R.drawable.moremnue));
                    if (mRoomList.size() > position) {
                        setDeviceAdapter(mRoomList.get(position).devices);
                    }
                });
        listMenuPopupWindow.addMenuItem("设备管理", R.drawable.ic_device_manage, v1 -> {
            Intent intent = new Intent(getActivity(), DeviceManageActivity.class);
            requireContext().startActivity(intent);
        });
        listMenuPopupWindow.addMenuItem("房间管理", R.drawable.ic_room_manage, v1 ->
                IntentUtils.gotoRoomManage(requireContext(), null));
        listMenuPopupWindow.show(mBinding.listmeun, 0, DisplayUtil.dip2px(requireContext(), 16));
    }

    @Override
    public void onResume() {
        super.onResume();
        mMessageViewModel.loadMessageCount();
        mViewModel.loadDefaultHome();
        // 启动定时刷新
        startAutoRefresh();
    }

    @Override
    public void onPause() {
        super.onPause();
        // 停止定时刷新
        stopAutoRefresh();
    }

    @Override
    public void onDestroyView() {
        // 确保停止定时刷新
        stopAutoRefresh();
        super.onDestroyView();
        if (addMenuPopupWindow != null) {
            addMenuPopupWindow.dismiss();
            addMenuPopupWindow = null;
        }
        mBinding = null;
    }

    /**
     * 启动定时刷新
     */
    private void startAutoRefresh() {
        stopAutoRefresh(); // 先停止之前的定时任务
        autoRefreshHandler.postDelayed(autoRefreshRunnable, REFRESH_INTERVAL);
    }

    /**
     * 停止定时刷新
     */
    private void stopAutoRefresh() {
        autoRefreshHandler.removeCallbacks(autoRefreshRunnable);
    }

    /**
     * 刷新数据
     */
    private void reloadData() {
        LogUtils.d("reloadData");
        mMessageViewModel.loadMessageCount();
        // 重新获取默认家庭数据
        mViewModel.loadDefaultHome();

        if (mHomeBase != null) {
            //获取场景信息
            mViewModel.loadScenes(mHomeBase.getId());
            if (!TextUtils.isEmpty(mCurrentCity)) {
                //获取天气信息
                mViewModel.loadWeather(mHomeBase.getId(), mCurrentCity);
            }
        }

        // 刷新完成后停止刷新动画
        mBinding.swipeRefreshLayout.setRefreshing(false);
    }

    /**
     * 控制设备
     */
    private void deviceControl(HomeDefBean.DataBean.RoomBean.DevicesBean bean, Boolean ispower) {
        mViewModel.loadDeviceControl(bean.device_code, ispower, bean.sub_code);
    }

    private void setDeviceAdapter(List<HomeDefBean.DataBean.RoomBean.DevicesBean> devices) {
        // 检查设备列表是否为空
        if (devices == null || devices.isEmpty()) {
            // 显示空状态视图
            mBinding.device.setVisibility(View.GONE);
            mBinding.emptyStateLayout.getRoot().setVisibility(View.VISIBLE);
            mBinding.emptyStateLayout.btnAddDevice.setOnClickListener(v ->
                    IntentUtils.intentToAddDevice(requireContext())
            );
            return;
        }

        // 有设备数据时显示列表
        mBinding.device.setVisibility(View.VISIBLE);
        mBinding.emptyStateLayout.getRoot().setVisibility(View.GONE);

        if (type == 1) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) mBinding.device.getLayoutManager();
            int firstVisiblePosition = 0;
            if (layoutManager != null) {
                firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
            }
            mBinding.device.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
            listadapter = new TopDeviceAdapter(devices, (position, isChecked) -> {
                if (devices.size() > position && devices.get(position).device_code != null) {
                    deviceControl(devices.get(position), isChecked);
                }
            });
            mBinding.device.setAdapter(listadapter);
            // 恢复滚动位置
            mBinding.device.scrollToPosition(firstVisiblePosition);
        } else {
            mBinding.device.setLayoutManager(new GridLayoutManager(getContext(), 2));
            gradapter = new TopDevicegridAdapter(devices, (position, isChecked) -> {
                if (devices.size() > position && devices.get(position).device_code != null) {
                    deviceControl(devices.get(position), isChecked);
                }
            });
            mBinding.device.setAdapter(gradapter);
        }
    }
}