package com.efounder.chat.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.item.ChatTipsMessageItem;
import com.efounder.frame.manager.AppLoginManager;
import com.efounder.frame.manager.UrlSchemeManager;
import com.efounder.chat.model.Group;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.GroupOperationHelper;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.widget.ExpandGridView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.groupimageview.NineGridImageView;
import com.groupimageview.NineGridImageViewAdapter;

import org.json.JSONException;
import org.json.JSONObject;

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

import static com.efounder.chat.activity.ChatGroupSettingActivity.setTopView;

/**
 * Created by will on 17-1-10.
 */

public class AddGroupUserInfoActivity extends BaseActivity implements View.OnClickListener {

    private TextView tv_groupname;//群名称
    private TextView tv_m_total;// 成员总数
    private ExpandGridView userGridview;// 人员列表
    private TextView tv_qunjieshao;//群介绍
    private Button addGroupBtn;// 申请加群
    private TextView tv_titleView;//群名称左上方

    private int groupId;
    //群英文名
    private String groupKey;
    private boolean isUrlScheme = false;
    private Group group;
    private boolean added;//是否已经加群

    private boolean isHaveAvatar = false;

    //仿qq 群聊
    private ImageView ivGroupAvatarView;//正常的ImageView显示群头像，有avatar字段情况下
    private NineGridImageView nineGridImageView;
    private TextView tvGroupIdView;
    private TextView userCountView;
    private LinearLayout ll_groupUserLayout;//点击跳转群成员界面

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_group_info);
        initView();
        initData();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GetHttpUtil.release();
    }


    private void initData() {
        

        //1.判断是否是urischme 跳转
        if (UrlSchemeManager.hasUrlScheme(getIntent())) {
            if (!AppLoginManager.isUserLogined()) {
                AppLoginManager.showNotLogInDialog(this);
                setSwipeBackEnable(false);
                return;
            }
            isUrlScheme = true;
            try {
                //groupId = Integer.parseInt(getIntent().getData().getQueryParameter("groupId"));
                groupKey = getIntent().getData().getQueryParameter("groupKey") + "";
            } catch (Exception e) {
                e.printStackTrace();
                groupKey = getIntent().getData().getQuery();
            }
        } else {
            //非urischme
            if (getIntent().hasExtra("stubObject")) {
                //点击消息跳过来
                StubObject stubObject = (StubObject) getIntent().getSerializableExtra("stubObject");
                IMStruct002 imStruct002 = (IMStruct002) stubObject.getStubTable().get("imStruct002");
                String message = imStruct002.getMessage();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(message);
                    groupId = jsonObject.optInt("id");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                //搜索或者其他页面跳过来
                groupId = getIntent().getIntExtra("id", 1);
            }

            added = getIntent().getBooleanExtra("added", false);
            group = WeChatDBManager.getInstance().getGroupWithUsersInGroups(groupId);//从数据库中获取group数据
            groupKey = groupId + "";
        }
        if (group != null) {
            setAddButtonText();
        }

        initNetData();
    }

    private void setAddButtonText() {
        if (!added) {
            // User groupUser = WeChatDBManager.getInstance().getGroupUser(groupId, Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
//            if (groupUser != null) {
//                added = true;
//            }
            if (WeChatDBManager.getInstance().queryMyGroupExist(groupId)) {
                added = true;
            }
        }

        if (added) {
            addGroupBtn.setText(R.string.chat_enter_chat);
        } else {
            if (group.getGroupType() == 0) {
                addGroupBtn.setText(R.string.chat_apply_admission);
            } else {
                addGroupBtn.setText(R.string.chat_join_chat);
            }

        }
    }

    private void initNetData() {
//        if (group != null && group.getUsers().size() == 0) {//成员为0，说明数据库中没有
//            if (!isNetActive()) {//没有网络
//                setTopView(group, tv_groupname, tvGroupIdView, tv_titleView, tv_qunjieshao);
//                return;
//            }

//            try {
//                //先获取group的基本信息，存入数据库后，进行显示
//                GetHttpUtil.getGroupById(AddGroupUserInfoActivity.this, groupId, new GetHttpUtil.getGroupInfoCallBack() {
//
//                    @Override
//                    public void onGetGroupInfoSuccess(Group group) {
//                        if (group==null){
//
//                        }
//                        if (group.getGroupType() == 0) {
//                            addGroupBtn.setText("申请加入");
//                        } else {
//                            addGroupBtn.setText("加入群聊");
//                        }
//                        setTopView(group, tv_groupname, tvGroupIdView, tv_titleView, tv_qunjieshao);
//                        if (!group.getAvatar().equals("")) {
//                            isHaveAvatar = true;
//                            ivGroupAvatarView.setVisibility(View.VISIBLE);
//                            nineGridImageView.setVisibility(View.GONE);
//                            LXGlideImageLoader.getInstance().showGroupAvatar(AddGroupUserInfoActivity.this, ivGroupAvatarView, group.getAvatar());
//
//                        }
//                        //获取群的成员信息，存入数据库，在完成的回调中显示群成员
//                        try {
//                            GetHttpUtil.getGroupUsers(AddGroupUserInfoActivity.this, groupId, new GetHttpUtil.ReqCallBack<List<User>>() {
//                                @Override
//                                public void onReqSuccess(List<User> users) {
//                                    onGetGroupUserSuccess(users, groupId);
//                                }
//
//                                @Override
//                                public void onReqFailed(String errorMsg) {
//
//                                }
//                            });
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }, false);
//
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
        try {
            //先获取group的基本信息，存入数据库后，进行显示
            showLoading(R.string.common_text_please_wait);
            GetHttpUtil.getGroupByKeyOrId(AddGroupUserInfoActivity.this, groupKey,
                    new JFCommonRequestManager.ReqCallBack<Group>() {

                        @Override
                        public void onReqSuccess(Group group1) {
                            group = group1;
                            groupId = group.getGroupId();
                            setAddButtonText();
                            setTopView(group, tv_groupname, tvGroupIdView, tv_titleView, tv_qunjieshao);
                            if (group.getAvatar() != null && !"".equals(group.getAvatar()) && group.getAvatar().startsWith("http")) {
                                isHaveAvatar = true;
                                ivGroupAvatarView.setVisibility(View.VISIBLE);
                                nineGridImageView.setVisibility(View.GONE);
                                LXGlideImageLoader.getInstance().showRoundGrouAvatar(AddGroupUserInfoActivity.this,
                                        ivGroupAvatarView, group.getAvatar(),LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_12);

                            }
                            //获取群的成员信息，存入数据库，在完成的回调中显示群成员
                            try {
                                GetHttpUtil.getGroupUsers(AddGroupUserInfoActivity.this, groupId,
                                        new GetHttpUtil.ReqCallBack<List<User>>() {
                                            @Override
                                            public void onReqSuccess(List<User> users) {
                                                dismissLoading();
                                                onGetGroupUserSuccess(users, groupId);
                                                //initData();
                                            }

                                            @Override
                                            public void onReqFailed(String errorMsg) {
                                                dismissLoading();
                                            }
                                        });
                            } catch (Exception e) {
                                e.printStackTrace();
                                dismissLoading();
                            }
                        }

                        @Override
                        public void onReqFailed(String errorMsg) {
                            dismissLoading();
                            showNoGroupDialog();
                        }


                    }, false);

        } catch (JSONException e) {
            e.printStackTrace();
            dismissLoading();
        }

