package com.ccwangluo.im.adapter;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ccwangluo.ccim.CCIMClient;
import com.ccwangluo.ccim.listener.ResultEventCallback;
import com.ccwangluo.ccim.modle.Contact;
import com.ccwangluo.ccim.modle.ContactGroup;
import com.ccwangluo.ccim.modle.Dialog;
import com.ccwangluo.im.R;
import com.ccwangluo.im.data.LoginViewModel;
import com.ccwangluo.im.listener.OnContactClickLisener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

public class ContactExpandableAdapter extends BaseExpandableListAdapter {

    private Context context;
    private List<ContactGroup> dataEntity = new ArrayList<>();
    private HashMap<Long, List<Contact>> listMap = new HashMap();
    private LoginViewModel loginViewModel;

    private OnContactClickLisener onContactClickLisener;

    public ContactExpandableAdapter(Context context, List<ContactGroup> dataEntity, List<Contact> datachild, LoginViewModel loginViewModel,OnContactClickLisener onContactClickLisener) {
        this.loginViewModel = loginViewModel;
        this.context = context;
        this.dataEntity.addAll(dataEntity);
        this.onContactClickLisener = onContactClickLisener;
        if (datachild == null || datachild.size() == 0) {
            return;
        }
        for (Contact contact : datachild) {
            long contactGroupId = contact.getContactGroupId();
            List<Contact> contacts = listMap.get(contactGroupId);
            if (contacts == null) {
                contacts = new ArrayList<>();
                listMap.put(contactGroupId, contacts);
            }
            contacts.add(contact);
        }
        ContactGroup contactGroup = new ContactGroup(0L, "未分组");
        dataEntity.add(contactGroup);
    }

    /**
     * 获取组的数目
     *
     * @return 返回一级列表组的数量
     */
    @Override
    public int getGroupCount() {
        return dataEntity == null ? 0 : dataEntity.size();
    }

    /**
     * 获取指定组中的子节点数量
     *
     * @param groupPosition 子元素组所在的位置
     * @return 返回指定组中的子数量
     */
    @Override
    public int getChildrenCount(int groupPosition) {
        List<Contact> contacts = listMap.get(dataEntity.get(groupPosition).getGroupId());
        return contacts == null ? 0 : contacts.size();
    }

    /**
     * 获取与给定组相关联的对象
     *
     * @param groupPosition 子元素组所在的位置
     * @return 返回指定组的子数据
     */
    @Override
    public Object getGroup(int groupPosition) {
        ContactGroup contactGroup = dataEntity.get(groupPosition);
        return contactGroup;
    }


    /**
     * 获取与给定组中的给定子元素关联的数据
     *
     * @param groupPosition 子元素组所在的位置
     * @param childPosition 子元素的位置
     * @return 返回子元素的对象
     */
    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return Objects.requireNonNull(listMap.get(dataEntity.get(groupPosition).getGroupId())).get(childPosition);
    }

    /**
     * 获取组在给定位置的ID（唯一的）
     *
     * @param groupPosition 子元素组所在的位置
     * @return 返回关联组ID
     */
    @Override
    public long getGroupId(int groupPosition) {
        return 0;
    }


    /**
     * 获取给定组中给定子元素的ID(唯一的)
     *
     * @param groupPosition 子元素组所在的位置
     * @param childPosition 子元素的位置
     * @return 返回子元素关联的ID
     */
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return 0;
    }

    /**
     * @return 确定id 是否总是指向同一个对象
     */
    @Override
    public boolean hasStableIds() {
        return false;
    }

    /**
     * @return 返回指定组的对应的视图 （一级列表样式）
     */
    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        ParentHolder parentHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.parent_item, null);
            parentHolder = new ParentHolder();
            parentHolder.tvParent = convertView.findViewById(R.id.tv_parent);
            convertView.setTag(parentHolder);
        } else {
            parentHolder = (ParentHolder) convertView.getTag();
        }
        parentHolder.tvParent.setText(dataEntity.get(groupPosition).getName());
        parentHolder.tvParent.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                AlertDialog alertDialog = new AlertDialog
                        .Builder(context)
                        .setTitle("是否删除群组")
                        .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                CCIMClient.getInstance().deleteContactGroup(dataEntity.get(groupPosition).getGroupId(), new ResultEventCallback<Void>() {
                                    @Override
                                    public void onSuccess(Void unused) {
                                        loginViewModel.getContactList();
                                    }

                                    @Override
                                    public void onFailed(int errorCode) {

                                    }
                                });
                            }
                        })
                        .setNegativeButton("cancle", null).create();
                alertDialog.show();
                return false;
            }
        });

        return convertView;
    }

    /**
     * @return 返回指定位置对应子视图的视图
     */
    @SuppressLint("SetTextI18n")
    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        final ChildrenHolder childrenHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.text_row_item, null);
            childrenHolder = new ChildrenHolder();
            childrenHolder.contactId = (TextView) convertView.findViewById(R.id.contactId);
            childrenHolder.contactName = (TextView) convertView.findViewById(R.id.contactName);
            childrenHolder.netStatus = (TextView) convertView.findViewById(R.id.netStatus);
            childrenHolder.status = (TextView) convertView.findViewById(R.id.status);
            convertView.setTag(childrenHolder);
        } else {
            childrenHolder = (ChildrenHolder) convertView.getTag();
        }

        List<Contact> dataList = listMap.get(dataEntity.get(groupPosition).getGroupId());

        childrenHolder.contactId.setText("userid: " + dataList.get(childPosition).getContactUserId());
        childrenHolder.contactName.setText("username: " + dataList.get(childPosition).getContactUserName());
        childrenHolder.netStatus.setText("netStatus: " + dataList.get(childPosition).getNetStatus().toString());
