package com.rv.im;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
import com.rv.im.adapter.CustomerListAdapter;
import com.rv.im.bean.CustomersBean;
import com.rv.im.db.service.ChatMessageServiceImp;
import com.rv.im.db.service.CustomerServiceImp;
import com.rv.im.db.service.ICustomerService;
import com.rv.im.db.table.ChatMessage;
import com.rv.im.db.table.Customer;
import com.rv.im.util.ServiceUtils;
import com.rv.im.xmpp.ListenerManager;
import com.rv.im.xmpp.listener.ChatMessageListener;

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

public class CustomerListActivity extends BaseStatusActivity<CommonPresenter> implements SimpleRefreshLayout.OnSimpleRefreshListener, ChatMessageListener {

    private SimpleRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private List<Customer> customers = new ArrayList<>();
    private CustomerListAdapter adapter = null;

    private int testTime = 0;

    @Override
    protected int setLayout() {
        return R.layout.activity_customer_list;
    }


    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        ListenerManager.getInstance().addChatMessageListener(this);
        titleView.setTitle("客服列表");

        titleView.setImageResource(R.id.iv_title_right, R.drawable.ic_app_add);
        titleView.setChildClickListener(R.id.iv_title_right, v -> {
            if (!BuildConfig.DEBUG) return;
            testTime += 1;
            if (testTime == 5) {
                testTime = 0;
                if (ServiceUtils.isServiceRunning(CustomerListActivity.this)) {
                    Toast.makeText(getApplicationContext(), "im服务正在运行", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "im服务挂掉", Toast.LENGTH_SHORT).show();
                }
            }
        });

        refreshLayout = findViewById(R.id.refresh);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL, false));
        adapter = new CustomerListAdapter(getApplicationContext(), customers);
        adapter.setOnItemClickListener((adapter, view, position) -> {
            Customer customer = customers.get(position);
            startActivityForResult(ChatActivity.getIntent(getApplicationContext(), customer.getImUserId(), customer.getName()), 1);
        });
        refreshLayout.setHeaderView(new SimpleRefreshView(this));
        refreshLayout.setOnSimpleRefreshListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        getCustomerList();
    }

    /******
     * 获取客服列表
     */
    private void getCustomerList() {
        List<Customer> lists = getCustomService().getCustomerLists();
        if (lists != null && lists.size() > 0) {
            for (Customer customer : lists) {
                ChatMessage message = ChatMessageServiceImp.getInstance(getApplicationContext()).getLastMsg(customer.getImUserId());
                if (message != null) customer.setLastMessageInfo(message);
            }
            Collections.sort(lists, (o1, o2) -> {
                if (o1.getLastMsgTimes() > o2.getLastMsgTimes()) {
                    return -1;
                } else if (o1.getLastMsgTimes() == o2.getLastMsgTimes()) {
                    return 0;
                }
                return 1;
            });
            customers.clear();
            customers.addAll(lists);
            adapter.notifyDataSetChanged();
        } else {
            mPresenter.getData(0, ImUrlConfig.HTTP_CUSTOMER_LIST_URL, CustomersBean.class, true);
        }
    }

    private boolean isRefresh = false;

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        if (requestType == 0) {
            CustomersBean bean = (CustomersBean) result;
            if (bean != null && bean.isRel() && bean.getData() != null && bean.getData().size() > 0) {
                if (isRefresh) {
                    refreshLayout.onRefreshComplete();
                    isRefresh = false;
                }
                customers.clear();
                customers.addAll(bean.getData());
                adapter.notifyDataSetChanged();
                getCustomService().addCustomers(customers);
            }
        }
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        mPresenter.getData(0, ImUrlConfig.HTTP_CUSTOMER_LIST_URL, CustomersBean.class, true);
    }

    private ICustomerService iCustomerService;

    private ICustomerService getCustomService() {
        if (iCustomerService == null) {
            iCustomerService = CustomerServiceImp.getInstance(getApplicationContext());
        }
        return iCustomerService;
    }

    @Override
    public void onMessageSendStateChange(int messageState, String msgId) {

    }

    @Override
    public void onNewMessage(String fromUserId, ChatMessage message, boolean isGroupMsg) {
        getCustomerList();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) { // 刷新UI
            getCustomerList();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ListenerManager.getInstance().removeChatMessageListener(this);
    }
}
