package com.rv.im;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
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.component.utils.CacheEnum;
import com.rv.component.utils.RvCache;
import com.rv.im.adapter.CustomerListAdapter;
import com.rv.im.bean.CustomersBean;
import com.rv.im.bean.User;
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.RvImTimerTask;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;

import okhttp3.Call;

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 Timer timer;
    private RvImTimerTask timerTask;

    private Map<String, Integer> customerStatus = new HashMap<>();

    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("客服列表");
        timer = new Timer();
        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, customerStatus);
        adapter.setOnItemClickListener((adapter, view, position) -> {
            Customer customer = customers.get(position);
            startActivityForResult(ChatActivity.getIntent(getApplicationContext(), customer.getImUserId(), customer.getName(),
                    customerStatus.get(customer.getImUserId()) == null ? 0 : customerStatus.get(customer.getImUserId()).intValue()), 1);
        });
        refreshLayout.setHeaderView(new SimpleRefreshView(this));
        refreshLayout.setOnSimpleRefreshListener(this);
        recyclerView.setAdapter(adapter);
        checkOverlayPermission();
    }

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

    /********
     * 检查滴房车是否能在其他应用上层显示
     */
    private void checkOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                new AlertDialog.Builder(this).setTitle("提示")
                        .setMessage("允许在手机上层显示,实时获知新消息")
                        .setNegativeButton("下次再说", (dialogInterface, i) -> {
                            dialogInterface.dismiss();
                        }).setPositiveButton("好的", (dialogInterface, i) -> {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }).setCancelable(false).show();
            }
        }
    }

    /******
     * 获取客服列表
     */
    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();
            if (timerTask == null) {
                timerTask = new RvImTimerTask(timerListener);
                timer.schedule(timerTask, 100, 10000);
            }
        } 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();
                if (timerTask == null) {
                    timerTask = new RvImTimerTask(timerListener);
                    timer.schedule(timerTask, 100, 10000);
                }
                getCustomService().addCustomers(customers);
            }
        } else if (requestType == 1) {
            User user = (User) result;
            if (user != null && user.getData() != null && customers != null) {
                int position = 0;
                if (!TextUtils.isEmpty(user.getData().getUserId())) {
                    customerStatus.remove(user.getData().getUserId());
                    customerStatus.put(user.getData().getUserId(), user.getData().getOnlinestate());
                }

                for (int i = 0; i < customers.size(); i++) {
                    Customer customer = customers.get(i);
                    if (!TextUtils.isEmpty(user.getData().getUserId()) && user.getData().getUserId().equals(customer.getImUserId())) {
                        position = i;
                        break;
                    }
                }
                adapter.notifyItemChanged(position);
            }
        }
    }

    @Override
    public void onShowError(String errorMsg, int errorType) {
        super.onShowError(errorMsg, errorType);
        if(isRefresh) {
            refreshLayout.onRefreshComplete();
            isRefresh = false ;
        }
    }

    @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) {
        if (customers != null && customers.size() > 0) {
            for (Customer customer : customers) {
                if (!TextUtils.isEmpty(customer.getImUserId()) &&
                        customer.getImUserId().equals(fromUserId)) {
                    if (message != null)
                        customer.setLastMessageInfo(message);
                    break;
                }
            }
        }
        Collections.sort(customers, (o1, o2) -> {
            if (o1.getLastMsgTimes() > o2.getLastMsgTimes()) {
                return -1;
            } else if (o1.getLastMsgTimes() == o2.getLastMsgTimes()) {
                return 0;
            }
            return 1;
        });
        adapter.notifyDataSetChanged();
    }

    @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);
        if (timer != null)
            timer.cancel();
        if (timerTask != null)
            timerTask.cancel();
    }

    private RvImTimerTask.TimerListener timerListener = () -> runOnUiThread(() -> {
        AppConfig appConfig = (AppConfig) RvCache.getInstance().get(CacheEnum.IM_CONFIG);
        if (appConfig != null && !TextUtils.isEmpty(appConfig.USER_GET_URL))
            if (customers != null && customers.size() > 0)
                for (Customer customer : customers) {
                    if (customer != null)
                        initFriendState(appConfig.USER_GET_URL, customer);
                }
    });

    private void initFriendState(String url, Customer customer) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", ImSetting.getImToken());
        params.put("userId", customer.getImUserId());
        mPresenter.getData(1, url, User.class, params, false);
    }

}