//        childrenHolder.status.setText("status: " + dataList.get(childPosition).);
//        childrenHolder.unReadMsg.setText("unReadMsg : " + dataList.get(childPosition).().toString());
        convertView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showAlertDialog(dataList.get(childPosition));
                return false;
            }
        });
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onContactClickLisener.onClick(dataList.get(childPosition));
            }
        });

        return convertView;
    }

    private void showAlertDialog(Contact contact) {
        String[] strings = {"删除联系人", "拉黑联系人", "举报用户", "移动联系人群组"};
        AlertDialog alertDialog = new AlertDialog
                .Builder(context)
                .setItems(strings, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                CCIMClient.getInstance().deleteContact(contact.getContactUserId(), new ResultEventCallback<Void>() {
                                    @Override
                                    public void onSuccess(Void unused) {
                                        loginViewModel.getContactList();
                                    }

                                    @Override
                                    public void onFailed(int errorCode) {

                                    }
                                });
                                break;
                            case 1:
                                CCIMClient.getInstance().blockContact(contact.getContactUserId(), new ResultEventCallback<Void>() {
                                    @Override
                                    public void onSuccess(Void unused) {
                                        loginViewModel.getContactList();
                                    }

                                    @Override
                                    public void onFailed(int errorCode) {

                                    }
                                });
                                break;
                            case 2:
                                final EditText title = new EditText(context);
                                final EditText contentView = new EditText(context);
                                LinearLayout linearLayout = new LinearLayout(context);
                                linearLayout.setOrientation(LinearLayout.VERTICAL);
                                linearLayout.addView(title);
                                linearLayout.addView(contentView);
                                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                builder.setTitle("举报理由").setIcon(android.R.drawable.ic_dialog_info).setView(linearLayout)
                                        .setNegativeButton("Cancel", null);
                                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                                    public void onClick(DialogInterface dialog, int which) {
                                        String reason = title.getText().toString();
                                        String content = contentView.getText().toString();
                                        CCIMClient.getInstance().reportIllegalUser(reason, content, contact.getContactUserId(), new ResultEventCallback<Void>() {
                                            @Override
                                            public void onSuccess(Void unused) {
                                                Toast.makeText(context, "举报成功", Toast.LENGTH_SHORT).show();
                                            }

                                            @Override
                                            public void onFailed(int errorCode) {

                                            }
                                        });

                                    }
                                });
                                builder.show();
                                break;
                            case 3:
                                moveContactGroup(contact);
                                break;
                        }
                    }
                })
                .create();
        alertDialog.show();
    }

    private void moveContactGroup(Contact contact) {
        ArrayList<ContactGroup> contactGroups = new ArrayList<>(loginViewModel.contactGroupList.getValue());
        if (contactGroups.size() > 0) {
            String[] strings = new String[contactGroups.size()];
            for (int i = 0; i < contactGroups.size(); i++) {
                strings[i] = contactGroups.get(i).getName();
            }
            AlertDialog alertDialog = new AlertDialog
                    .Builder(context)
                    .setTitle("group list")
                    .setItems(strings, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            CCIMClient.getInstance().moveContactGroup(contactGroups.get(which).getGroupId(), contact.getContactUserId(), new ResultEventCallback<Void>() {
                                @Override
                                public void onSuccess(Void unused) {
                                    Toast.makeText(context, "移动成功", Toast.LENGTH_SHORT).show();
                                    loginViewModel.getContactList();
                                }

                                @Override
                                public void onFailed(int errorCode) {

                                }
                            });
                        }
                    })
                    .create();
            alertDialog.show();
        }


    }


    /**
     * 指定位置的子元素是否可选
     *
     * @param groupPosition 子元素组所在的位置
     * @param childPosition 子元素的位置
     * @return 返回是否可选
     */

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }


    class ParentHolder {
        TextView tvParent;
    }


    class ChildrenHolder {
        public TextView contactId;
        public TextView contactName;
        public TextView netStatus;
        public TextView status;
    }


    /**
     * 用于刷新更新后的数据
     */
    public void reFreshData(List<ContactGroup> dataEntity, List<Contact> datachild, List<Dialog> dialogs) {
        ContactGroup contactGroup = new ContactGroup(0L, "未分组");
        this.dataEntity.clear();
        if (dataEntity != null) {
            this.dataEntity.addAll(dataEntity);
        }
        listMap.clear();
        if (dialogs != null && dialogs.size() > 0){
            ContactGroup dialogGroup = new ContactGroup(-1L, "最近联系人");
            List<Contact> contacts = listMap.get(dialogGroup.getGroupId());
            if (contacts == null) {
                contacts = new ArrayList<>();
                listMap.put(dialogGroup.getGroupId(), contacts);
            }
            for (Dialog dialog : dialogs) {
                Contact contact = new Contact();
                contact.setContactGroupId(dialogGroup.getGroupId());
                contact.setContactUserId(dialog.getContactUserId());
                contact.setNetStatus(dialog.getNetStatus());
                contact.setContactUserName(dialog.getContactUserName());

                contacts.add(contact);
            }
            this.dataEntity.add(dialogGroup);
        }

        for (Contact contact : datachild) {
            long contactGroupId = contact.getContactGroupId();
            List<Contact> contacts = listMap.get(contactGroupId);
            if (contacts == null) {
                contacts = new ArrayList<>();
                listMap.put(contactGroupId, contacts);
            }
            contacts.add(contact);
        }
        this.dataEntity.add(contactGroup);
        notifyDataSetChanged();
    }


}