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.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.item.ChatTipsMessageItem;
import com.efounder.chat.model.ApplyGroupNotice;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.notify.MessageNotificationHelper;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.GroupOperationHelper;
import com.efounder.chat.utils.LXGlideImageLoader;
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.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 java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

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


public class GroupNotifacationActivity extends BaseActivity {

    private ApplyGroupAdapter adapter;
    private List<ApplyGroupNotice> listGroupNotice;
    private AsyncTask<Void, Void, List<ApplyGroupNotice>> asyncTask;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recycleview;


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

    private void initView() {
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(getString(R.string.group_notification));
        ImageView iv_backImage = (ImageView) findViewById(R.id.iv_back);
        iv_backImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                GroupNotifacationActivity.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(listGroupNotice.size());
            }

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

    }

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

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


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        listGroupNotice.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();
    }

    @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("groupNotice") != null) {
                int position = data.getIntExtra("position", 0);
                if (listGroupNotice != null && listGroupNotice.size() > position) {
                    ApplyGroupNotice groupNotice = (ApplyGroupNotice) data.getSerializableExtra("groupNotice");
                    listGroupNotice.get(position).setState(groupNotice.getState());
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    public class ApplyGroupAdapter extends CommonAdapter<ApplyGroupNotice> {

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

        @Override
        protected void convert(final com.efounder.recycleviewhelper.base.ViewHolder viewHolder, final ApplyGroupNotice groupNotice, final int position) {
            ImageView iv_icon;
            TextView tv_name;
            final Button btn_accept;
            TextView info;
            LinearLayout containerLayout;
            Button deleteButton;
            TextView tvLeaveMessage;


            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);
            tvLeaveMessage = viewHolder.getView(R.id.tv_leave_message);

            final int state = groupNotice.getState();

            if (groupNotice.getUser() != null) {
//                LXGlideImageLoader.getInstance().showUserAvatar(GroupNotifacationActivity.this, iv_icon,
//                        groupNotice.getUser().getAvatar());

                LXGlideImageLoader.getInstance().showRoundUserAvatar(GroupNotifacationActivity.this, iv_icon, groupNotice.getUser().getAvatar(), LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);

            }
            tv_name.setText(groupNotice.getUser().getNickName());
            tvLeaveMessage.setText(groupNotice.getLeaveMessage().equals("") ? ResStringUtil.getString(R.string.chat_no_validation_info) : groupNotice.getLeaveMessage());

            String text = groupNotice.getGroup().getGroupName();
            if (text.length() > 8) {
                text = text.substring(0, 8) + ResStringUtil.getString(R.string.wechatview_group_notification_1);
            } else {
                text = text + ResStringUtil.getString(R.string.wechatview_group_notification_group);

            }
            if (state == ApplyGroupNotice.UNACCEPT) {
                btn_accept.setText(R.string.chat_agree);
                btn_accept.setEnabled(true);
                btn_accept.setTextColor(JfResourceUtil.getSkinColor(R.color.white_text_color));
                btn_accept.setBackground(JfResourceUtil.getSkinDrawable(R.drawable.btn_style_alert_dialog_special));
                info.setText(ResStringUtil.getString(R.string.wechatview_group_notification_apply_to) + text);
            } else if (state == ApplyGroupNotice.ACCEPTED) {
                btn_accept.setText(R.string.wechatview_group_notification_habe_joined);
                btn_accept.setTextColor(JfResourceUtil.getSkinColor(R.color.light_text_color));
                btn_accept.setBackgroundColor(JfResourceUtil.getSkinColor(R.color
                        .transparent));
                info.setText(ResStringUtil.getString(R.string.wechatview_group_notification_habe_joined) + text);
            } else if (state == ApplyGroupNotice.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(getResources().getString(R.string.wechatview_group_notification_join_has_send, text));
            } else if (state == ApplyGroupNotice.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("加入" + text + "申请已发送");
                info.setText(ResStringUtil.getString(R.string.wechatview_group_notification_apply_to) + text);
            } else if (state == ApplyGroupNotice.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(ResStringUtil.getString(R.string.wechatview_group_notification_apply_to) + text);
            }
            btn_accept.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (state == ApplyGroupNotice.UNACCEPT) {
                        showLoading(R.string.common_text_please_wait);
                        aggreeGroupApply(groupNotice, btn_accept);
                    }
                }
            });
            //点击事件
            containerLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)) == groupNotice.getUserId()) {
                        return;
                    }
                    AddRequestActivity.start(GroupNotifacationActivity.this, groupNotice, position);
                }
            });
            //删除
            deleteButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    listGroupNotice.remove(position);
                    WeChatDBManager.getInstance().deleteGroupNotice(groupNotice.getGroupId(), groupNotice.getUserId());
                    notifyDataSetChanged();
                }
            });
        }
    }

    //同意加入群组
    private void aggreeGroupApply(final ApplyGroupNotice notice, final Button btn_accept) {

        try {
            GetHttpUtil.addUserToGroup(GroupNotifacationActivity.this, notice.getGroupId(),
                    String.valueOf(notice.getUserId()), new GetHttpUtil.ReqCallBack<Boolean>() {
                        @Override
                        public void onReqSuccess(Boolean result) {
                            dismissLoading();
                            Toast.makeText(GroupNotifacationActivity.this, 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);
                            btn_accept.setText(R.string.wechatview_group_notification_habe_joined);
                            btn_accept.setEnabled(false);
                            btn_accept.setTextColor(getResources().getColor(R.color.light_text_color));
                            btn_accept.setBackgroundColor(getResources().getColor(R.color.transparent));
                            //发送群通知
                            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);
                        }

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

    }

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

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

            @Override
            protected List<ApplyGroupNotice> doInBackground(Void... params) {
                List<ApplyGroupNotice> list = WeChatDBManager.getInstance().getGroupNoticeList(loadedCount);
                return list;
            }

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

            }


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


}
