package com.ycgis.macall.personalcenter.v.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.View;

import com.google.gson.JsonObject;
import com.rs.macall.androidx.basemodel.base.BaseViewBindFragment;
import com.rs.macall.androidx.basemodel.callback.SimpleListClickListener;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.SmartRefreshLayoutHelp;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.rs.macall.androidx.basemodel.utils.TypConversion;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.ycgis.macall.personalcenter.databinding.FragmentMessageContentBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.MessageBean;
import com.ycgis.macall.personalcenter.m.requestbean.BaseRequestModel;
import com.ycgis.macall.personalcenter.m.requestbean.PagingModel;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;
import com.ycgis.macall.personalcenter.util.InsertAppUtils;
import com.ycgis.macall.personalcenter.util.ToThirdPartyAppUtils;
import com.ycgis.macall.personalcenter.v.adapter.MessageAdapter;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MessageContentFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MessageContentFragment extends BaseViewBindFragment<FragmentMessageContentBinding> {
    private int counts;
    private int pageNum;
    private final int pageSize=10;
    private ToThirdPartyAppUtils appUtils;
    public static boolean isReadMsg = false;

    private MessageAdapter adapter;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";

    // TODO: Rename and change types of parameters
    private boolean isRecord;

    public MessageContentFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment MessageContentFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MessageContentFragment newInstance(boolean isRecord) {
        MessageContentFragment fragment = new MessageContentFragment();
        Bundle args = new Bundle();
        args.putBoolean(ARG_PARAM1, isRecord);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected FragmentMessageContentBinding getViewBinding() {
        return FragmentMessageContentBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void lazyLoad() {
        viewBinding.msgSrLayout.autoRefresh();

    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void initView(View view) {
        LinearLayoutManager manager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        viewBinding.msgRvList.setLayoutManager(manager);
        SmartRefreshLayoutHelp.setRefreshAndLoad(getContext(), viewBinding.msgSrLayout);
        viewBinding.msgSrLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                if (pageNum*pageSize>=counts){
                    viewBinding.msgSrLayout.finishLoadMoreWithNoMoreData();
                    return;
                }
                pageNum++;
                getMessage();
            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                viewBinding.msgSrLayout.resetNoMoreData();
                pageNum = 1;
                getMessage();
            }
        });
    }

    @Override
    protected void startView(View view) {
        assert getArguments() != null;
        isRecord = getArguments().getBoolean(ARG_PARAM1);
        List<MessageBean> dataList=  new ArrayList<>();
        MessageBean bean = new MessageBean();
        bean.setBaseType(0);
        bean.setBaseMessage("暂无消息");
        dataList.add(bean);
        initMessage(dataList);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (adapter == null){
            viewBinding.msgSrLayout.autoRefresh();
            isRefresh = false;
        }
        if (!isRecord&&isRefresh){
            viewBinding.msgSrLayout.autoRefresh();
            isRefresh = false;
        }
        if (isReadMsg){
            viewBinding.msgSrLayout.autoRefresh();
            isReadMsg = false;
        }
    }

    private void hanLoadMore( List<MessageBean> messageBeanList){
        viewBinding.msgSrLayout.finishLoadMore();
        if (messageBeanList == null||messageBeanList.isEmpty())return;
        adapter.addData(messageBeanList);
    }

    private boolean isRefresh = false;
    private void hanRefreshMore( List<MessageBean> messageBeanList,int type,String msg){
        viewBinding.msgSrLayout.finishRefresh();
        if (messageBeanList == null){
            messageBeanList = new ArrayList<>();
        }
        if (messageBeanList.isEmpty()){
            MessageBean bean = new MessageBean();
            bean.setBaseType(type);
            bean.setBaseMessage(msg);
            messageBeanList.add(bean);
        }
        initMessage(messageBeanList);
    }

    public void getMessage(){
        ApiModel.request(RetrofitService.getBaseInstance().getMessage(isRecord?1:0, pageNum, pageSize), new BaseRequestCallback<BaseRequestModel<PagingModel<MessageBean>>>() {
            @Override
            public void onRequestFailure(String msg) {
                LogUtils.e(TAG, msg);
               if (viewBinding.msgSrLayout.isLoading()){
                   hanLoadMore(null);
               }
               if (viewBinding.msgSrLayout.isRefreshing()){
                   hanRefreshMore(null,-1,msg);
               }
            }

            @Override
            public void onRequestSuccess(BaseRequestModel<PagingModel<MessageBean>> result) {
                LogUtils.w(TAG, result.toString());
                if (result.getCode()==20041){
                    PagingModel<MessageBean> data = result.getData();
                    if (data == null){
                        if (viewBinding.msgSrLayout.isLoading()){
                            hanLoadMore(null);
                        }
                        if (viewBinding.msgSrLayout.isRefreshing()){
                            hanRefreshMore(null,-1,"");
                        }
                        return;
                    }
                    counts = data.getCounts();
                    List<MessageBean> items = data.getItems();
                    if (counts<=0||items.isEmpty()){
                        if (viewBinding.msgSrLayout.isLoading()){
                            hanLoadMore(null);
                        }
                        if (viewBinding.msgSrLayout.isRefreshing()){
                            hanRefreshMore(null,0,"暂无消息");
                        }
                        return;
                    }
                    for (MessageBean b :items) {
                        b.setBaseType(1);
                        b.setRead(!"0".equals(b.getState()));
                    }
                    if (viewBinding.msgSrLayout.isLoading()){
                        hanLoadMore(items);
                    }
                    if (viewBinding.msgSrLayout.isRefreshing()){
                        hanRefreshMore(items,0,"暂无新消息");
                    }
                    if (pageNum*pageSize>=counts){
                        viewBinding.msgSrLayout.finishLoadMoreWithNoMoreData();
                    }
                    return;
                }
                if (viewBinding.msgSrLayout.isLoading()){
                    hanLoadMore(null);
                }
                if (viewBinding.msgSrLayout.isRefreshing()){
                    hanRefreshMore(null,-1,result.getMsg());
                }
            }
        });
    }

    private void initMessage(List<MessageBean> dataList) {
        viewBinding.msgSrLayout.finishRefresh();
        if (adapter == null) {
            adapter = new MessageAdapter(getContext(), dataList);
            viewBinding.msgRvList.setAdapter(adapter);
            adapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    if (appUtils == null){
                        appUtils = new ToThirdPartyAppUtils(getContext());
                        getLifecycle().addObserver(appUtils);
                    }
                    appUtils.skipReadMsg(adapter.getDataItem(pointer));
                    //点击后刷新
                    isRefresh = true;
                    if (!isRecord){
                        Home2Fragment.isReadMsg = true;
                    }
                }
            });
        }else {
            adapter.upData(dataList);
        }
    }
}