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

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

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

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.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.OnRefreshListener;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.ActivityApplyForMainBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.ActionBean;
import com.ycgis.macall.personalcenter.m.adapterbean.BaseBean;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.app.UserData;
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.AhdsAddressUtils;
import com.ycgis.macall.personalcenter.v.adapter.ApplyForMainAdapter;

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 ApplyForMainActivity extends BaseViewBindActivity<ActivityApplyForMainBinding> {
    private ApplyForMainAdapter applyForMainAdapter;

    //TODO 正式环境地址
    public static final String BASE_PHOTO_URL = "http://20.90.2.2";
    public static final String BASE_URL = BASE_PHOTO_URL + "/yysq_app_out/";

    //TODO 测试环境地址
//    public static final String BASE_PHOTO_URL = "http://192.168.0.109:8086";
//    public static final String BASE_URL = BASE_PHOTO_URL + "/app/";

    private Map<String, ActionBean> actionBeanMap;

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

    @Override
    protected boolean isImmersiveStatusBar() {
        return true;
    }
    @Override
    protected void init() {
        GridLayoutManager manager = new GridLayoutManager(getContext(), 2);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int itemViewType = applyForMainAdapter.getItemViewType(position);
                if (itemViewType == 1) {
                    return 1;
                }
                return 2;
            }
        });
        LinearLayoutManager manager1 = new LinearLayoutManager(getContext());
        manager1.setOrientation(LinearLayoutManager.VERTICAL);
        viewBinding.rvAppList.setLayoutManager(manager1);
        viewBinding.ivExit.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                finish();
            }
        });
        SmartRefreshLayoutHelp.setPullDownToRefresh(getContext(), viewBinding.srlRefresh);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void start() {
        //TODO 测试使用
//        setTestUer();
        UserData userData = RuanseeApplication.getUserData();
        viewBinding.tvUserName.setText(String.format("你好！%s警官(%s)", userData.getUserName(), userData.getUserCode()));
        viewBinding.tvUserDeptName.setText(userData.getDeptName());
        viewBinding.srlRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                getData();
            }
        });
        viewBinding.srlRefresh.autoRefresh();
    }

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

    private void getData() {
        String apply_token = RuanseeApplication.getAppCache().getApply_token();
        if (StringUtil.isNullOrEmpty(apply_token)) {
//            ApiModel.request(RetrofitService.getBaseInstance().applyLogin(BASE_URL + "login", "064922"),
            ApiModel.request(RetrofitService.getBaseInstance().applyLogin(BASE_URL + "login", RuanseeApplication.getUserData().getUserCode()),
//            ApiModel.request(RetrofitService.getBaseInstance().applyLogin(BASE_URL + "login","ahst"),
                    new BaseRequestCallback<JsonObject>() {
                        @Override
                        public void onRequestFailure(String msg) {
                            LogUtils.e(TAG, msg);
                            ToastUtil.centered(getContext(), msg);
                            viewBinding.srlRefresh.finishRefresh();
                            loginError(-1, msg);
                        }

                        @Override
                        public void onRequestSuccess(JsonObject result) {
                            LogUtils.w(TAG, result.toString());
                            viewBinding.srlRefresh.finishRefresh();
                            try {
                                JSONObject jsonObject = new JSONObject(result.toString());
                                int code = TypConversion.getJsonInt(jsonObject, "code", -1);
                                if (code != 200) {
                                    loginError(-1, TypConversion.getJsonStr(jsonObject, "msg"));
                                    return;
                                }
                                JSONObject data = TypConversion.getJSONObject(jsonObject, "data");
                                String token = TypConversion.getJsonStr(data, "token");
                                RuanseeApplication.getAppCache().setApply_token(token);
                                testIndex(token);
                            } catch (JSONException e) {
                                e.printStackTrace();
                                loginError(-1, e.getMessage());
                            }
                        }
                    });
        } else {
            testIndex(apply_token);
        }

        actionBeanMap = new HashMap<>();
        ActionBean bean1 = new ActionBean();
        bean1.setBaseType(1);
        bean1.setName("申请应用");
        bean1.setaClass(InitiateApplyForActivity.class);
        bean1.setIconId(R.drawable.ic_ybss);
        actionBeanMap.put("申请应用", bean1);

//        dataList.add(bean1);
        ActionBean bean6 = new ActionBean();
        bean6.setBaseType(1);
        bean6.setName("我的申请");
        bean6.setaClass(MyApplyForActivity.class);
        bean6.setIconId(R.drawable.ic_usercenter);

        actionBeanMap.put("我的申请", bean6);
//        dataList.add(bean6);
        ActionBean bean3 = new ActionBean();
        bean3.setBaseType(1);
        bean3.setaClass(ToBeReviewedActivity.class);
        bean3.addParam("operatingType", 2);
        bean3.setName("待审核");
        bean3.setIconId(R.drawable.ic_transit);
        actionBeanMap.put("待审核", bean3);

//        dataList.add(bean3);
        ActionBean bean4 = new ActionBean();
        bean4.setBaseType(1);
        bean4.setaClass(ToBeReviewedActivity.class);
        bean4.addParam("operatingType", 3);
        bean4.setName("审核记录");
        bean4.setIconId(R.drawable.ic_zhyy);
        actionBeanMap.put("审核记录", bean4);

        ActionBean bean8 = new ActionBean();
        bean8.setBaseType(1);
        bean8.setaClass(PersonnelReviewActivity.class);
//        bean8.addParam("operatingType", 3);
        bean8.setName("人员审查");
        bean8.setIconId(R.drawable.ic_zhyy);
        actionBeanMap.put("人员审查", bean8);

//        dataList.add(bean4);
        ActionBean bean5 = new ActionBean();
        bean5.setBaseType(1);
        bean5.setaClass(ApplyProcessActivity.class);
        bean5.setName("申请流程");
        bean5.setIconId(R.drawable.ic_zazdr);
        actionBeanMap.put("申请流程", bean5);
//        dataList.add(bean5);
//        initData(dataList);
    }

    private void setTestUer() {
        //53.1.229.115:8086
        RuanseeApplication.getAppCache().setIpAndPort("20.90.2.2", "80");
        UserData userData = RuanseeApplication.getUserData();
        userData.setUserCode("admin");
        userData.setUserName("陈乐");
        userData.setDeptCode("340012000000");
        userData.setDeptName("省厅");
        userData.setIdCardNum("");
    }

    private void testIndex(String token) {
        Map<String, String> headMap = new HashMap<>(1);
        headMap.put("app-yysq-token", token);
        ApiModel.request(RetrofitService.getBaseInstance().applyGet(BASE_URL + "index", headMap, new HashMap<>()),
                new BaseRequestCallback<JsonObject>() {
                    @Override
                    public void onRequestFailure(String msg) {
                        LogUtils.e(TAG, msg);
                        ToastUtil.centered(getContext(), 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) {
                                ToastUtil.centered(getContext(), TypConversion.getJsonStr(object, "msg"));
                                return;
                            }
                            JSONArray data = TypConversion.getJSONArray(object, "data");
                            if (data == null) {
                                ToastUtil.centered(getContext(), "没有权限");
                                return;
                            }
                            List<BaseBean> dataList = new ArrayList<>();
                            for (int i = 0; i < data.length(); i++) {
                                JSONObject jsonObject = TypConversion.getJSONObject(data, i);
                                if (jsonObject == null) continue;
                                String name = TypConversion.getJsonStr(jsonObject, "name");
                                if (!"Model".equals(name)) {
                                    continue;
                                }
                                JSONArray children = TypConversion.getJSONArray(jsonObject, "children");
                                for (int j = 0; j < children.length(); j++) {
                                    JSONObject jsonObject1 = TypConversion.getJSONObject(children, j);
                                    if (jsonObject1 == null) continue;
                                    JSONObject meta1 = TypConversion.getJSONObject(jsonObject1, "meta");
                                    String title1 = TypConversion.getJsonStr(meta1, "title");
                                    ActionBean bean = actionBeanMap.get(title1);
                                    if (bean == null) {
                                        Log.e(TAG, "没有：" + title1);
                                        continue;
                                    }
                                    dataList.add(bean);
                                }
                            }
                            if (dataList.isEmpty()) {
                                BaseBean baseBean = new BaseBean() {
                                };
                                baseBean.setBaseType(0);
                                baseBean.setBaseMessage("暂无应用");
                                dataList.add(baseBean);
                            }
                            initData(dataList);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void initData(List<BaseBean> dataList) {
        if (applyForMainAdapter == null) {
            applyForMainAdapter = new ApplyForMainAdapter(getContext(), dataList);
            viewBinding.rvAppList.setAdapter(applyForMainAdapter);
            applyForMainAdapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    BaseBean dataItem = applyForMainAdapter.getDataItem(pointer);
                    if (dataItem instanceof ActionBean) {
                        ActionBean bean = (ActionBean) dataItem;
                        if (bean.getaClass() == null) {
                            ToastUtil.centered(getContext(), "正在紧急开发中！");
                            return;
                        }
                        Intent intent = bean.setIntentParam(new Intent(getContext(), bean.getaClass()));
                        startActivity(intent);
                    }
                }
            });
        } else {
            applyForMainAdapter.upData(dataList);
        }
        viewBinding.srlRefresh.finishRefresh();
        viewBinding.srlRefresh.setEnableRefresh(false);
    }
}