package com.efounder.chat.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

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.chat.model.ApplyGroupNotice;
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.RoundImageView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.http.EFHttpRequest;
import com.efounder.http.EFHttpRequest.HttpRequestListener;
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.efounder.utils.ResStringUtil;

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

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;



/**
 * 新的朋友 群通知拒绝同意界面
 *
 * @author YQS 2018/08/02
 */
public class AddRequestActivity extends BaseActivity implements OnClickListener {
    public static final int REQUEST_CODE = 110;

    private ImageView ivBack;
    private ImageView ivClose;
    private TextView tvTitle;
    private RelativeLayout rlTop;
    private RoundImageView ivAvatar;
    private TextView tvFriendName;
    private ImageView ivArrow;
    private TextView tvLeaveMessage;
    private LinearLayout llDoubleLayout;
    private Button butCancel;
    private Button butAgree;
    private TextView tvFriendId;


    private User user;
    private TextView tvBottom;
    private ApplyGroupNotice groupNotice;


    public static void start(Context context, User user, int position) {
        Intent starter = new Intent(context, AddRequestActivity.class);
        starter.putExtra("user", user);
        starter.putExtra("position", position);
        ((Activity) context).startActivityForResult(starter, REQUEST_CODE);
    }

    public static void start(Context context, ApplyGroupNotice groupNotice, int position) {
        Intent starter = new Intent(context, AddRequestActivity.class);
        starter.putExtra("groupNotice", groupNotice);
        starter.putExtra("position", position);
        ((Activity) context).startActivityForResult(starter, REQUEST_CODE);
    }

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.wechatview_activity_add_request);
        initView();
        initData();
    }

    private void initView() {

        ivBack = (ImageView) findViewById(R.id.iv_back);
        ivClose = (ImageView) findViewById(R.id.iv_close);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        rlTop = (RelativeLayout) findViewById(R.id.rl_top);
        ivAvatar = (RoundImageView) findViewById(R.id.iv_avatar);
        tvFriendName = (TextView) findViewById(R.id.tv_friend_name);
        ivArrow = (ImageView) findViewById(R.id.iv_arrow);
        tvLeaveMessage = (TextView) findViewById(R.id.tv_leave_message);
        llDoubleLayout = (LinearLayout) findViewById(R.id.ll_double_layout);
        butCancel = (Button) findViewById(R.id.but_cancel);
        butAgree = (Button) findViewById(R.id.but_agree);
        tvBottom = (TextView) findViewById(R.id.tv_bottom);
        tvFriendId = (TextView) findViewById(R.id.tv_friend_id);
        rlTop.setOnClickListener(this);
        butAgree.setOnClickListener(this);
        butCancel.setOnClickListener(this);

    }

    private void initData() {
        if (getIntent().hasExtra("user")) {
            initAddUserData();
        } else {
            initAddGroupData();
        }


    }

    private void initAddGroupData() {
        groupNotice = (ApplyGroupNotice) getIntent().getSerializableExtra("groupNotice");
        tvTitle.setText(R.string.im_add_group_request);
        user = groupNotice.getUser();
        tvFriendName.setText(user.getNickName());
        tvFriendId.setText(user.getId() + "");
        tvLeaveMessage.setText(groupNotice.getLeaveMessage().equals("") ? ResStringUtil.getString(R.string.chat_no_validation_info) : groupNotice.getLeaveMessage());
        if (user.getAvatar() != null && user.getAvatar().contains("http")) {
            LXGlideImageLoader.getInstance().showUserAvatar(AddRequestActivity.this, ivAvatar, user.getAvatar());
        } else {
            LXGlideImageLoader.getInstance().showUserAvatar(AddRequestActivity.this, ivAvatar, "");
        }
        int state = groupNotice.getState();
        if (state == ApplyGroupNotice.UNACCEPT) {
            llDoubleLayout.setVisibility(View.VISIBLE);
        } else {
            tvBottom.setVisibility(View.VISIBLE);
            if (state == ApplyGroupNotice.ACCEPTED) {
                tvBottom.setText(R.string.chat_agree_this_request);
            } else if (state == ApplyGroupNotice.REFUSE) {
                tvBottom.setText(R.string.chat_refuse_this_request);
            } else if (state == ApplyGroupNotice.SENT) {
                tvBottom.setText(R.string.chat_send_this_request);
            } else if (state == ApplyGroupNotice.REJECTED) {
                tvBottom.setText(R.string.chat_this_request_be_refused);
            }

        }
    }

    private void initAddUserData() {
        tvTitle.setText(R.string.chat_friend_request);
        user = (User) getIntent().getSerializableExtra("user");
        tvFriendName.setText(user.getNickName());
        tvFriendId.setText(user.getId() + "");
        tvLeaveMessage.setText(user.getLeaveMessage());
        tvLeaveMessage.setText(user.getLeaveMessage().equals("") ? ResStringUtil.getString(R.string.chat_no_validation_info) : user.getLeaveMessage());

        if (user.getAvatar() != null && user.getAvatar().contains("http")) {
            LXGlideImageLoader.getInstance().showUserAvatar(AddRequestActivity.this, ivAvatar, user.getAvatar());
        } else {
            LXGlideImageLoader.getInstance().showUserAvatar(AddRequestActivity.this, ivAvatar, "");
        }
        int state = user.getState();
        if (state == User.UNACCEPT) {
            llDoubleLayout.setVisibility(View.VISIBLE);
        } else {
            tvBottom.setVisibility(View.VISIBLE);
            if (state == User.ACCEPTED) {
                tvBottom.setText(R.string.chat_agree_this_request);
            } else if (state == User.REFUSE) {
                tvBottom.setText(R.string.chat_refuse_this_request);
            } else if (state == User.SENT) {
                tvBottom.setText(R.string.chat_send_this_request);
            } else if (state == User.REJECTED) {
                tvBottom.setText(R.string.chat_this_request_be_refused);
            }
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
    }

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


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rl_top) {
            Intent intent = new Intent();
            intent.putExtra("id", user.getId());
            intent.putExtra("chattype", StructFactory.TO_USER_TYPE_PERSONAL);
            ChatActivitySkipUtil.startUserInfoActivity(AddRequestActivity.this, intent);

        } else if (id == R.id.but_agree) {
            if (getIntent().hasExtra("user")) {
                aggreeFriend(user, butAgree);
            } else {
                aggreeGroupApply(groupNotice, butAgree);
            }

        } else if (id == R.id.but_cancel) {
            if (getIntent().hasExtra("user")) {
                refuseFriend();
            } else {
                refuseAddGroup();
            }

        }
    }


    private void refuseFriend() {
        showLoading(R.string.common_text_please_wait);
        String userid = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String password = EnvironmentVariable.getProperty(CHAT_PASSWORD);
        String id = user.getId() + "";
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("userId", userid);
        hashMap.put("passWord", password);
        hashMap.put("friendUserId", id);
        hashMap.put("leaveMessage", "");
        JFCommonRequestManager.getInstance(this).requestGetByAsyn(TAG, GetHttpUtil.ROOTURL
                + "/IMServer/user/rejectAddFriend", hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String info = jsonObject.getString("result");
                    if ("success".equals(info)) {
                        user.setState(User.REFUSE);//好友申请已拒绝
                        user.setTime(System.currentTimeMillis());
                        user.setIsRead(true);
                        user.setLoginUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
                        WeChatDBManager.getInstance().insertSendNewFriendApply(user);
                        ToastUtil.showToast(AddRequestActivity.this,
                                R.string.chat_operation_success);
                        Intent intent = new Intent();
                        intent.putExtra("user", user);
                        intent.putExtra("position", getIntent().getIntExtra("position", 0));
                        setResult(RESULT_OK, intent);
                        finish();
                    } else {
                        ToastUtil.showToast(AddRequestActivity.this,
                                R.string.chat_operation_fail);
                    }
                } catch (JSONException e) {
                    dismissLoading();
                    e.printStackTrace();
                    ToastUtil.showToast(AddRequestActivity.this,
                            R.string.chat_operation_fail);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                dismissLoading();
                ToastUtil.showToast(AddRequestActivity.this,
                        R.string.chat_operation_fail);

            }
        });
    }


    //同意好友请求
    private void aggreeFriend(final User user, final Button btn_accept) {
        showLoading(R.string.common_text_please_wait);
        String userid = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String password = EnvironmentVariable.getProperty(CHAT_PASSWORD);
        EFHttpRequest httpRequest = new EFHttpRequest(TAG);
        try {
            password = URLEncoder.encode(password, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = GetHttpUtil.ROOTURL + "/IMServer/user/addFriend?userId="
                + userid + "&passWord=" + password + "&friendUserId="
                + user.getId();

        httpRequest.httpGet(url);
        httpRequest.setHttpRequestListener(new HttpRequestListener() {

            @Override
            public void onRequestSuccess(int requestCode, String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String info = jsonObject.getString("result");
                    if ("success".equals(info)) {
                        dismissLoading();
                        Toast.makeText(AddRequestActivity.this, R.string.chat_agree_request_friend,
                                Toast.LENGTH_SHORT).show();
                        // 接受成为好友 存入数据库
                        user.setState(User.ACCEPTED);
                        user.setIsRead(true);
                        user.setTime(System.currentTimeMillis());
                        WeChatDBManager.getInstance().agreeNewFriendApply(user);
                        btn_accept.setText(R.string.chat_added);
                        btn_accept.setEnabled(false);
                        btn_accept.setTextColor(getResources().getColor(R.color.light_text_color));
                        btn_accept.setBackgroundColor(getResources().getColor(R.color.transparent));


                        IMStruct002 struct002 = null;
                        struct002 = StructFactory.getInstance().
                                createTextStruct(ResStringUtil.getString(R.string.chat_become_friend_chat),
                                        StructFactory.TO_USER_TYPE_PERSONAL);
                        struct002.setToUserId(user.getId());
                        struct002.setFromUserId(Integer.parseInt(EnvironmentVariable
                                .getProperty(Constants.CHAT_USER_ID)));

                        JFMessageManager.getInstance().sendMessage(struct002);
                        Intent intent = new Intent();
                        intent.putExtra("user", user);
                        intent.putExtra("position", getIntent().getIntExtra("position", 0));
                        setResult(RESULT_OK, intent);
                        finish();
                    } else {
                        dismissLoading();
                        Toast.makeText(AddRequestActivity.this, R.string.chat_operation_fail,
                                Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }


            @Override
            public void onRequestFail(int requestCode, String message) {
                dismissLoading();
                Toast.makeText(AddRequestActivity.this, R.string.chat_operation_fail,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    //同意加群请求
    private void aggreeGroupApply(final ApplyGroupNotice notice, final Button btn_accept) {
        showLoading(R.string.common_text_please_wait);
        try {
            GetHttpUtil.addUserToGroup(AddRequestActivity.this, notice.getGroupId(),
                    String.valueOf(notice.getUserId()), new GetHttpUtil.ReqCallBack<Boolean>() {
                        @Override
                        public void onReqSuccess(Boolean result) {
                            dismissLoading();
                            Toast.makeText(AppContext.getInstance(), R.string.chat_agree_this_user_request,
                                    Toast.LENGTH_SHORT).show();

                            notice.setState(ApplyGroupNotice.ACCEPTED);
                            notice.setRead(true);
                            notice.setTime(System.currentTimeMillis());
                            WeChatDBManager.getInstance().agreeApplyGroup(notice);

                            Intent intent = new Intent();
                            intent.putExtra("groupNotice", notice);
                            intent.putExtra("position", getIntent().getIntExtra("position", 0));
                            setResult(RESULT_OK, intent);

                            //发送群通知
                            String content = GroupOperationHelper.getAgreeToGroupMesage(notice.getGroupId(), notice.getUser());
                            IMStruct002 struct002 = null;
                            struct002 = StructFactory.getInstance().
                                    createCommonNotificationImstruct002(ChatTipsMessageItem.TYPE_NOTIFY, content, null,
                                            StructFactory.TO_USER_TYPE_GROUP);
                            struct002.setToUserId(notice.getGroupId());
                            struct002.setFromUserId(Integer.parseInt(EnvironmentVariable
                                    .getProperty(Constants.CHAT_USER_ID)));
                            JFMessageManager.getInstance().sendMessage(struct002);
                            finish();

                        }

                        @Override
                        public void onReqFailed(String errorMsg) {
                            Toast.makeText(AppContext.getInstance(), R.string.chat_operation_fail,
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //拒绝加群请求
    private void refuseAddGroup() {
//        /IMServer/user/rejectAddUserToGroup
//        参数:
//        userId 管理员联信ID
//        passWord 密码
//        groupId 群组id
//        applyUserId 申请人id
//        leaveMessage 留言

        showLoading(R.string.common_text_please_wait);
        String userid = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String password = EnvironmentVariable.getProperty(CHAT_PASSWORD);
        String id = user.getId() + "";
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("userId", userid);
        hashMap.put("passWord", password);
        hashMap.put("applyUserId", id);
        hashMap.put("groupId", groupNotice.getGroupId() + "");
        hashMap.put("leaveMessage", "");
        JFCommonRequestManager.getInstance(this).requestGetByAsyn(TAG, GetHttpUtil.ROOTURL
                + "/IMServer/group/rejectAddUserToGroup", hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String info = jsonObject.getString("result");
                    if ("success".equals(info)) {
                        groupNotice.setState(ApplyGroupNotice.REFUSE);
                        groupNotice.setRead(true);
                        groupNotice.setTime(System.currentTimeMillis());
                        WeChatDBManager.getInstance().agreeApplyGroup(groupNotice);
                        Intent intent = new Intent();
                        intent.putExtra("groupNotice", groupNotice);
                        intent.putExtra("position", getIntent().getIntExtra("position", 0));
                        setResult(RESULT_OK, intent);
                        finish();
                    } else {
                        ToastUtil.showToast(AddRequestActivity.this,
                                R.string.chat_operation_fail);
                    }
                } catch (JSONException e) {
                    dismissLoading();
                    e.printStackTrace();
                    ToastUtil.showToast(AddRequestActivity.this,
                            R.string.chat_operation_fail);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                dismissLoading();
                ToastUtil.showToast(AddRequestActivity.this,
                        R.string.chat_operation_fail);
            }
        });
    }
}
