package com.ycgis.macall.personalcenter.v.activity.applyfo;

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

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.rs.macall.androidx.basemodel.base.BaseViewBindActivity;
import com.rs.macall.androidx.basemodel.callback.SimpleListClickListener;
import com.rs.macall.androidx.basemodel.decoration.MyDividerItemDecoration;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.SmartRefreshLayoutHelp;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
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.ActivityPersonnelReviewBinding;
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.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;

/**
 * 人员审查
 */
public class PersonnelReviewActivity extends BaseViewBindActivity<ActivityPersonnelReviewBinding> {
    private InitiateRecordAdapter adapter;

    private int page;
    private final int pageSize = 10;
    private int total;

    @Override
    protected boolean isImmersiveStatusBar() {
        return true;
    }

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

    @Override
    protected void init() {
        viewBinding.reviewSearch.editQuery.setHint("请输入警号姓名搜索");
        SmartRefreshLayoutHelp.setRefreshAndLoad(getContext(), viewBinding.reviewSrf);
        viewBinding.reviewRv.addItemDecoration(new MyDividerItemDecoration(getContext(),LinearLayoutManager.VERTICAL));
        viewBinding.reviewRv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        viewBinding.reviewTitle.titleleft.setOnClickListener(v -> finish());
        viewBinding.reviewTitle.leftImage.setImageDrawable(getDrawable(R.drawable.ic_back));
        viewBinding.reviewTitle.contentTitle.setText("人员审查");
        viewBinding.reviewSearch.editQuery.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void start() {
        viewBinding.reviewSearch.editQuery.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String editText = getEditText(viewBinding.reviewSearch.editQuery);
                    searchData(editText);
                    return true;
                }
                return false;
            }
        });
        viewBinding.reviewSrf.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                if (pageSize * page >= total) {
                    //没有gengd
                    refreshLayout.finishLoadMoreWithNoMoreData();
                    return;
                }
                page++;
                getData();
            }

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

    private void searchData(String searchWord) {
        if (StringUtil.isNullOrEmpty(searchWord)) {
            ToastUtil.centered(getContext(), "请输入警号或者姓名进行搜索！");
            return;
        }
        viewBinding.reviewSrf.autoRefresh();
    }

    private void getData() {
        String editText = getEditText(viewBinding.reviewSearch.editQuery);
        Map<String, String> headMap = new HashMap<>(1);
        headMap.put("app-yysq-token", RuanseeApplication.getAppCache().getApply_token());
        Map<String, Object> param = new HashMap<>();
        param.put("pageSize", String.valueOf(pageSize));
        param.put("pageNum", String.valueOf(page));
        if (StringUtil.hasContent(editText)) {
            if (StringUtil.isInteger(editText)) {
                param.put("userName", editText);
            } else {
                param.put("nickName", editText);
            }
        }
        ApiModel.request(RetrofitService.getBaseInstance().applyGet(ApplyForMainActivity.BASE_URL + "apply/shenchalist", headMap, param),
                new BaseRequestCallback<JsonObject>() {

                    @Override
                    public void onRequestSuccess(JsonObject result) {
                        LogUtils.d(result.toString());
                        try {
                            JSONObject object = new JSONObject(result.toString());
                            int code = TypConversion.getJsonInt(object, "code", -1);
                            if (code == 200) {
                                total = TypConversion.getJsonInt(object, "total", -1);
                                JSONArray rows = TypConversion.getJSONArray(object, "rows");

                                List<BaseBean> dataList = new ArrayList<>();
                                for (int i = 0; i < rows.length(); i++) {
                                    JSONObject jsonObject = TypConversion.getJSONObject(rows, i);
                                    if (jsonObject == null) return;
                                    ApplyBean bean = new ApplyBean();
                                    bean.setBaseType(3);
                                    bean.setApplyReason(TypConversion.getJsonStr(jsonObject, "reason"));
                                    bean.setId(TypConversion.getJsonStr(jsonObject, "id"));

                                    bean.setRoleName(TypConversion.getJsonStr(jsonObject, "roleName"));
                                    bean.setNode(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(1);
                                    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 (viewBinding.reviewSrf.isRefreshing()) {
                                    viewBinding.reviewSrf.finishRefresh();
                                    if (dataList.isEmpty()) {
                                        getErrorList(0, "暂无审核记录!");
                                        return;
                                    }
                                    initData(dataList);
                                } else {
                                    viewBinding.reviewSrf.finishLoadMore();
                                    if (!dataList.isEmpty()) {
                                        adapter.addData(dataList);
                                    }
                                }
                            } else {
                                if (viewBinding.reviewSrf.isRefreshing()) {
                                    viewBinding.reviewSrf.finishRefresh();
                                    getErrorList(-1, TypConversion.getJsonStr(object, "msg"));
                                } else {
                                    viewBinding.reviewSrf.finishLoadMore();
                                    ToastUtil.centered(getContext(), TypConversion.getJsonStr(object, "msg"));
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            if (viewBinding.reviewSrf.isRefreshing()) {
                                viewBinding.reviewSrf.finishRefresh();
                                getErrorList(-1, e.getMessage());
                            } else {
                                viewBinding.reviewSrf.finishLoadMore();
                                ToastUtil.centered(getContext(), e.getMessage());
                            }
                        }
                    }

                    @Override
                    public void onRequestFailure(String msg) {
                        LogUtils.e(msg);
                        if (viewBinding.reviewSrf.isRefreshing()) {
                            viewBinding.reviewSrf.finishRefresh();
                            getErrorList(-1, msg);
                        } else {
                            viewBinding.reviewSrf.finishLoadMore();
                            ToastUtil.centered(getContext(), msg);
                        }
                    }
                });

    }

    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 initData(List<BaseBean> baseBeans) {
        if (adapter == null) {
            adapter = new InitiateRecordAdapter(getContext(), baseBeans);
            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", 3);
                        startActivity(intent);
                    }
                }
            });
            viewBinding.reviewRv.setAdapter(adapter);
        } else {
            adapter.upData(baseBeans);
        }
    }


}