package com.rdiot.yx485.room;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.king.zxing.util.LogUtils;
import com.rdiot.yx485.R;
import com.rdiot.yx485.adapter.RoomEditAdapter;
import com.rdiot.yx485.base.BaseFragment;
import com.rdiot.yx485.bean.DeviceRoomListBean;
import com.rdiot.yx485.databinding.ActivityRoomEditBinding;

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

public class RoomListEditableFragment extends BaseFragment {
    private ActivityRoomEditBinding mBinding;
    private RoomEditAdapter mAdapter;
    private final List<DeviceRoomListBean.RoomBean> mRoomList = new ArrayList<>();
    private RoomViewModel mViewModel;

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

    /**
     * 设备房间
     */
    private void initData() {
        mViewModel = new ViewModelProvider(requireActivity()).get(RoomViewModel.class);
        mViewModel.getRoomList().observe(getViewLifecycleOwner(), this::setupRecyclerView);
    }

    private void setupRecyclerView(List<DeviceRoomListBean.RoomBean> data) {
        mRoomList.clear();
        if (data == null || data.isEmpty()) {
            mBinding.tvDataEmpty.setText("暂无数据");
        } else {
            mBinding.tvDataEmpty.setText("");
            mRoomList.addAll(data);
        }
        mAdapter = new RoomEditAdapter(mRoomList, this::showDeleteRoomDialog);
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        mBinding.recyclerView.setAdapter(mAdapter);

        // 设置拖动排序功能
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(
                ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView,
                                  @NonNull RecyclerView.ViewHolder viewHolder,
                                  @NonNull RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAbsoluteAdapterPosition();
                int toPosition = target.getAbsoluteAdapterPosition();
                LogUtils.d("onMove:" + fromPosition + " " + toPosition);

                // 交换数据
                Collections.swap(mAdapter.getData(), fromPosition, toPosition);
                mAdapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
//                 不需要实现，因为我们只支持拖动
            }

            @Override
            public void clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                mViewModel.updateRoomOrder(mAdapter.getData());
            }
        });

        itemTouchHelper.attachToRecyclerView(mBinding.recyclerView);
    }

    private void showDeleteRoomDialog(String roomId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_detele_room, null);
        builder.setView(dialogView);

        TextView btnCancel = dialogView.findViewById(R.id.btn_cancel);
        TextView btnOk = dialogView.findViewById(R.id.btn_ok);

        final AlertDialog dialog = builder.create();
        dialog.setTitle("删除房间");

        btnCancel.setOnClickListener(v -> dialog.dismiss());

        btnOk.setOnClickListener(v -> {
            if (getActivity() instanceof RoomManageActivity) {
                ((RoomManageActivity) getActivity()).deleteRoom(roomId);
            }
            dialog.dismiss();
        });

        dialog.show();
    }
}
