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

import android.content.Intent;
import android.os.Bundle;

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

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
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.decoration.MyDividerItemDecoration;
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.R;
import com.ycgis.macall.personalcenter.databinding.FragmentApplyOkBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.ApplyBean;
import com.ycgis.macall.personalcenter.m.adapterbean.BaseBean;
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.v.activity.applyfo.ApplyDetailsActivity;
import com.ycgis.macall.personalcenter.v.activity.applyfo.ApplyForMainActivity;
import com.ycgis.macall.personalcenter.v.adapter.InitiateRecordAdapter;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ApplyOkFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ApplyOkFragment extends BaseViewBindFragment<FragmentApplyOkBinding> {
    private InitiateRecordAdapter adapter;
    private int page;
    private final int pageSize = 10;
    private int total;
    private int refreshType;

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

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ApplyOkFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ApplyOkFragment newInstance(String param1, String param2) {
        ApplyOkFragment fragment = new ApplyOkFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

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

    @Override
    protected void lazyLoad() {

    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void initView(View view) {
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        viewBinding.rvAppList.addItemDecoration(new MyDividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
        viewBinding.rvAppList.setLayoutManager(manager);
        SmartRefreshLayoutHelp.setRefreshAndLoad(getContext(), viewBinding.srlRefresh);
    }

    @Override
    protected void startView(View view) {
        viewBinding.srlRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                if (page * pageSize >= total) {
                    viewBinding.srlRefresh.finishLoadMoreWithNoMoreData();
                    return;
                }
                refreshType = 2;
                page++;
                getData();
            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                viewBinding.srlRefresh.resetNoMoreData();
                page = 1;
                refreshType = 1;
                getData();
            }
        });
        viewBinding.srlRefresh.autoRefresh();
    }

    private void getErrorList(int type, String msg) {
        List<BaseBean> baseBeans = new ArrayList<>();
        BaseBean baseBean = new BaseBean() {
        };
        baseBean.setBaseType(type);
        baseBean.setBaseMessage(msg);
        baseBeans.add(baseBean);
        initData(baseBeans);
    }

    private void getData() {
        Map<String, Object> param = new HashMap<>();
        param.put("pageNum", page);
        param.put("pageSize", pageSize);
        param.put("status", 1);
        Map<String, String> headMap = new HashMap<>(1);
        headMap.put("app-yysq-token", RuanseeApplication.getAppCache().getApply_token());
        ApiModel.request(RetrofitService.getBaseInstance().applyGet(ApplyForMainActivity.BASE_URL + "apply/list", headMap, param), new BaseRequestCallback<JsonObject>() {
            @Override
            public void onRequestFailure(String msg) {
                Log.e(TAG, msg);
                if (refreshType == 1) {
                    refreshType = 0;
                    viewBinding.srlRefresh.finishRefresh();
                    getErrorList(0, msg);
                } else {
                    viewBinding.srlRefresh.finishLoadMore();
                    refreshType = 0;
                    ToastUtil.centered(getContext(), msg);
                }
            }

            @Override
            public void onRequestSuccess(JsonObject result) {
                Log.w(TAG, result.toString());
                try {
                    JSONObject object = new JSONObject(result.toString());
                    int code = TypConversion.getJsonInt(object, "code", -1);
                    if (code != 200) {
                        getErrorList(-1, TypConversion.getJsonStr(object, "msg"));
                        return;
                    }
                    total = TypConversion.getJsonInt(object, "total", 0);
                    JSONArray rows = TypConversion.getJSONArray(object, "rows");
                    if (rows == null) {
                        if (refreshType == 1) {
                            refreshType = 0;
                            viewBinding.srlRefresh.finishRefresh();
                            getErrorList(0, "暂无已通过的申请!");
                        } else {
                            viewBinding.srlRefresh.finishLoadMore();
                            refreshType = 0;
                            ToastUtil.centered(getContext(), "暂无已通过的申请!");
                        }
                        return;
                    }

                    List<BaseBean> dataList = new ArrayList<>();
                    for (int i = 0; i < rows.length(); i++) {
                        JSONObject jsonObject = TypConversion.getJSONObject(rows, i);
                        if (jsonObject == null) continue;
                        int status = TypConversion.getJsonInt(jsonObject, "status", 11);
                        if (status== 0)continue;
                        ApplyBean bean = new ApplyBean();
                        bean.setBaseType(1);
                        bean.setSysId(TypConversion.getJsonStr(jsonObject,"appId"));
                        bean.setId(TypConversion.getJsonStr(jsonObject,"id"));
                        bean.setSysName(TypConversion.getJsonStr(jsonObject, "appName"));
                        bean.setRoleName(TypConversion.getJsonStr(jsonObject, "appRole"));
                        bean.setPhone(TypConversion.getJsonStr(jsonObject, "contact"));
                        bean.setName(TypConversion.getJsonStr(jsonObject, "nickName"));
                        bean.setCode(TypConversion.getJsonStr(jsonObject, "userName"));
                        bean.setDeptCode(TypConversion.getJsonStr(jsonObject, "deptId"));
                        bean.setDeptName(TypConversion.getJsonStr(jsonObject, "deptName"));
                        bean.setIdCordNum(TypConversion.getJsonStr(jsonObject, "idcard"));
                        bean.setState(TypConversion.getJsonInt(jsonObject, "status", 11));
                        bean.setNode(TypConversion.getJsonStr(jsonObject, "appRole"));
                        bean.setTime(TypConversion.getJsonStr(jsonObject, "opTime"));
                        bean.setUserId(TypConversion.getJsonStr(jsonObject, "userId"));
                        bean.setApplyReason(TypConversion.getJsonStr(jsonObject, "reason"));
                        String opType = TypConversion.getJsonStr(jsonObject, "opType");
                        bean.setType("申请".equals(opType) ? 1 : 2);
                        dataList.add(bean);
                    }
                    if (refreshType == 1) {
                        refreshType = 0;
                        viewBinding.srlRefresh.finishRefresh();
                        if (dataList.isEmpty()) {
                            getErrorList(0, "暂无已通过的申请!");
                            return;
                        }
                        initData(dataList);
                    } else {
                        viewBinding.srlRefresh.finishLoadMore();
                        refreshType = 0;
                        if (dataList.isEmpty()) {
                            ToastUtil.centered(getContext(), "暂无已通过的申请！");
                            return;
                        }
                        adapter.addData(dataList);
                    }
                    if (page*pageSize>=total){
                        viewBinding.srlRefresh.finishLoadMoreWithNoMoreData();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    if (refreshType == 1) {
                        refreshType = 0;
                        viewBinding.srlRefresh.finishRefresh();
                        getErrorList(-1, e.getMessage());
                    } else {
                        viewBinding.srlRefresh.finishLoadMore();
                        refreshType = 0;
                        ToastUtil.centered(getContext(), e.getMessage());
                    }
                }
            }
        });
    }

    private void initData(List<BaseBean> dataList) {
        viewBinding.srlRefresh.finishRefresh();
        if (adapter == null) {
            adapter = new InitiateRecordAdapter(getContext(), dataList);
            viewBinding.rvAppList.setAdapter(adapter);
            adapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    BaseBean dataItem = adapter.getDataItem(pointer);
                    if (dataItem instanceof ApplyBean) {
                        ApplyBean bean = (ApplyBean) dataItem;
                        Intent intent = new Intent(getContext(), ApplyDetailsActivity.class);
                        intent.putExtra("data", new Gson().toJson(bean));
                        intent.putExtra("operatingType", 1);
                        startActivity(intent);
                    }
                }
            });
        } else {
            adapter.upData(dataList);
        }
    }
}