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

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

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
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.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.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.ActivityUpdateDeptBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.BaseBean;
import com.ycgis.macall.personalcenter.m.adapterbean.OrgBean;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.callback.EditTextWatcherListener;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;
import com.ycgis.macall.personalcenter.v.adapter.SelectDeptAdapter;

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 UpdateDeptActivity extends BaseViewBindActivity<ActivityUpdateDeptBinding> {
    private SelectDeptAdapter adapter;
    private int total, page, pageSize = 50;
    private String searchWord;
    private String imei = "", imsi = "";
    private String selectDeptCode;

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

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

    @Override
    protected void init() {
        viewBinding.updateDeptTitle.contentTitle.setText(R.string.applyUpdateDept);
        viewBinding.updateDeptTitle.rightText.setText(R.string.submitApply);
        viewBinding.updateDeptTitle.leftImage.setImageDrawable(getDrawables(R.drawable.back_cliener));
        viewBinding.updateDeptTitle.titleleft.setOnClickListener(v -> finish());
        viewBinding.updateDeptTitle.titleright.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                submitDept();
            }
        });
        MyDividerItemDecoration myDividerItemDecoration = new MyDividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
        myDividerItemDecoration.setBottom(true);
        viewBinding.updateDeptList.addItemDecoration(myDividerItemDecoration);
        viewBinding.updateDeptList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        SmartRefreshLayoutHelp.setRefreshAndLoad(getContext(), viewBinding.updateDeptSrl);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {
        imei = getIntent().getStringExtra("imei");
        imsi = getIntent().getStringExtra("imsi");
//        ToastUtil.centered(getContext(),String.format("imei:%s || imsi:%s",imei,imsi));
    }

    @Override
    protected void start() {
        viewBinding.updateDeptSearch.editQuery.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        //处理搜索事件
        viewBinding.updateDeptSearch.editQuery.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                searchWord = getEditText(viewBinding.updateDeptSearch.editQuery);
                viewBinding.updateDeptSrl.autoRefresh();
                return true;
            }
            return false;
        });
        //处理清空事件
        viewBinding.updateDeptSearch.btnClean.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                viewBinding.updateDeptSearch.editQuery.setText("");
                searchWord = "";
            }
        });
        //处理 清空按钮
        viewBinding.updateDeptSearch.editQuery.addTextChangedListener(new EditTextWatcherListener() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s == null || StringUtil.isNullOrEmpty(s.toString())) {
                    goneView(viewBinding.updateDeptSearch.btnClean);
                    return;
                }
                visibleView(viewBinding.updateDeptSearch.btnClean);
            }
        });
        //
        viewBinding.updateDeptSrl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                if (total <= page * pageSize) {
                    viewBinding.updateDeptSrl.finishLoadMoreWithNoMoreData();
                    return;
                }
                page++;
                getDeptData();
            }

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

    private OrgBean getErrorBean(int type, String msg) {
        OrgBean bean = new OrgBean();
        bean.setBaseType(type);
        bean.setBaseMessage(msg);
        return bean;
    }

    private void submitDept() {
        if (StringUtil.isNullOrEmpty(selectDeptCode)) {
            ToastUtil.centered(getContext(), "请先选择单位这提交申请！");
            return;
        }
        baseShowFaseDialong("重要提醒", "正在提交申请，请勿执行其他操作，申请成功后需等待管路员审核！");
        Map<String, String> param = new HashMap<>();
        param.put("token", RuanseeApplication.getAppCache().getToken());
        param.put("clientType", "MOBILE");
        param.put("deviceFlags", imei);
        param.put("imsi1", imsi);
        param.put("sysCode", RuanseeApplication.getAppCache().getSysmCode());
        param.put("orgCode", selectDeptCode);
        ApiModel.request(RetrofitService.getBaseInstance().getLoginType("http://20.90.2.2/UniAuth/api/sso/v1/auditUserOrg", param),
                new BaseRequestCallback<JsonObject>() {
                    @Override
                    public void onRequestFailure(String msg) {
                        baseDismissDialog();
                        ToastUtil.centered(getContext(), msg);
                    }

                    @Override
                    public void onRequestSuccess(JsonObject result) {
                        baseDismissDialog();
                        LogUtils.w(TAG, result.toString());
                        try {
                            JSONObject object = new JSONObject(result.toString());
                            int code = TypConversion.getJsonInt(object, "code", -1);
                            if (code == 200) {
                                ToastUtil.centered(getContext(),"申请提交成功，请等待审核！");
                            } else {
                                ToastUtil.centered(getContext(), StringUtil.get(TypConversion.getJsonStr(object, "msg"), TypConversion.getJsonStr(object, "content")));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ToastUtil.centered(getContext(), e.getMessage());
                        }
                    }
                });
    }

    private void getDeptData() {
//        Map<String, String> param = new HashMap<>();
//        param.put("token", RuanseeApplication.getAppCache().getToken());
//        param.put("clientType", "MOBILE");
//        param.put("deviceFlags", imei);
//        param.put("imsi1", imsi);
//        param.put("sysCode", RuanseeApplication.getAppCache().getSysmCode());
//        param.put("page", pageSize + "");
//        param.put("pageSize", page + "");
//        param.put("size", pageSize + "");
//        param.put("orgName", searchWord);
        ApiModel.request(RetrofitService.getBaseInstance().getDeptList(searchWord, page, pageSize),
                new BaseRequestCallback<JsonObject>() {
                    @Override
                    public void onRequestFailure(String msg) {
                        ToastUtil.centered(getContext(), msg);
                        if (viewBinding.updateDeptSrl.isRefreshing()) {
                            viewBinding.updateDeptSrl.finishRefresh();
                            List<OrgBean> data = new ArrayList<>();
                            OrgBean errorBean = getErrorBean(-1, msg);
                            data.add(errorBean);
                            initData(data);
                        }
                        if (viewBinding.updateDeptSrl.isLoading()) {
                            viewBinding.updateDeptSrl.finishLoadMore();
                        }
                    }

                    @Override
                    public void onRequestSuccess(JsonObject result) {
                        try {
                            JSONObject object = new JSONObject(result.toString());
                            String code = TypConversion.getJsonStr(object, "code");
                            if (!code.equals("20041")) {
                                if (viewBinding.updateDeptSrl.isRefreshing()) {
                                    viewBinding.updateDeptSrl.finishRefresh();
                                    List<OrgBean> data = new ArrayList<>();
                                    OrgBean errorBean = getErrorBean(-1, TypConversion.getJsonStr(object, "msg"));
                                    data.add(errorBean);
                                    initData(data);
                                }
                                if (viewBinding.updateDeptSrl.isLoading()) {
                                    viewBinding.updateDeptSrl.finishLoadMore();
                                }
                                return;
                            }
                            JSONObject dataJson = object.getJSONObject("data");
                            total = TypConversion.getJsonInt(dataJson, "counts", 0);
                            Gson gson = new Gson();
                            List<OrgBean> data = new ArrayList<>();
                            JSONArray array = dataJson.getJSONArray("items");
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject object1 = array.getJSONObject(i);
                                OrgBean bean = gson.fromJson(object1.toString(), OrgBean.class);
                                bean.setBaseType(1);
                                data.add(bean);
                            }
                            if (viewBinding.updateDeptSrl.isRefreshing()) {
                                if (data.isEmpty()) {
                                    OrgBean errorBean = getErrorBean(0, "暂无数据！");
                                    data.add(errorBean);
                                }
                                initData(data);
                                viewBinding.updateDeptSrl.finishRefresh();
                            }
                            if (viewBinding.updateDeptSrl.isLoading()) {
                                if (!data.isEmpty()) {
                                    adapter.addData(data);
                                }
                                viewBinding.updateDeptSrl.finishLoadMore();
                            }
                            if (total <= page * pageSize) {
                                viewBinding.updateDeptSrl.finishLoadMoreWithNoMoreData();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ToastUtil.centered(getContext(), e.getMessage());
                            if (viewBinding.updateDeptSrl.isRefreshing()) {
                                viewBinding.updateDeptSrl.finishRefresh();
                                List<OrgBean> data = new ArrayList<>();
                                OrgBean errorBean = getErrorBean(-1, e.getMessage());
                                data.add(errorBean);
                                initData(data);
                            }
                            if (viewBinding.updateDeptSrl.isLoading()) {
                                viewBinding.updateDeptSrl.finishLoadMore();
                            }
                        }
                    }
                });
    }

    private void initData(List<OrgBean> data) {
        if (adapter == null) {
            adapter = new SelectDeptAdapter(getContext(), data);
            viewBinding.updateDeptList.setAdapter(adapter);
            adapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    OrgBean dataItem = adapter.getDataItem(pointer);
                    if (dataItem.isSelect()) {
                        return;
                    }
                    for (int i = 0; i < adapter.getItemCount(); i++) {
                        OrgBean dataItem1 = adapter.getDataItem(i);
                        if (dataItem1.isSelect()) {
                            dataItem1.setSelect(false);
                            adapter.notifyItemChanged(i, 12);
                            break;
                        }
                    }
                    dataItem.setSelect(true);
                    adapter.notifyItemChanged(pointer, 12);
                    selectDeptCode = dataItem.getOrgCode();
                }
            });
        } else {
            adapter.upData(data);
        }
    }
}