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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

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.BaseRecycleBtnClickListener;
import com.rs.macall.androidx.basemodel.callback.CustomClickListener;
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.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.ActivityToBeReviewedBinding;
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.callback.OnAdapterLongClickListener;
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;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 待审核
 */
public class ToBeReviewedActivity extends BaseViewBindActivity<ActivityToBeReviewedBinding> {
    private InitiateRecordAdapter adapter;
    private int page;
    private final int pageSize = 10;
    private int total;
    private int refreshType;
    private int operatingType;

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

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

    @Override
    protected void init() {
        viewBinding.titleleft.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                finish();
            }
        });
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        viewBinding.rvAppList.setLayoutManager(manager);
        SmartRefreshLayoutHelp.setPullDownToRefresh(getContext(), viewBinding.srlRefresh);
        setViewOnClickListener(viewBinding.btnCancel);
        setViewOnClickListener(viewBinding.btnSubmit);
    }


    @Override
    protected void readInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            operatingType = getIntent().getIntExtra("operatingType", 1);
            savePageCacheData("operatingType", operatingType);
        } else {
            operatingType = savedInstanceState.getInt("operatingType");
        }
    }

    @Override
    protected void bindViewClick(View v) {
        if (v.getId() == R.id.btn_cancel) {
            cleanMoreOperation();
        } else if (v.getId() == R.id.btn_submit) {
            //显示批量提交弹框
            showMoreOperationDialog();
        }
    }

    private void cleanMoreOperation(){
        goneView(viewBinding.llMoreOperation);
        List<BaseBean> data = adapter.getData();
        for (int i = 0; i < data.size(); i++) {
            ApplyBean bean = (ApplyBean) data.get(i);
            bean.setMore(false);
            bean.setSel(false);
            adapter.notifyItemChanged(i, 5);
        }
    }

    private void showMoreOperationDialog() {
        Dialog dialog = new AlertDialog.Builder(getContext())
                .setView(getLayoutInflater().inflate(R.layout.dialog_batch_audit, null, false))
                .create();
        dialog.show();
        EditText editText = dialog.findViewById(R.id.edit_audit_view);
        dialog.findViewById(R.id.btn_reject).setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                submit(false,getEditText(editText));
                dialog.dismiss();
            }
        });
        dialog.findViewById(R.id.btn_pass).setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                submit(true,getEditText(editText));
                dialog.dismiss();
            }
        });
    }

    /**
     * 不通过为0   通过为 1
     *
     * @param isPass 是否通过
     */
    private void submit(boolean isPass, String opinion) {
        baseShowDialog("正在提交，请稍后...");
        List<String> applyId =  new ArrayList<>();
        List<BaseBean> data = adapter.getData();
        for (int i = 0; i < data.size(); i++) {
            ApplyBean bean = (ApplyBean) data.get(i);
            if (bean.isSel()){
                applyId.add(bean.getId());
            }
        }

        Map<String, Object> param = new HashMap<>();
        param.put("applyId", "");
        param.put("applyIds", applyId.toArray());
        param.put("auditStatus", String.valueOf(isPass ? 1 : 0));
        param.put("opinion", opinion);
        baseShowDialog("正在查询审核记录，请稍后...");
        Map<String, String> headMap = new HashMap<>(1);
        headMap.put("app-yysq-token", RuanseeApplication.getAppCache().getApply_token());
        MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
        RequestBody stringBody = RequestBody.Companion.create(new Gson().toJson(param), mediaType);
        ApiModel.request(RetrofitService.getBaseInstance().applyPost(ApplyForMainActivity.BASE_URL + "audit/batchadd", headMap, stringBody), new BaseRequestCallback<JsonObject>() {

            @Override
            public void onRequestFailure(String msg) {
                Log.e(TAG, msg);
                baseDismissDialog();
                ToastUtil.centered(getContext(), msg);
            }

            @Override
            public void onRequestSuccess(JsonObject result) {
                Log.w(TAG, result.toString());
                baseDismissDialog();
                //{"msg":"操作成功","code":200}
                try {
                    JSONObject object = new JSONObject(result.toString());
                    ToastUtil.centered(getContext(), TypConversion.getJsonStr(object,"msg"));
                    int code = TypConversion.getJsonInt(object, "code", -1);
                    if (code != 200) {
                        ToastUtil.centered(getContext(),TypConversion.getJsonStr(object,"msg"));
                        return;
                    }
                    cleanMoreOperation();
                    viewBinding.srlRefresh.autoRefresh();
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtil.centered(getContext(), "msg");
                }
            }
        });
    }

    @Override
    protected void start() {
        if (operatingType == 1) {
            viewBinding.contentTitle.setText("审核记录");
            viewBinding.rvAppList.addItemDecoration(new MyDividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
        } else if (operatingType == 2) {
            viewBinding.contentTitle.setText("我的审核");
        } else if (operatingType == 3) {
            viewBinding.contentTitle.setText("审核记录");
            viewBinding.rvAppList.addItemDecoration(new MyDividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
        }
        viewBinding.srlRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                if (page * pageSize >= total) {
                    viewBinding.srlRefresh.finishLoadMoreWithNoMoreData();
                    return;
                }
                page++;
                refreshType = 2;
                if (operatingType == 2) {
                    getAuditList();
                } else if (operatingType == 3) {
                    getAuditRecord();
                }
            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                viewBinding.srlRefresh.resetNoMoreData();
                page = 1;
//                getData();
                refreshType = 1;
                if (operatingType == 2) {
                    getAuditList();
                } else if (operatingType == 3) {
                    getAuditRecord();
                }
            }
        });
        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 getAuditRecord() {
        Map<String, Object> param = new HashMap<>();
        param.put("pageNum", page);
        param.put("pageSize", pageSize);
        Map<String, String> headMap = new HashMap<>(1);
        headMap.put("app-yysq-token", RuanseeApplication.getAppCache().getApply_token());
        ApiModel.request(RetrofitService.getBaseInstance().applyGet(ApplyForMainActivity.BASE_URL + "audit/history", headMap, param), new BaseRequestCallback<JsonObject>() {
            @Override
            public void onRequestFailure(String msg) {
                LogUtils.e(TAG, msg);
                stopRefreshAnim(-1, msg);
            }

            @Override
            public void onRequestSuccess(JsonObject result) {
                LogUtils.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();
                            if (operatingType == 2) {
                                getErrorList(0, "暂无审核!");
                            } else if (operatingType == 3) {
                                getErrorList(0, "暂无审核记录!");
                            }
                        } else {
                            viewBinding.srlRefresh.finishLoadMore();
                            refreshType = 0;
                            if (operatingType == 2) {
                                ToastUtil.centered(getContext(), "暂无审核!");
                            } else if (operatingType == 3) {
                                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(operatingType);
                        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.setApplyReason(TypConversion.getJsonStr(jsonObject, "reason"));
                        bean.setSysId(TypConversion.getJsonStr(jsonObject, "appId"));
                        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"));
                        String opType = TypConversion.getJsonStr(jsonObject, "opType");
                        bean.setRoleName(TypConversion.getJsonStr(jsonObject, "roleName"));
                        bean.setType("申请".equals(opType) ? 1 : 2);
                        dataList.add(bean);
                    }
                    if (refreshType == 1) {
                        refreshType = 0;
                        viewBinding.srlRefresh.finishRefresh();
                        if (dataList.isEmpty()) {
                            if (operatingType == 2) {
                                getErrorList(0, "暂无审核!");
                            } else if (operatingType == 3) {
                                getErrorList(0, "暂无审核记录!");
                            }
                            return;
                        }
                        initData(dataList);
                    } else {
                        viewBinding.srlRefresh.finishLoadMore();
                        refreshType = 0;
                        if (dataList.isEmpty()) {
                            if (operatingType == 2) {
                                ToastUtil.centered(getContext(), "暂无审核!");
                            } else if (operatingType == 3) {
                                ToastUtil.centered(getContext(), "暂无审核记录!");
                            }
                            return;
                        }
                        adapter.addData(dataList);
                    }
                    if (page * pageSize >= total) {
                        viewBinding.srlRefresh.finishLoadMoreWithNoMoreData();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    stopRefreshAnim(-1, e.getMessage());
                }
            }
        });
    }

    private void getAuditList() {
        Map<String, Object> param = new HashMap<>();
        param.put("pageNum", page);
        param.put("pageSize", pageSize);
        Map<String, String> headMap = new HashMap<>(1);
        headMap.put("app-yysq-token", RuanseeApplication.getAppCache().getApply_token());
        ApiModel.request(RetrofitService.getBaseInstance().applyGet(ApplyForMainActivity.BASE_URL + "audit/my", headMap, param), new BaseRequestCallback<JsonObject>() {
            @Override
            public void onRequestFailure(String msg) {
                LogUtils.e(TAG, msg);
                stopRefreshAnim(-1, msg);
            }

            @Override
            public void onRequestSuccess(JsonObject result) {
                LogUtils.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) {
                        stopRefreshAnim(0, "暂无审核!");
                        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(operatingType);
                        bean.setId(TypConversion.getJsonStr(jsonObject, "id"));
//                        bean.setSysName(TypConversion.getJsonStr(jsonObject, "appName"));
//                        bean.setRoleName(TypConversion.getJsonStr(jsonObject, "appRole"));
                        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.setApplyReason(TypConversion.getJsonStr(jsonObject, "reason"));
                        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"));
                        String opType = TypConversion.getJsonStr(jsonObject, "opType");
                        bean.setRoleName(TypConversion.getJsonStr(jsonObject, "roleName"));
                        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();
                    stopRefreshAnim(-1, e.getMessage());
                }
            }
        });
    }

    private void stopRefreshAnim(int type, String msg) {
        if (refreshType == 1) {
            refreshType = 0;
            viewBinding.srlRefresh.finishRefresh();
            getErrorList(type, msg);
        } else {
            viewBinding.srlRefresh.finishLoadMore();
            refreshType = 0;
            ToastUtil.centered(getContext(), msg);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        if (requestCode == 1101 && resultCode == Activity.RESULT_OK) {
            viewBinding.srlRefresh.autoRefresh();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void updateMoreOperationText() {
        List<BaseBean> data = adapter.getData();
        int selCount = 0;
        for (int i = 0; i < data.size(); i++) {
            ApplyBean bean = (ApplyBean) data.get(i);
            if (bean.isSel()) {
                selCount++;
            }
        }
        viewBinding.tvSelCount.setText("已选中" + selCount);
    }

    private void initData(List<BaseBean> dataList) {
        viewBinding.srlRefresh.finishRefresh();
        if (adapter == null) {
            adapter = new InitiateRecordAdapter(getContext(), dataList);
            viewBinding.rvAppList.setAdapter(adapter);
            Long interval = 1000l;
            if (operatingType == 2){
                interval = 500l;
            }
            adapter.setListClickListener(new SimpleListClickListener(interval) {
                @Override
                public void onSingleClick(View v, int pointer) {
                    BaseBean dataItem = adapter.getDataItem(pointer);
                    if (dataItem instanceof ApplyBean) {
                        ApplyBean bean = (ApplyBean) dataItem;
                        if (operatingType == 2) {
                            if (bean.isMore()) {
                                bean.setSel(!bean.isSel());
                                updateMoreOperationText();
                                adapter.notifyItemChanged(pointer, 3);
                                return;
                            }
                        }
                        Intent intent = new Intent(getContext(), ApplyDetailsActivity.class);
                        intent.putExtra("data", new Gson().toJson(bean));
                        intent.putExtra("operatingType", operatingType);
                        startActivityForResult(intent, 1101);
                    }
                }
            });
            if (operatingType == 2) {
                adapter.setBtnClickListener(new BaseRecycleBtnClickListener() {
                    @Override
                    public void onSingleClick(View v, int position, int what, Object msg) {
                        updateMoreOperationText();
                    }
                });
                adapter.setLongClickListener(new OnAdapterLongClickListener<BaseBean>(null, 0) {
                    @Override
                    protected void onLongClick(View v, BaseBean data, int position) {
                        //显示下方控件
                        if (viewBinding.llMoreOperation.getVisibility() != View.VISIBLE) {
                            viewBinding.llMoreOperation.setVisibility(View.VISIBLE);
                            List<BaseBean> data1 = adapter.getData();
                            for (int i = 0; i < data1.size(); i++) {
                                ApplyBean bean = (ApplyBean) data1.get(i);
                                bean.setMore(true);
                                if (i == position) {
                                    bean.setSel(true);
                                }
                                adapter.notifyItemChanged(i, 5);
                            }
                            updateMoreOperationText();
                        }
                    }
                });
            }
        } else {
            adapter.upData(dataList);
        }
    }
}