package com.efounder.chat.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.appcompat.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.http.OpenEthRequest;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.MessageEvent;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.GroupNameUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.http.EFHttpRequest.HttpRequestListener;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.router.constant.RouterConstant;
import com.efounder.util.ToastUtil;
import com.efounder.utils.CommonUtils;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

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


/**
 * @author Administrator-lch 用户详情信息
 */
@Route(path = RouterConstant.CHAT_USERINFO_ACTIVITY_OLD)
public class UserInfoActivity extends BaseActivity {
    private static final String TAG = "UserInfoActivity";
    // 发送按钮
    private Button btn_sendmsg;
    // 头像区域
    private ImageView iv_avata;
    //空间图标
    private ImageView iv_wode_kj;
    // 性别
    ImageView iv_sex;
    private ImageView iv_detail;
    // 用户名
    private TextView tv_name;
    private TextView tv_zhanghao;
    private TextView tv_nickname;
    private LinearLayout middleArea;

    private byte chatType;
    private int userId;
    //private String userNick;
    private String avatar;
    private String zhanghao;
    private User user;
    //是否是好友
    private boolean isFriend = true;
    //是否是展示的群组成员
    private boolean isGroupUser = false;
    private int groupId;

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


        initView();
        initData();
        initNetWorkData();

    }


    private void initView() {
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.wrchatview_one_detail);
        btn_sendmsg = (Button) findViewById(R.id.btn_sendmsg);
        iv_avata = (ImageView) findViewById(R.id.iv_avatar);
        iv_sex = (ImageView) findViewById(R.id.iv_sex);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_zhanghao = (TextView) findViewById(R.id.tv_zhanghao);
        tv_nickname = (TextView) findViewById(R.id.tv_nickname);
        middleArea = (LinearLayout) this.findViewById(R.id.middle_remark);
        iv_detail = (ImageView) findViewById(R.id.iv_detail);
        iv_detail.setVisibility(View.VISIBLE);
        iv_wode_kj = (ImageView) findViewById(R.id.iv_wode_kj);
    }

    private void initData() {
        //是否展示进入空间的图标
        if (!"0".equals(EnvironmentVariable.getProperty("isShowMyZone"))) {
            iv_wode_kj.setVisibility(View.VISIBLE);
        } else {
            iv_wode_kj.setVisibility(View.GONE);
        }
        chatType = getIntent().getByteExtra("chattype", StructFactory.TO_USER_TYPE_PERSONAL);
        userId = getIntent().getIntExtra("id", 1);
        groupId = getIntent().getIntExtra("groupId", 1);
        if (groupId != 1) {
            //表示从群聊查看人员信息
            isGroupUser = true;
        }


        final int loginUserId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID));
        user = WeChatDBManager.getInstance().getOneFriendById(userId);
        if (!user.isExist()) {
            isFriend = false;
            user = WeChatDBManager.getInstance().getOneUserById(userId);
        }
        if (isGroupUser) {
            user = GroupNameUtil.getGroupUser(groupId, userId);
            user.setReMark(GroupNameUtil.getGroupUserName(user));
        }
        avatar = user.getAvatar();

        iv_avata.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (user.getAvatar() != null && user.getAvatar().contains("http")) {
                    Intent intent = new Intent(UserInfoActivity.this,
                            ShowBigImageActivity.class);
                    intent.putExtra("path", user.getAvatar());
                    ActivityOptionsCompat options = ActivityOptionsCompat
                            .makeSceneTransitionAnimation(UserInfoActivity.this, iv_avata, "avatar");
                    ActivityCompat.startActivity(UserInfoActivity.this, intent, options.toBundle());
                } else {
                    ToastUtil.showToast(UserInfoActivity.this, R.string.chat_user_not_set_head);
                }
            }
        });


        zhanghao = user.getName();
        if (zhanghao == null || zhanghao.equals("")) {
            tv_zhanghao.setText(R.string.wrchatview_not_set);

        } else {
            tv_zhanghao.setText(zhanghao);
        }
        tv_nickname.setText(user.getNickName());
        if (loginUserId == userId) {
            iv_detail.setVisibility(View.INVISIBLE);
        }
        iv_detail.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isFriend) {
                    showPopWindow(iv_detail);
                }
            }
        });
        if (!isFriend) {
            btn_sendmsg.setText(R.string.wrchatview_add_contact_list);
        }
        btn_sendmsg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (loginUserId == userId) {
                    Toast.makeText(UserInfoActivity.this, R.string.chat_not_add_mine_friend, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (isFriend) {
                    EnvironmentVariable.setProperty("currentChatUserId", String.valueOf(userId));
                    Intent intent = new Intent();
                    intent.putExtra("id", userId);
                    intent.putExtra("chattype", StructFactory.TO_USER_TYPE_PERSONAL);
                    ChatActivitySkipUtil.startChatActivity(UserInfoActivity.this, intent);
                    finish();
                } else {
                    searchUser(userId);
                }


            }

        });
        iv_wode_kj.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFriend || Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)) == userId) {
                    try {
                        EnvironmentVariable.setProperty("currentChatUserId", String.valueOf(userId));
                        Intent intent = new Intent(UserInfoActivity.this, Class.forName("com.efounder.FriendMZoneActivity"));
                        EnvironmentVariable.setProperty("friendStatusNative", "true");
                        startActivity(intent);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(UserInfoActivity.this, R.string.wrchatview_not_you_friend_please);
                }
            }
        });
        Map<String, String> map = new LinkedHashMap<String, String>();

        String key1 = getResources().getString(R.string.showNumberText);
        map.put(key1, String.valueOf(user.getId()));
        if (EnvironmentVariable.getProperty("isShowWalletAddress", "0").equals("1")) {
            map.put("基地ID", user.getWalletAddress());
        }
        //map.put("手机号码", user.getMobilePhone());
        if (user.getSigNature() == null || user.getSigNature().equals("")) {
            map.put("个性签名", ResStringUtil.getString(R.string.chat_unfilled));
        } else {
            map.put("个性签名", user.getSigNature());
        }


        user.setRemarkmap(map);

        this.setcontent(user);

    }

    @Override
    protected void onResume() {
        super.onResume();
        user = WeChatDBManager.getInstance().getOneFriendById(userId);
        if (!user.isExist()) {
            isFriend = false;
            user = WeChatDBManager.getInstance().getOneUserById(userId);
        }
        if (isGroupUser) {
            user = GroupNameUtil.getGroupUser(groupId, userId);
            user.setReMark(GroupNameUtil.getGroupUserName(user));
        }
        // 设置用户名
        tv_name.setText(user.getReMark());
    }

    /**
     * 设置内容
     *
     * @param user
     */
    private void setcontent(User user) {
        middleArea.removeAllViews();
        // 设置性别
        String sex = user.getSex();

        if ("M".equals(sex)) {
            iv_sex.setImageResource(R.drawable.ic_sex_male);
        } else if ("F".equals(sex)) {
            iv_sex.setImageResource(R.drawable.ic_sex_female);
        } else {
            iv_sex.setVisibility(View.GONE);
        }
        // 设置用户名
        tv_name.setText(user.getReMark());
        //设置用户头像
        // LXGlideImageLoader.getInstance().showUserAvatar(this, iv_avata, avatar);
        LXGlideImageLoader.getInstance().showRoundUserAvatar(this, iv_avata, avatar
                , LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
        // 设置描述区域
        final Map<String, String> remarkMap = user.getRemarkmap();

        LayoutInflater inflater = LayoutInflater.from(this);
        for (final String key : remarkMap.keySet()) {
            System.out.println("key= " + key + " and value= "
                    + remarkMap.get(key));
            ViewGroup userinfo_merge = (ViewGroup) inflater.inflate(
                    R.layout.userinfo_merge, null);
            TextView merge_key = (TextView) userinfo_merge
                    .findViewById(R.id.merge_key);
            merge_key.setText(key);

            TextView merge_value = (TextView) userinfo_merge
                    .findViewById(R.id.merge_value);
            merge_value.setText(remarkMap.get(key));
            ImageView ivCopyAddress = (ImageView) userinfo_merge.findViewById(R.id.iv_copy_address);

            if (key.equals("基地ID")) {
                merge_value.setEllipsize(TextUtils.TruncateAt.MIDDLE);
                merge_value.setMaxLines(1);
                ivCopyAddress.setVisibility(View.VISIBLE);
                ivCopyAddress.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
//                    // 将文本内容放到系统剪贴板里。
                        cm.setText(remarkMap.get(key));
                        ToastUtils.showShort(R.string.chat_copy_to_clipboard);
                    }
                });
            }
            LayoutParams lp = new LayoutParams(
                    LayoutParams.MATCH_PARENT, CommonUtils.dip2px(this, 48));
            middleArea.addView(userinfo_merge, lp);
        }

    }

    @Override
    public void back(View view) {
        Intent intent = getIntent().putExtra("remarkName", user.getReMark());
        setResult(1, intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = getIntent().putExtra("remarkName", user.getReMark());
        setResult(1, intent);
        finish();
    }

    private void searchUser(int uid) {
        showLoading(ResStringUtil.getString(R.string.chat_adding));
        String userid = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String password = EnvironmentVariable.getProperty(CHAT_PASSWORD);
        try {
            password = URLEncoder.encode(password, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        EFHttpRequest httpRequest = new EFHttpRequest(TAG);
        String url = GetHttpUtil.ROOTURL
                + "/IMServer/user/applyAddFriend?userId=" + userid
                + "&passWord=" + password + "&friendUserId=" + uid;
        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");
                    System.out.printf(info);
                    if ("success".equals(info)) {
                        dismissLoading();
                        user.setState(User.SENT);//好友申请已发送
                        user.setTime(System.currentTimeMillis());
                        user.setIsRead(true);
                        user.setLoginUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
                        WeChatDBManager.getInstance().insertSendNewFriendApply(user);
                        ToastUtil.showToast(UserInfoActivity.this,
                                R.string.chat_send_friend_request_success);
                    } else {
                        dismissLoading();
                        ToastUtil.showToast(UserInfoActivity.this,
                                R.string.chat_send_friend_request_fail);
                    }
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onRequestFail(int requestCode, String message) {


            }
        });
        // WeChatHttpRequest.

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        return super.onKeyDown(keyCode, event);

    }

    public void showPopWindow(View view) {
        final PopupWindow popupWindow = new PopupWindow(this);
        View conentView;
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        conentView = inflater.inflate(R.layout.popupwindow_beizhu, null);

        RelativeLayout beizhuLayout = (RelativeLayout) conentView.findViewById(R.id.setbeizhi);
        RelativeLayout deleteLayout = (RelativeLayout) conentView.findViewById(R.id.deletefriend);
        if (isGroupUser) {
            TextView textview = conentView.findViewById(R.id.text1);
            textview.setText(R.string.chat_set_group_remark);
        }
        beizhuLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(UserInfoActivity.this, UserRemarkActivity.class);
                intent.putExtra("id", userId);
                if (isGroupUser) {
                    intent.putExtra("groupId", groupId);
                }
                startActivity(intent);
                popupWindow.dismiss();
            }
        });
        deleteLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                new AlertDialog.Builder(UserInfoActivity.this).
                        setMessage(ResStringUtil.getString(R.string.chat_sure_delete_friend)).setTitle(R.string.common_text_hint).setNegativeButton(R.string.common_text_cancel, null)

                        .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                showLoading(ResStringUtil.getString(R.string.chat_deleteing));
                                GetHttpUtil.deleteFriend(UserInfoActivity.this, userId, new
                                        GetHttpUtil.UpdateUserInfoCallBack() {


                                            @Override
                                            public void updateSuccess(boolean isSuccess) {
                                                if (isSuccess) {
                                                    dismissLoading();
                                                    clearBadgem(userId, chatType);

                                                    //跳转到首页
                                                    try {
                                                        ToastUtil.showToast(UserInfoActivity.this,
                                                                R.string.chat_delete_friend_success);
                                                        String className = getResources().getString(R.string.from_group_backto_first);
                                                        Class clazz = Class.forName(className);
                                                        Intent myIntent = new Intent
                                                                (UserInfoActivity.this, clazz);
                                                        startActivity(myIntent);
                                                    } catch (ClassNotFoundException e) {
                                                        e.printStackTrace();
                                                    }


                                                    UserInfoActivity.this.finish();
                                                } else {
                                                    dismissLoading();
                                                    ToastUtil.showToast(UserInfoActivity.this,
                                                            R.string.chat_delete_friend_fail);
                                                }
                                            }
                                        });
                                dialogInterface.dismiss();
                            }
                        }).show();

            }
        });
        // 设置SelectPicPopupWindow的View
        popupWindow.setContentView(conentView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        // 刷新状态
        popupWindow.update();
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0000000000);
        // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
        popupWindow.setBackgroundDrawable(dw);

        // 设置SelectPicPopupWindow弹出窗体动画效果
        popupWindow.setAnimationStyle(R.style.AnimationPreview);
        popupWindow.showAsDropDown(view, 0, 0);
    }

    private void clearBadgem(int id, byte chatType) {

        //清除当前聊天的角标
        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(id, chatType);

        JFMessageManager.getInstance().unreadZero(id, chatType);
        int unReadCount = JFMessageManager.getInstance().
                getUnReadCount(id, chatType);

//        //发送广播
//        Intent unReadIntent = new Intent();
//
//        unReadIntent.putExtra("id", id);
//        unReadIntent.putExtra("chatType", chatType);
//        unReadIntent.putExtra("delete", 1);
//        unReadIntent.putExtra("userType", user.getType());
        if (unReadCount == 0) {
            unReadCount = -1;
        }
        if (chatListItem != null) {
            chatListItem.setBadgernum(unReadCount);
            WeChatDBManager.getInstance().deleteChatListiItem(chatListItem);
            //unReadIntent.putExtra("unReadCount", unReadCount);
            //ChatListItemUtil.updateUnreadCount(unReadCount, 0);
            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.DELETE));

        }
        //  unReadIntent.setAction(ChatListFragment.UPDATEBADGNUM);
        // this.sendBroadcast(unReadIntent);


    }

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

    private void initNetWorkData() {
        // if (!user.isExist()) {
        GetHttpUtil.getUserInfo(userId, UserInfoActivity.this, new GetHttpUtil.GetUserListener() {
            @Override
            public void onGetUserSuccess(User user1) {
                user = WeChatDBManager.getInstance().getOneFriendById(user1.getId());
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    if (UserInfoActivity.this.isDestroyed()) {
                        return;
                    }
                }
                initData();
            }

            @Override
            public void onGetUserFail() {

            }
        });
        // }

        //显示钱包地址
        if (EnvironmentVariable.getProperty("isShowWalletAddress", "0").equals("1") && user.getWalletAddress() == null) {

            OpenEthRequest.getUserEthByImUserId(UserInfoActivity.this, userId, new OpenEthRequest.EthUserRequestListener() {
                @Override
                public void onSuccess(String ethAddress, String publicKey, String RSAPublicKey) {
//                    user.setWalletAddress(ethAddress);
//                    user.setPublicKey(publicKey);
//                    user.setRSAPublicKey(RSAPublicKey);
//                    WeChatDBManager.getInstance().insertUserTable(user);
//                    initData();
                }

                @Override
                public void onSuccess(User user1) {
                    user.setWalletAddress(user1.getWalletAddress());
                    user.setPublicKey(user1.getPublicKey());
                    user.setRSAPublicKey(user1.getRSAPublicKey());
                    user.setWeixinQrUrl(user1.getWeixinQrUrl());
                    user.setZhifubaoQrUrl(user1.getZhifubaoQrUrl());
                    WeChatDBManager.getInstance().insertUserTable(user);
                    initData();


                }

                @Override
                public void onFail(String error) {

                }
            }, true);

        }
    }


}
