package com.efounder.chat.activity;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
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.model.ChatListItem;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.notify.MessageNotificationHelper;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
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.recycleviewhelper.CommonAdapter;
import com.efounder.utils.JfResourceUtil;
import com.efounder.utils.ResStringUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

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

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

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 NewFriendsActivity extends BaseActivity {
    private NewFriendsAdapter adapter;
    private List<User> listUser;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recycleview;
    private AsyncTask<Void, Void, List<User>> asyncTask;


    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.wechatview_activity_new_friend);
        initView();
        initData();
        markData();
        loadDataByAsync(0);
    }

    private void initView() {
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.chat_new_friends);
        ImageView iv_backImage = (ImageView) findViewById(R.id.iv_back);
        iv_backImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                NewFriendsActivity.this.finish();
            }
        });

        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        recycleview = (RecyclerView) findViewById(R.id.recycleview);
        recycleview.setLayoutManager(new LinearLayoutManager(this));
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                // 上拉加载更多
                loadDataByAsync(listUser.size());
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                // 下拉刷新
                listUser.clear();
                markData();
                loadDataByAsync(0);
            }
        });
    }

    private void initData() {
        listUser = new ArrayList<>();
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        recycleview = (RecyclerView) findViewById(R.id.recycleview);
        adapter = new NewFriendsAdapter(this, R.layout.wechatview_item_new_friends_item, listUser);
        recycleview.setAdapter(adapter);
    }

    private void markData() {
        // 清除通知栏消息
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancel(0);
        MessageNotificationHelper.cancel(getApplicationContext());
        WeChatDBManager.getInstance().updateAllNewFriendsSetIsRead();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        listUser.clear();
        markData();
        loadDataByAsync(0);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().post(new UpdateBadgeViewEvent("-2", (byte) 0));
    }

    @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
    protected void onDestroy() {
        super.onDestroy();
        if (asyncTask != null && !asyncTask.isCancelled()) {
            asyncTask.cancel(true);
            refreshLayout.finishLoadMore();
            refreshLayout.finishRefresh();
        }
    }

    public class NewFriendsAdapter extends CommonAdapter<User> {

        public NewFriendsAdapter(Context context, int layoutId, List<User> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(final com.efounder.recycleviewhelper.base.ViewHolder viewHolder, final User user, final int position) {

            ImageView iv_icon;
            TextView tv_name;
            final Button btn_accept;
            TextView info;
            LinearLayout containerLayout;
            Button deleteButton;
            final int state = user.getState();

            iv_icon = viewHolder.getView(R.id.iv_icon);
            tv_name = viewHolder.getView(R.id.tv_name);
            btn_accept = viewHolder.getView(R.id.bt_accept);
            info = viewHolder.getView(R.id.info);
            containerLayout = viewHolder.getView(R.id.ll_container);
            deleteButton = viewHolder.getView(R.id.bt_delete);

            if (user != null) {
                LXGlideImageLoader.getInstance().showRoundUserAvatar(NewFriendsActivity.this, iv_icon, user.getAvatar(), LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
            }

            tv_name.setText(user.getNickName());
            if (state == User.UNACCEPT) {
                btn_accept.setText(R.string.chat_agree);
                btn_accept.setEnabled(true);
                info.setText(user.getLeaveMessage().equals("") ? ResStringUtil.getString(R.string.chat_request_your_friend) : user.getLeaveMessage());
                btn_accept.setTextColor(JfResourceUtil.getSkinColor(R.color.white_text_color));
                btn_accept.setBackground(JfResourceUtil.getSkinDrawable(R.drawable.btn_style_alert_dialog_special));
            } else if (state == User.ACCEPTED) {
                btn_accept.setText(R.string.chat_added);
                btn_accept.setTextColor(JfResourceUtil.getSkinColor(R.color.light_text_color));
                btn_accept.setBackgroundColor(JfResourceUtil.getSkinColor(R.color
                        .transparent));
                info.setText(user.getLeaveMessage().equals("") ? ResStringUtil.getString(R.string.chat_and_you_friend) : user.getLeaveMessage());
            } else if (state == User.SENT) {
                btn_accept.setText(R.string.chat_sent);
                btn_accept.setTextColor(JfResourceUtil.getSkinColor(R.color.light_text_color));
                btn_accept.setBackgroundColor(JfResourceUtil.getSkinColor(R.color
                        .transparent));
                info.setText(R.string.chat_request_friend_sent);
            } else if (state == User.REFUSE) {
                btn_accept.setText(R.string.chat_refused);
                btn_accept.setTextColor(JfResourceUtil.getSkinColor(R.color.light_text_color));
                btn_accept.setBackgroundColor(JfResourceUtil.getSkinColor(R.color
                        .transparent));
                info.setText(user.getLeaveMessage().equals("") ? ResStringUtil.getString(R.string.chat_request_friend_refused) : user.getLeaveMessage());
            } else if (state == User.REJECTED) {
                btn_accept.setText(R.string.chat_be_refused);
                btn_accept.setTextColor(JfResourceUtil.getSkinColor(R.color.light_text_color));
                btn_accept.setBackgroundColor(JfResourceUtil.getSkinColor(R.color
                        .transparent));
                info.setText(user.getLeaveMessage().equals("") ? ResStringUtil.getString(R.string.chat_request_friend_refused) : user.getLeaveMessage());
            }

            btn_accept.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (state == User.UNACCEPT) {
                        // TODO 将结果发送到服务器
                        showLoading(ResStringUtil.getString(R.string.common_text_please_wait));
                        aggreeFriend(user, btn_accept);
                    }
                }
            });

            containerLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (user.getState() == User.SENT) {
                        //自己发送的好友请求跳转详情界面
                        Intent intent = new Intent();
                        intent.putExtra("id", user.getId());
                        intent.putExtra("chattype", StructFactory.TO_USER_TYPE_PERSONAL);
                        ChatActivitySkipUtil.startUserInfoActivity(NewFriendsActivity.this, intent);
                        return;
                    }
                    AddRequestActivity.start(NewFriendsActivity.this, user, position);
                }
            });
            deleteButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    listUser.remove(position);
                    WeChatDBManager.getInstance().deleteApplyFriend(user.getId());
                    notifyDataSetChanged();
                }
            });
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AddRequestActivity.REQUEST_CODE && resultCode == RESULT_OK) {
            if (data.getSerializableExtra("user") != null) {
                int position = data.getIntExtra("position", 0);
                if (listUser != null && listUser.size() > position) {
                    User user = (User) data.getSerializableExtra("user");
                    listUser.get(position).setState(user.getState());
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    private void aggreeFriend(final User user, final Button btn_accept) {
        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(NewFriendsActivity.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));


//						//接受成为好友，给对方发一条消息
                        //清除聊天角标
                        clearBadgem(user.getId(), StructFactory.TO_USER_TYPE_PERSONAL, user);

                        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)));
                        new AsyncTask<IMStruct002, Integer, String>() {

                            @Override
                            protected String doInBackground(IMStruct002... params) {
                                try {
                                    IMStruct002 struct002 = params[0];
                                    boolean b = JFMessageManager.getInstance().sendMessage(struct002);
                                    Log.i("New_FriendsActivity", ResStringUtil.getString(R.string.chat_send_a_message) + struct002.toString());

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

                                return null;
                            }
                        }.execute(struct002);

                    } else {
                        dismissLoading();
                        Toast.makeText(NewFriendsActivity.this, R.string.chat_operation_fail,
                                Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }


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


            }
        });
    }

    private void clearBadgem(int id, byte chatType, User user) {

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

        //发送广播
//        Intent unReadIntent = new Intent();
//
//        unReadIntent.putExtra("id", id);
//        unReadIntent.putExtra("chatType", chatType);
//        unReadIntent.putExtra("userType", User.PERSONALFRIEND);
//        unReadIntent.putExtra("name", user.getNickName());
//        if (chatListItem != null) {
//            chatListItem.setBadgernum(-1);
//            WeChatDBManager.getInstance().insertOrUpdateChatList(chatListItem);
//            unReadIntent.putExtra("unReadCount", unReadCount);
//            //ChatListItemUtil.updateUnreadCount(unReadCount, 0);
//        }
//        unReadIntent.setAction(ChatListFragment.UPDATEBADGNUM);
//        this.sendBroadcast(unReadIntent);


    }

    //数据库中读取列表数据
    private void loadDataByAsync(final int loadedCount) {
        asyncTask = new AsyncTask<Void, Void, List<User>>() {

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

            @Override
            protected List<User> doInBackground(Void... params) {
                List<User> users = WeChatDBManager.getInstance().getNewFriendsInfo(loadedCount);
                return users;
            }

            @Override
            protected void onPostExecute(List<User> result) {
                super.onPostExecute(result);
                listUser.addAll(result);
                refreshLayout.finishRefresh(100);
                refreshLayout.finishLoadMore(100);
                adapter.notifyDataSetChanged();

            }

            @Override
            protected void onCancelled() {
                super.onCancelled();
            }
        };
        asyncTask.executeOnExecutor(Executors.newCachedThreadPool());

    }
}
