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.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

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.model.Group;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.widget.RoundImageView;
import com.efounder.constant.EnvironmentVariable;
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.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 AddUserOrGroupVerifyActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "AddUserOrGroupVerifyAct";

    private ImageView ivBack;
    private TextView tvTitle;
    private TextView tvSave;
    private RelativeLayout rlAddUserLayout;
    private RoundImageView ivAvatar;
    private TextView tvFriendName;
    private TextView tvFriendId;
    private TextView tvFriendLeaveMessage;
    private EditText etAddfriend;
    private RelativeLayout rlGroupLayout;
    private EditText etAddgroup;
    private TextView leftCloseView;
    private int id;
    private byte chatType;
    //是否是添加群组
    private boolean isAddGroup = false;
    private User friendUser, selfUser;
    private Group group;

    public static void start(Context context, int id, byte chatType) {
        Intent starter = new Intent(context, AddUserOrGroupVerifyActivity.class);
        starter.putExtra("id", id);
        starter.putExtra("chatType", chatType);
        int inTransition = R.anim.push_bottom_in;
        int outTransition = R.anim.push_top_out;
        ((Activity) context).startActivity(starter);
        ((Activity) context).overridePendingTransition(inTransition, outTransition);

    }

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

    }

    private void initView() {
        ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setVisibility(View.GONE);
        leftCloseView = (TextView) findViewById(R.id.tv_left_close);
        leftCloseView.setVisibility(View.VISIBLE);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvSave = (TextView) findViewById(R.id.tv_save);
        tvSave.setVisibility(View.VISIBLE);
        rlAddUserLayout = (RelativeLayout) findViewById(R.id.rl_add_user_layout);
        ivAvatar = (RoundImageView) findViewById(R.id.iv_avatar);
        tvFriendName = (TextView) findViewById(R.id.tv_friend_name);
        tvFriendId = (TextView) findViewById(R.id.tv_friend_id);
        tvFriendLeaveMessage = (TextView) findViewById(R.id.tv_friend_leave_message);
        etAddfriend = (EditText) findViewById(R.id.et_addfriend);
        rlGroupLayout = (RelativeLayout) findViewById(R.id.rl_group_layout);
        etAddgroup = (EditText) findViewById(R.id.et_addgroup);
        tvSave.setOnClickListener(this);
        leftCloseView.setOnClickListener(this);

    }

    private void initData() {
        id = getIntent().getIntExtra("id", 0);
        chatType = getIntent().getByteExtra("chatType", (byte) 0);
        selfUser = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        if (chatType != 0) {
            isAddGroup = true;
            tvTitle.setText(R.string.chat_verification_info);
            rlAddUserLayout.setVisibility(View.GONE);
            rlGroupLayout.setVisibility(View.VISIBLE);
            Group group = WeChatDBManager.getInstance().getGroup(id, false);
            if (!group.isExist()) {

            }

        } else {
            tvTitle.setText(R.string.chat_add_friend);
            rlAddUserLayout.setVisibility(View.VISIBLE);
            rlGroupLayout.setVisibility(View.GONE);
            friendUser = WeChatDBManager.getInstance().getOneUserById(id);
            LXGlideImageLoader.getInstance().displayImage(this, ivAvatar, friendUser.getAvatar(),
                    R.drawable.default_user_avatar, R.drawable.default_user_avatar);
            tvFriendName.setText(friendUser.getNickName());
            tvFriendId.setText(friendUser.getId() + "");

        }
        etAddfriend.setText(ResStringUtil.getString(R.string.chat_i_am) + selfUser.getNickName());
        etAddgroup.setText(ResStringUtil.getString(R.string.chat_i_am) + selfUser.getNickName());
        etAddfriend.setSelection(etAddfriend.getText().length());
        etAddgroup.setSelection(etAddgroup.getText().length());
        leftCloseView.setOnClickListener(this);
        tvSave.setText(R.string.common_text_send);


    }


    @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.tv_save) {
            if (isAddGroup) {
                sendAddGroup();
            } else {
                sendAddUser();
            }
        } else if (id == R.id.tv_left_close) {
            finish();
        }
    }

    private void sendAddUser() {
        showLoading(ResStringUtil.getString(R.string.chat_adding));
        String userid = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String password = EnvironmentVariable.getProperty(CHAT_PASSWORD);
        String id = friendUser.getId() + "";
        String leaveMessage = etAddfriend.getText().toString().equals("") ? "" : etAddfriend.getText().toString();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("userId", userid);
        hashMap.put("passWord", password);
        hashMap.put("friendUserId", id);
        hashMap.put("leaveMessage", leaveMessage);
        JFCommonRequestManager.getInstance(this).requestGetByAsyn(TAG, GetHttpUtil.ROOTURL
                + "/IMServer/user/applyAddFriend", hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String info = jsonObject.getString("result");
                    System.out.printf(info);
                    if ("success".equals(info)) {
                        friendUser.setState(User.SENT);//好友申请已发送
                        friendUser.setTime(System.currentTimeMillis());
                        friendUser.setIsRead(true);
                        friendUser.setLeaveMessage(ResStringUtil.getString(R.string.chat_send_verification_info));
                        friendUser.setLoginUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
                        WeChatDBManager.getInstance().insertSendNewFriendApply(friendUser);
                        ToastUtil.showToast(AppContext.getInstance(),
                                R.string.chat_send_friend_request_success);
                        finish();
                    } else {
                        ToastUtil.showToast(AppContext.getInstance(),
                                R.string.chat_send_friend_request_fail);
                    }
                } catch (JSONException e) {
                    dismissLoading();
                    e.printStackTrace();
                    ToastUtil.showToast(AppContext.getInstance(),
                            R.string.chat_send_friend_request_fail);
                }
            }

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

            }
        });
    }

    private void sendAddGroup() {
        showLoading(ResStringUtil.getString(R.string.chat_adding));
        try {
            GetHttpUtil.applyToGroup(this, id, etAddgroup.getText().toString(), new GetHttpUtil.ApplyToGroupCallBack() {
                @Override
                public void applyToGroupResult(boolean isSuccess) {
                    dismissLoading();
                    if (isSuccess) {
                        ToastUtil.showToast(AppContext.getInstance(), R.string.im_appy_add_group_success);
                        finish();
                    } else {
                        ToastUtil.showToast(AppContext.getInstance(), R.string.im_appy_add_group_fail);
                    }
                }
            });
        } catch (Exception e) {
            dismissLoading();
            e.printStackTrace();
        }

    }
}
