package com.offcn.im.demo.ui;

import android.view.View;
import android.widget.AdapterView;

import com.jyall.base.base.BaseFragment;
import com.jyall.base.util.CommonUtils;
import com.offcn.im.demo.R;
import com.offcn.im.demo.adapter.ContactAdapter;
import com.offcn.im.demo.bean.UserBean;
import com.offcn.im.demo.util.LoginManager;
import com.offcn.im.demo.util.MockData;
import com.offcn.live.im.OIMSDK;
import com.offcn.live.im.bean.OIMSendTypeEnum;

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

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 通讯录页。业务页面，由外部完成，因为平台无通讯录
 */
public class ContactListFragment extends BaseFragment {
    private static final String TAG = ContactListFragment.class.getSimpleName();

    private RecyclerView mRecyclerView;

    private List<UserBean> friends = new ArrayList<>();
    private ContactAdapter mAdapter;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_contact_list;
    }

    @Override
    protected boolean setLoadAlways() {
        return false;
    }

    @Override
    protected void init(View view) {
        mRecyclerView = view.findViewById(R.id.recycler_view);
        mAdapter = new ContactAdapter(getContext(), friends);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UserBean userBean = friends.get(position);
                if (userBean != null) {
                    if(userBean.getUser_id().equals(LoginManager.getUserId(getActivity()))){
                        CommonUtils.showToast(getActivity(), "不能跟自己聊");
                    }else {
                        OIMSDK.getInstance().startChat(getActivity(), OIMSendTypeEnum.PRIVATE, userBean.getUser_id(), userBean.getName(), 0);
                    }
                } else {
                    CommonUtils.showToast(getActivity(), "获取用户信息失败");
                }
            }
        });

        getContactList();
    }


    /**
     * 模拟接口，获取通讯录
     */
    private void getContactList() {
        if (!CommonUtils.isNetConnected(getActivity())) {
            return;
        }

        friends = MockData.getUsers();
        mAdapter.addAll(friends);
        // 保存信息，供内部SDK刷新UI。正常开发会存储数据库，本示例直接由 MockData 提供，不走持久化。
//        UserBeanDaoManager.getInstance().insertMulti(friends);
        // 获得通讯录后刷新，供内部SDK刷新会话列表
        OIMSDK.getInstance().refreshUserData();
    }
}
