package com.bokecc.room.ui.view.userList;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.bokecc.common.utils.Tools;
import com.bokecc.sskt.base.common.dialog.CustomDialog;
import com.bokecc.room.ui.R;
import com.bokecc.room.ui.model.RoomUser;
import com.bokecc.room.ui.view.menu.MenuTopView;
import com.bokecc.sskt.base.CCAtlasClient;
import com.bokecc.sskt.base.bean.CCUser;
import com.bokecc.sskt.base.callback.CCAtlasCallBack;
import com.bokecc.sskt.base.common.network.CCRequestCallback;

import org.json.JSONArray;
import org.json.JSONObject;

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

/**
 * 用户列表视图
 *
 * @author wy
 */
public class UserListDialog extends CustomDialog {

    private MenuTopView.MenuTopListener mListener;

    private ExpandableListView elv;

    private ExpandableListViewAdapter expandableListViewAdapter;

    /**互动人数*/
    private List<RoomUser> mRoomUsers = new ArrayList<>();

    /**
     * 用户
     * 一级分类，二级用户列表
     */
    private List<List<RoomUser>> mRoomUsersList = new ArrayList<>();

    private Context context;

    private int audienceCount = 0;

    private String[] groups = {"互动","旁听"};

    /**
     * 标题
     */
    private TextView title;

    public UserListDialog(Context context, MenuTopView.MenuTopListener listener) {
        super(context);
        this.context = context;
        this.mListener = listener;

        mRoomUsersList.clear();
        mRoomUsersList.add(new ArrayList<RoomUser>());
        mRoomUsersList.add(new ArrayList<RoomUser>());

        initData();
    }

    /**
     * 初始化数据
     */
    public void initData() {
        if (!isShowing()) show();

        anim.start();
        //获取互动人员
        CCAtlasClient.getInstance().getRewardHistory(new CCAtlasCallBack<ArrayList<CCUser>>() {
            @Override
            public void onSuccess(final ArrayList<CCUser> users) {
                transformUser(users);
                //获取旁听人员
                CCAtlasClient.getInstance().getAuditList(new CCRequestCallback<JSONObject>() {
                    @Override
                    public void onSuccess(JSONObject jsonObject) {
                        anim.stop();
                        anim.setOneShot(true);

                        audienceCount = jsonObject.optInt("viewer_count");

                        ArrayList<RoomUser> roomUsers = new ArrayList<>();

                        JSONArray viewUsers = jsonObject.optJSONArray("view_users");
                        if(viewUsers != null && viewUsers.length() > 0){
                            for(int i=0;i<viewUsers.length();i++){
                                RoomUser roomUser = new RoomUser();
                                JSONObject userJson = viewUsers.optJSONObject(i);
                                if(userJson != null){
                                    String userName = userJson.optString("user_name");
//                                    int platform = userJson.optInt("platform");

                                    CCUser user = new CCUser();
                                    user.setUserName(userName);
                                    user.setPlatForm(-1);
                                    user.setUserRole(CCAtlasClient.AUDITOR);
                                    roomUser.setUser(user);
                                    roomUsers.add(roomUser);
                                }
                            }
                        }

                        title.setText((users.size()+audienceCount)+ Tools.getString(R.string.cc_menu_people_num));

                        mRoomUsersList.set(1,roomUsers);

                        expandableListViewAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(int errorCode, String errorMsg) {
                        anim.stop();
                        anim.setOneShot(true);
                        Tools.showToast(errorMsg);
                    }
                });
            }

            @Override
            public void onFailure(int errCode, String errMsg) {
                anim.stop();
                anim.setOneShot(true);
                Tools.showToast(errMsg);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.view_user_list_layout);

        setCanceledOnTouchOutside(false);
        super.onCreateMatchParent(savedInstanceState);

        setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return false;
            }
        });

        initView();
    }

    private AnimationDrawable anim;

    /**
     * 初始化视图和适配器
     */
    private void initView() {
        title = findViewById(R.id.id_list_title);

        findViewById(R.id.id_list_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        anim = (AnimationDrawable)findViewById(R.id.id_list_flush).getBackground();
        findViewById(R.id.id_list_flush).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
            }
        });

        expandableListViewAdapter = new ExpandableListViewAdapter(context,groups,mRoomUsersList);

        elv = findViewById(R.id.user_list_elv);
        elv.setAdapter(expandableListViewAdapter);
        elv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v,int groupPosition,int childPosition, long id) {
                try{
                    if(CCAtlasClient.getInstance().getRole() == CCAtlasClient.PRESENTER){
                        CCUser user = mRoomUsersList.get(groupPosition).get(childPosition).getUser();
                        mListener.onClickUser(user,childPosition);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                return false;
            }
        });
        //用于当组项折叠时的通知。
        elv.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
//                showToastShort("折叠了数据___"+groups[groupPosition]);
            }
        });
        //用于当组项折叠时的通知。
        elv.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
//                showToastShort("展开了数据___"+groups[groupPosition]);
            }
        });

    }

    /**
     * 更新数据
     *
     * @param users
     */
    public void updateData(ArrayList<CCUser> users) {
        transformUser(users);
        title.setText((users.size()+audienceCount)+Tools.getString(R.string.cc_menu_people_num));
        expandableListViewAdapter.notifyDataSetChanged();
        if (!isShowing()) show();
    }

    /**
     * 转换用户
     *
     * @param users
     */
    private void transformUser(ArrayList<CCUser> users) {
        if (users == null || users.size() <= 0) {
            return;
        }
        mRoomUsers.clear();

        ArrayList<RoomUser> compareUsers = new ArrayList<>();
        int index = 0;
        for (CCUser user : users) {
//            if (mUserPopup.isShowing()) { // 如果弹出框显示，更新当前选中的用户状态
//                if (mCurUser != null && user.getUserId().equals(mCurUser.getUserId())) {
//                    updateOrShowUserPopup(user);
//                }
//            }
            RoomUser roomUser = new RoomUser();
            roomUser.setUser(user);
            if (user.getLianmaiStatus() == CCAtlasClient.LIANMAI_STATUS_IN_MAI ||
                    user.getLianmaiStatus() == CCAtlasClient.LIANMAI_STATUS_UP_MAI) {
                compareUsers.add(roomUser);
            } else {
                if (user.getUserRole() == CCAtlasClient.PRESENTER) {
                    mRoomUsers.add(0, roomUser);
                    index++;
                } /*else if (user.getLianmaiStatus() == 3) { // 这段代码实现将连麦中的学生位置定位在老师的下面
                    mRoomUsers.add(index, roomUser);
                    index++;
                }*/ else {
                    mRoomUsers.add(roomUser);
                }
            }
        }
        Collections.sort(compareUsers, new RoomUserComparator());
        int queueIndex = 1;
        for (RoomUser queueUser : compareUsers) {
            queueUser.setMaiIndex(queueIndex++);
        }
        mRoomUsers.addAll(index, compareUsers);
        //添加到总列表中
        mRoomUsersList.set(0,mRoomUsers);
    }

}
