package com.rdiot.yx485.home;

import android.content.Intent;
import android.os.Bundle;

import androidx.lifecycle.ViewModelProvider;

import com.google.android.material.tabs.TabLayoutMediator;
import com.rdiot.yx485.BaseActivity;
import com.rdiot.yx485.adapter.HomePagerAdapter;
import com.rdiot.yx485.bean.HomeResultBean;
import com.rdiot.yx485.databinding.ActivityHomeBinding;
import com.rdiot.yx485.util.LocalCache;

public class HomeActivity extends BaseActivity {
    private ActivityHomeBinding mBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityHomeBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());

        initView();
        initData();
    }

    private void initData() {
        HomeViewModel viewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        viewModel.getErrorMessage().observe(this, this::showMessage);
        viewModel.getDeleteState().observe(this, success -> {
            if (success) {
                showMessage("删除成功");
                onBackPressed();
            }
        });
        viewModel.getHomeList().observe(this, list -> {
            HomePagerAdapter adapter = new HomePagerAdapter(this, list);
            mBinding.viewPager.setAdapter(adapter);
            mBinding.viewPager.setUserInputEnabled(false);
            // 联动 TabLayout 和 ViewPager2
            new TabLayoutMediator(mBinding.tabLayout, mBinding.viewPager, (tab, position) -> {
                tab.setText(list.get(position).name); // 设置 Tab 的标题
            }).attach();
            String homeId = LocalCache.getDefaultHomeId();
            for (HomeResultBean.HomeInfo info : list) {
                if (homeId.equals(info.record_id)) {
                    mBinding.viewPager.setCurrentItem(list.indexOf(info));
                    return;
                }
            }
        });
        viewModel.loadAllCities("1");
        viewModel.loadHomeList(false);
    }

    private void initView() {
        mBinding.layoutTitle.tvTitle.setText("我的家庭");
        mBinding.layoutTitle.btnTitleLeft.setOnClickListener(view -> finish());
        mBinding.layoutTitle.btnTitleRight.setText("新建家庭");
        mBinding.layoutTitle.btnTitleRight.setOnClickListener(view -> {
            Intent intent = new Intent();
            intent.setClass(HomeActivity.this, HomeCreateActivity.class);
            startActivity(intent);
            finish();
        });
    }
}