//        } else {//如果数据库中存在群数据，则直接显示数据库中的
//            setTopView(group, tv_groupname, tvGroupIdView, tv_titleView, tv_qunjieshao);
//            setUpUsers();
//        }
//        if ((group.getAvatar() != null && group.getAvatar().startsWith("http"))) {
//            ivGroupAvatarView.setVisibility(View.VISIBLE);
//            nineGridImageView.setVisibility(View.GONE);
//            LXGlideImageLoader.getInstance().showGroupAvatar(AddGroupUserInfoActivity.this, ivGroupAvatarView, group.getAvatar());
//        }
    }

    private void showNoGroupDialog() {
        if (!this.isDestroyed()) {
            new AlertDialog.Builder(this).setTitle(R.string.common_text_hint)
                    .setMessage(R.string.wechatview_add_group_error1)
                    .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    }).show();
        }
    }

    private void initView() {
        addGroupBtn = (Button) findViewById(R.id.btn_exit_grp);
        addGroupBtn.setOnClickListener(this);
        tv_groupname = (TextView) findViewById(R.id.tv_groupname);
        tv_m_total = (TextView) findViewById(R.id.tv_m_total);
        userGridview = (ExpandGridView) findViewById(R.id.gridview_groupuser);
        tv_titleView = (TextView) findViewById(R.id.tv_title);

        //这部分是仿qq群聊新增的
        ivGroupAvatarView = (ImageView) findViewById(R.id.iv_group_avatar_normal);
        nineGridImageView = (NineGridImageView) findViewById(R.id.iv_group_avatar);
        tvGroupIdView = (TextView) findViewById(R.id.tv_groupid);
        userCountView = (TextView) findViewById(R.id.tv_usercount);
        ll_groupUserLayout = (LinearLayout) findViewById(R.id.ll_groupUserlayout);
        ll_groupUserLayout.setOnClickListener(this);
        tv_qunjieshao = (TextView) findViewById(R.id.tv_qunjieshao);
    }

    /**
     * 设置群成员数，群成员的GridView
     * 显示群头像
     */
    private void setUpUsers() {
//        String avatar = ChatGroupSettingActivity.getAvatar(group);
//        imageLoader.displayImage(avatar, ivGroupAvatarView, options);
        List<User> users = group.getUsers();
        ChatGroupSettingActivity.setGroupUsers(users, AddGroupUserInfoActivity.this, tv_m_total, userCountView, userGridview, 0, groupId);
        showGroupAvatar(users);
    }

    /**
     * 用9宫IV生成群头像
     *
     * @param users
     */
    private void showGroupAvatar(final List<User> users) {
        List<String> urlList = new ArrayList<>();
        for (int i = 0; i < users.size(); i++) {
            String avatarUrl = users.get(i).getAvatar();
            urlList.add(avatarUrl);
        }

        final NineGridImageViewAdapter<Object> mAdapter = new NineGridImageViewAdapter<Object>() {
            @Override
            protected synchronized void onDisplayImage(final Context context, ImageView imageView, Object s) {
                if (s == null || "".equals(s)) {
                    s = +R.drawable.default_useravatar;
                }
                try {
                    LXGlideImageLoader.getInstance().displayImage(AddGroupUserInfoActivity.this,
                            imageView, s, R.drawable.default_user_avatar, R.drawable.default_user_avatar);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected ImageView generateImageView(Context context) {
                return super.generateImageView(context);
            }
        };
        nineGridImageView.setAdapter(mAdapter);
        nineGridImageView.setImagesData(urlList);

    }

    @Override
    public void onBackPressed() {
        if (isTaskRoot()) {
            try {
                String className = getResources().getString(R.string.from_group_backto_first);
                Class clazz = Class.forName(className);
                Intent myIntent = new Intent(this, clazz);
                startActivity(myIntent);
                finish();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_exit_grp) {
            if (added) {//如果已经加过群，点击Button跳入聊天界面
                Intent intent = new Intent();
                intent.putExtra("id", groupId);
                intent.putExtra("chattype", StructFactory.TO_USER_TYPE_GROUP);
                ChatActivitySkipUtil.startChatActivity(AddGroupUserInfoActivity.this, intent);

                AddGroupUserInfoActivity.this.finish();
            } else {//没有加过，则进行加群操作
                //需要申请加群才跳转界面
                if (group.getGroupType() == 0) {
                    AddUserOrGroupVerifyActivity.start(AddGroupUserInfoActivity.this, groupId, StructFactory.TO_USER_TYPE_GROUP);
                    return;
                }

                String message = getResources().getString(R.string.im_apply_add_group_text);
                if (group.getGroupType() == 1) {
                    message = getResources().getString(R.string.im_add_group_text);
                }
                final boolean freeAdd = group.getGroupType() == 1;
                new AlertDialog.Builder(AddGroupUserInfoActivity.this).setTitle(R.string.common_text_hint).setMessage(message)
                        .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                try {
                                    GetHttpUtil.applyToGroup(AppContext.getInstance(), groupId, "", new GetHttpUtil.ApplyToGroupCallBack() {
                                        @Override
                                        public void applyToGroupResult(boolean isSuccess) {
                                            if (!isSuccess) {
                                                if (freeAdd) {
                                                    ToastUtil.showToast(AppContext.getInstance(), R.string.im_add_group_fail);
                                                    return;
                                                }
                                                ToastUtil.showToast(AppContext.getInstance(), R.string.im_appy_add_group_fail);
                                                return;
                                            } else {
                                                if (freeAdd) {
                                                    added = true;
                                                    addGroupBtn.setText(R.string.chat_enter_chat);
                                                    ToastUtil.showToast(AppContext.getInstance(), R.string.im_add_group_success);
                                                    sendMessage(group.getGroupId());
                                                    return;
                                                }
                                                ToastUtil.showToast(AppContext.getInstance(), R.string.im_appy_add_group_success);
                                            }
                                        }
                                    });
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                        }).setNegativeButton(R.string.common_text_cancel, null).show();
            }
        } else if (v.getId() == R.id.ll_groupUserlayout) {//跳入群成员列表界面
            Intent intent = new Intent(AddGroupUserInfoActivity.this, ChatGroupUserActivity.class);
            intent.putExtra("id", groupId);
            intent.putExtra("queryFrom", 0);
            startActivity(intent);
        }
    }

    //像群里发送入群通知
    private void sendMessage(int groupId) {
        //发送群通知
        String content = GroupOperationHelper.getFreeToGroupMesage();
        IMStruct002 struct002 = null;
        struct002 = StructFactory.getInstance().
                createCommonNotificationImstruct002(ChatTipsMessageItem.TYPE_NOTIFY, content, null,
                        StructFactory.TO_USER_TYPE_GROUP);
        struct002.setToUserId(groupId);
        struct002.setFromUserId(Integer.parseInt(EnvironmentVariable
                .getProperty(Constants.CHAT_USER_ID)));
        JFMessageManager.getInstance().sendMessage(struct002);
    }


    public void onGetGroupUserSuccess(List<User> groupUsers, int groupId) {
        group = WeChatDBManager.getInstance().getGroupWithUsersInGroups(groupId);
        ChatGroupSettingActivity.setGroupUsers(groupUsers, AddGroupUserInfoActivity.this, tv_m_total, userCountView, userGridview, 0, groupId);
        if (isHaveAvatar) {
            return;
        }
        showGroupAvatar(groupUsers);
    }

}
