package xn.xxp.home.notice;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.util.Pair;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.kongzue.dialogx.dialogs.PopMenu;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kongzue.dialogx.interfaces.OnMenuItemClickListener;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import http.client.ApiRepository;
import http.client.HttpTool;
import http.vo.request.NoticeReq;
import http.vo.response.LaboratoryVo;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.Response;
import xn.xxp.databinding.ActivityNoticeListBinding;
import xn.xxp.app.LabApp;
import xn.xxp.room.RoomTool;
import xn.xxp.room.bean.DeviceConfig;
import xn.xxp.room.bean.LabConfig;
import xn.xxp.room.bean.NoticeSummary;

public class NoticeListActivity extends AppCompatActivity implements OnRefreshListener, OnRefreshLoadMoreListener, AdapterView.OnItemClickListener {
    private ActivityNoticeListBinding binding;
    private int page = 1;
    private CompositeDisposable compositeDisposable;
    private List<NoticeSummary> noticeSummaryList = new ArrayList<>();
    private NoticeListAdapter noticeListAdapter;
    private final String[] itemArray = {"全部通知", "整改通知", "消息通知"};
    private DeviceConfig deviceConfig;
    private LabConfig labConfig;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityNoticeListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        compositeDisposable = new CompositeDisposable();
        LaboratoryVo laboratoryVo = LabApp.laboratory;
        deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
        labConfig = RoomTool.getInstance().labConfigDao().getLabConfig();
        if (null != laboratoryVo) {
            Glide.with(this).load(laboratoryVo.rectangleLogo).into(binding.logo);
            binding.subName.setText(laboratoryVo.subName);
        }
        binding.nowDate.setText(TimeUtils.getNowString(new SimpleDateFormat("MM月dd日 EEEE ", Locale.getDefault())));
        binding.smartRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        binding.smartRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        binding.smartRefreshLayout.setOnRefreshListener(this);
        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(this);
        binding.smartRefreshLayout.autoRefresh();
        noticeListAdapter = new NoticeListAdapter(this, noticeSummaryList);
        binding.noticeLV.setAdapter(noticeListAdapter);
        binding.backLayout.setOnClickListener(v -> finish());
        binding.noticeLV.setOnItemClickListener(this);
        binding.noticeTypeACBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopMenu.show(binding.noticeTypeACBT, itemArray).setOverlayBaseView(false).setAlignGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL).setOnMenuItemClickListener(new OnMenuItemClickListener<PopMenu>() {
                    @Override
                    public boolean onClick(PopMenu dialog, CharSequence text, int index) {
                        binding.noticeTypeACBT.setText(text);
                        binding.smartRefreshLayout.autoRefresh();
                        return false;
                    }
                });
            }
        });
    }

    private void getMsgList() {
        NoticeReq noticeReq = new NoticeReq();
        noticeReq.businessTypeList.add(0L);
        noticeReq.businessTypeList.add(1L);
        noticeReq.businessTypeList.add(13L);
        noticeReq.subIds = String.valueOf(labConfig.getLabId());
        noticeReq.page = page;
        noticeReq.pageSize = 20;
        Disposable disposable = ApiRepository.INSTANCE.newMsgGroup(noticeReq).subscribe(new Consumer<List<NoticeSummary>>() {
            @Override
            public void accept(List<NoticeSummary> noticeSummaries) throws Exception {
                if (null == noticeSummaries || noticeSummaries.isEmpty()) {
                    binding.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                    binding.smartRefreshLayout.finishRefreshWithNoMoreData();
                } else {
                    RoomTool.getInstance().noticeSummaryDao().insert(noticeSummaries.toArray(new NoticeSummary[0]));
                    // 全部消息
                    if (itemArray[0].equals(binding.noticeTypeACBT.getText().toString())) {
                        noticeSummaryList.addAll(noticeSummaries);
                    }
                    // 整改消息
                    else if (itemArray[1].equals(binding.noticeTypeACBT.getText().toString())) {
                        for (int i = 0; i < noticeSummaries.size(); i++) {
                            NoticeSummary NoticeSummary = noticeSummaries.get(i);
                            if (13==(NoticeSummary.getBusinessType())) {
                                noticeSummaryList.add(NoticeSummary);
                            }
                        }
                    }
                    // 其它消息
                    else if (itemArray[2].equals(binding.noticeTypeACBT.getText().toString())) {
                        for (int i = 0; i < noticeSummaries.size(); i++) {
                            NoticeSummary NoticeSummary = noticeSummaries.get(i);
                            if (13!=(NoticeSummary.getBusinessType())) {
                                noticeSummaryList.add(NoticeSummary);
                            }
                        }
                    }
                    noticeListAdapter.notifyDataSetChanged();
                    binding.smartRefreshLayout.finishRefresh();
                    binding.smartRefreshLayout.finishLoadMore();
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                LogUtils.e(throwable.toString());
                binding.smartRefreshLayout.finishRefresh();
                binding.smartRefreshLayout.finishLoadMore();
            }
        });
        compositeDisposable.add(disposable);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        NoticeSummary noticeSummary = noticeSummaryList.get(position);
        if (13!=(noticeSummary.getBusinessType())) {
            String sendDesc = noticeSummary.getSendDesc();
            if (null == sendDesc || sendDesc.isEmpty()) {
                ToastUtils.showLong("无法查看更多信息!");
                return;
            }
            WaitDialog.show("正在查询详情...");
            ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Pair<Integer, String>>() {
                @Override
                public Pair<Integer, String> doInBackground() throws Throwable {
                    try {
                        Response response = HttpTool.getRectifyAdviceNoteView(noticeSummary.getSendDesc());
                        if (response.isSuccessful()) {
                            RectifyMsg rectifyMsg = GsonUtils.fromJson(response.body().string(), RectifyMsg.class);
                            if (rectifyMsg.getCode() == 200) {
                                LogUtils.json(rectifyMsg);
                                RectifyMsg.RectifyMsgBean rectifyMsgBean = rectifyMsg.getData();
                                return Pair.create(rectifyMsgBean.getCheckCategory(), GsonUtils.toJson(rectifyMsgBean));
                            }
                        }
                    } catch (Exception e) {
                        LogUtils.e(Log.getStackTraceString(e));
                    }
                    return Pair.create(0, null);
                }

                @Override
                public void onSuccess(Pair<Integer, String> result) {
                    WaitDialog.dismiss();
                    // 校级:1
                    if (result.first == 1) {
                        Intent intent = new Intent(NoticeListActivity.this, NoticeMsgSchoolActivity.class);
                        intent.putExtra("json", result.second);
                        startActivity(intent);
                    }
                    // 院级:2
                    else if (result.first == 2) {
                        Intent intent = new Intent(NoticeListActivity.this, NoticeMsgCollegeActivity.class);
                        intent.putExtra("json", result.second);
                        startActivity(intent);
                    } else {
                        ToastUtils.showLong("没有更多信息了!");
                    }
                }
            });
        }
        // 系统消息
        else if (0!=(noticeSummary.getBusinessType())) {
            if (!TextUtils.isEmpty(noticeSummary.getContent())) {
                Intent intent = new Intent(NoticeListActivity.this, NoticeMsgSystemActivity.class);
                intent.putExtra("content", noticeSummary.getContent());
                startActivity(intent);
            } else {
                ToastUtils.showLong("没有更多信息了!");
            }
        } else {
            ToastUtils.showLong("没有更多信息了!");
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        noticeSummaryList.clear();
        getMsgList();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        getMsgList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        compositeDisposable.dispose();
        compositeDisposable.clear();
    }

}