package com.rdiot.yx485;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.lifecycle.ViewModelProvider;

import com.rdiot.yx485.bean.HomeBase;
import com.rdiot.yx485.bean.HomeResultBean;
import com.rdiot.yx485.databinding.ActivityInviteBinding;
import com.rdiot.yx485.home.HomeViewModel;

public class InviteActivity extends BaseActivity {
    private ActivityInviteBinding mBinding;
    private HomeViewModel mViewModel;

    public static Intent newIntent(Context context, HomeResultBean.HomeInfo info) {
        Intent intent = new Intent();
        intent.setClass(context, InviteActivity.class);
        intent.putExtra("homeid", info.record_id);
        intent.putExtra("home_name", info.name);
        return intent;
    }

    public static void newIntent(Context context, HomeBase info) {
        Intent intent = new Intent();
        intent.setClass(context, InviteActivity.class);
        intent.putExtra("homeid", info.getId());
        intent.putExtra("home_name", info.getName());
        context.startActivity(intent);
    }

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

        mViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        initView();
        observeViewModel();
    }

    private void initView() {
        Intent intent = getIntent();
        String home_id = intent.getStringExtra("homeid");
        String home_name = intent.getStringExtra("home_name");
        if (!TextUtils.isEmpty(home_name)) {
            mBinding.homename.setText("邀请家人加入" + home_name);
        }
        mBinding.layoutTitle.tvTitle.setText("邀请家人");
        mBinding.layoutTitle.btnTitleLeft.setOnClickListener(view -> onBackPressed());
        mBinding.btnInvite.setOnClickListener(view -> {
            String phone = mBinding.etPhone.getText().toString();
            if (TextUtils.isEmpty(phone)) {
                showMessage("请输入手机号");
                return;
            }
            mViewModel.inviteMember(phone, home_id);
        });
    }

    private void observeViewModel() {
        mViewModel.getInviteResult().observe(this, success -> {
            if (success) {
                showMessage("邀请成功");
                Intent intent = new Intent();
                intent.putExtra("changed", true);
                setResult(RESULT_OK, intent);
                onBackPressed();
            }
        });

        mViewModel.getErrorMessage().observe(this, this::showMessage);
    }
}