package com.rdiot.yx485.message;

import android.os.Bundle;
import android.view.View;

import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.rdiot.yx485.BaseActivity;
import com.rdiot.yx485.adapter.MessageListAdapter;
import com.rdiot.yx485.bean.MessageListBean;
import com.rdiot.yx485.databinding.ActivityMessageContentListBinding;

import java.util.List;

public class MessageContentListActivity extends BaseActivity {
    String type;
    private ActivityMessageContentListBinding mBinding;
    private MessageViewModel mViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityMessageContentListBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());
        initView();
        initData();
    }

    private void initView() {
        //消息类型 1系统消息（天气、系统通知） 2设备消息（设备故障、设备耗材、场景执行） 3活动消息
        type = getIntent().getStringExtra("type");

        String name = getIntent().getStringExtra("name");
        mBinding.layoutTitle.tvTitle.setText(name);
        mBinding.layoutTitle.btnTitleLeft.setOnClickListener(v -> finish());
        mBinding.layoutTitle.btnTitleRight.setText("全部已读");
        mBinding.layoutTitle.btnTitleRight.setOnClickListener(v -> {
            mViewModel.markAllRead(type);
        });
    }

    private void initData() {
        mViewModel = new ViewModelProvider(this).get(MessageViewModel.class);
        mViewModel.getErrorMessage().observe(this, this::showMessage);
        mViewModel.getMessageList().observe(this, this::setupRecyclerView);
        mViewModel.getReadAllResult().observe(this, success -> {
            if (success) {
                showMessage("全部已读成功");
                mViewModel.loadMessageList(type);
            }
        });
    }

    private void setupRecyclerView(List<MessageListBean.DataBean.MessageInfo> data) {
        if (data == null || data.isEmpty()) {
            mBinding.tvDataEmpty.setVisibility(View.VISIBLE);
        } else {
            mBinding.tvDataEmpty.setVisibility(View.GONE);
        }
        mBinding.rvMessageContent.setLayoutManager(new LinearLayoutManager(this));
        MessageListAdapter myAdapter = new MessageListAdapter(this, data);
        myAdapter.setReadListener(messageId -> mViewModel.markMessageAsRead(messageId));
        mBinding.rvMessageContent.setAdapter(myAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mViewModel.loadMessageList(type);
    }
}