package com.casic.dcms.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.casic.dcms.R;
import com.casic.dcms.adapter.SwipeViewAdapter;
import com.casic.dcms.base.BaseApplication;
import com.casic.dcms.base.BaseFragment;
import com.casic.dcms.bean.NoticeBean;
import com.casic.dcms.greendao.DaoSession;
import com.casic.dcms.greendao.NoticeBeanDao;
import com.casic.dcms.ui.CaseDetailActivity;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.StringHelper;
import com.igexin.sdk.message.GTTransmitMessage;
import com.qmuiteam.qmui.recyclerView.QMUIRVItemSwipeAction;
import com.qmuiteam.qmui.recyclerView.QMUISwipeAction;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class NoticePageFragment extends BaseFragment {

    private static final String TAG = "NoticePageFragment";
    @BindView(R.id.swipeRecyclerView)
    RecyclerView swipeRecyclerView;

    private Context context;
    private List<NoticeBean> noticeBeans = new ArrayList<>();
    private SwipeViewAdapter swipeViewAdapter;
    private DaoSession daoSession;
    private static WeakReferenceHandler weakReferenceHandler;

    @Override
    protected int initLayoutView() {
        return R.layout.fragment_notice;
    }

    @Override
    protected void setupTopBarLayout() {
        context = getContext();
    }

    @Override
    protected void initData() {
        daoSession = BaseApplication.getDaoSession();
        swipeViewAdapter = new SwipeViewAdapter(context);
        //根据loginName加载历史数据
        String account = StringHelper.getUserAccount();
        if (TextUtils.isEmpty(account)) {
            return;
        }
        noticeBeans = daoSession.queryBuilder(NoticeBean.class)
                .where(NoticeBeanDao.Properties.UserAccount.eq(account))
                .orderDesc(NoticeBeanDao.Properties.PushDate)//按时间顺序最新顺序排序
                .list();
        swipeViewAdapter.setData(noticeBeans);

        weakReferenceHandler = new WeakReferenceHandler(this);
    }

    @Override
    protected void initEvent() {
        QMUIRVItemSwipeAction swipeAction = new QMUIRVItemSwipeAction(true, new QMUIRVItemSwipeAction.Callback() {
            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();
                daoSession.delete(noticeBeans.get(position));
                swipeViewAdapter.remove(position);
            }

            @Override
            public int getSwipeDirection(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                return QMUIRVItemSwipeAction.SWIPE_LEFT;
            }

            @Override
            public void onClickAction(QMUIRVItemSwipeAction swipeAction, RecyclerView.ViewHolder selected, QMUISwipeAction action) {
                super.onClickAction(swipeAction, selected, action);
                int position = selected.getAdapterPosition();
                daoSession.delete(noticeBeans.get(position));
                swipeViewAdapter.remove(position);
            }
        });
        swipeAction.attachToRecyclerView(swipeRecyclerView);
        swipeRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        });
        swipeRecyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        swipeRecyclerView.setAdapter(swipeViewAdapter);
        swipeViewAdapter.setOnItemClickListener(new SwipeViewAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                //点击之后之后，未读消息变为已读消息
                NoticeBean noticeBean = noticeBeans.get(position);
                noticeBean.setIsRead("0");
                daoSession.update(noticeBean);
                swipeViewAdapter.notifyDataSetChanged();

                String caseId = noticeBeans.get(position).getCaseId();
                Intent intent = new Intent(context, CaseDetailActivity.class);
                intent.putExtra("id", caseId);
                startActivity(intent);
            }
        });
    }

    /**
     * 供{@link com.casic.dcms.service.GeTuiIntentService#onReceiveMessageData(Context, GTTransmitMessage)}调用
     */
    public static void sendMessage(Message msg) {
        if (weakReferenceHandler == null) {
            return;
        }
        weakReferenceHandler.sendMessage(msg);
    }

    private static class WeakReferenceHandler extends Handler {
        private WeakReference<NoticePageFragment> reference;

        private WeakReferenceHandler(NoticePageFragment fragment) {
            reference = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            NoticePageFragment noticePageFragment = reference.get();
            List<NoticeBean> noticeBeans = noticePageFragment.noticeBeans;
            if (msg.what == Constant.PUSH_MESSAGE_DATA) {
                NoticeBean noticeBean = (NoticeBean) msg.obj;
                Log.d(TAG, "收到推送消息，更新列表: " + noticeBean.getCaseId());
                noticeBeans.add(0, noticeBean);//新消息永远放到第一个
                //更新数据
                noticePageFragment.swipeViewAdapter.setData(noticeBeans);
            }
        }
    }
}
