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

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.EditorInfo;

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

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
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.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.ActivitySelectSystemBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.ApplyAppBean;
import com.ycgis.macall.personalcenter.m.adapterbean.BaseBean;
import com.ycgis.macall.personalcenter.m.adapterbean.SelectRoleBean;
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.CommonCompositeManage;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;
import com.ycgis.macall.personalcenter.v.adapter.SelectSystemAdapter;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 选择应用和角色
 */
public class SelectSystemActivity extends BaseViewBindActivity<ActivitySelectSystemBinding> {
    private SelectSystemAdapter appAdapter;
    private String selectData;
    private int pageNum, pageSize = 10, totalCount;
    private int refreshType = 0;

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

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

    @Override
    protected void init() {
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        viewBinding.rvAppList.setLayoutManager(manager);
        MyDividerItemDecoration myDividerItemDecoration = new MyDividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL, 10);
        myDividerItemDecoration.setOnMarginListener(new MyDividerItemDecoration.OnMarginListener() {
            @Override
            public int onLeft(int itemViewType, int Pointer) {
                if (itemViewType == 1) {
                    return 15;
                } else {
                    return 0;
                }
            }
        });
        viewBinding.rvAppList.addItemDecoration(new MyDividerItemDecoration(getContext(),LinearLayoutManager.VERTICAL,45));
        viewBinding.rvAppList.addItemDecoration(myDividerItemDecoration);
//        viewBinding.search.editQuery.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        SmartRefreshLayoutHelp.setPullDownToRefresh(getContext(), viewBinding.srlRefresh);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {
        selectData = getIntent().getStringExtra("data");
    }

    @Override
    protected void start() {
//        viewBinding.leftImage.setImageDrawable(getDrawables(R.drawable.back_cliener));
        viewBinding.rightText.setText("确定");
//        goneView(viewBinding.search.getRoot());
        viewBinding.contentTitle.setText(R.string.applyTitleSelectPermissions1);
        setViewOnClickListener(viewBinding.titleright);
        setViewOnClickListener(viewBinding.titleleft);
//        queryEvent();
        refreshEvent();
        viewBinding.srlRefresh.autoRefresh();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CommonCompositeManage.getInstance().unDisposable("getSqyyList");
    }


    private void refreshEvent() {
        viewBinding.srlRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                pageNum = 1;
                refreshType = 1;
                viewBinding.srlRefresh.resetNoMoreData();
                getAppData();
            }
        });
        viewBinding.srlRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                if (pageNum * pageSize >= totalCount) {
                    viewBinding.srlRefresh.finishLoadMoreWithNoMoreData();
                    return;
                }
                pageNum++;
                refreshType = 2;
                getAppData();
            }
        });
    }

    @Override
    protected void bindViewClick(View v) {
        if (v.getId() == R.id.titleleft) {
            finish();
        } else if (v.getId() == R.id.titleright) {
            submit();
        }
    }

    private void submit() {
        if (selectContent == null) {
            return;
        }

        if (StringUtil.isContainEmpty(selectContent)) {
            ToastUtil.centered(getContext(), "请选择权限");
            return;
        }
        Intent intent = new Intent();
//        intent.putExtra("roleId", String.valueOf(bean1.getId()));
//        intent.putExtra("selectData", new Gson().toJson(param));
        intent.putExtra("selectContent", selectContent);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }
    /*private void submit() {
        if (appAdapter == null) {
            return;
        }
        if (appAdapter.getData() == null || appAdapter.getItemCount() <= 0) return;
        Map<String, String[]> param = new HashMap<>();
        for (BaseBean bean : appAdapter.getData()) {
            if (bean instanceof SelectRoleBean) {
                SelectRoleBean bean1 = (SelectRoleBean) bean;
                String[] strings = {bean1.getAppName(), bean1.getName()};
                param.put(bean1.getAppId(), strings);
            }
        }
        if (param.isEmpty()) {
            ToastUtil.centered(getContext(), "请选择要申请的应用和角色");
            return;
        }
        Intent intent = new Intent();
//        intent.putExtra("roleId", String.valueOf(bean1.getId()));
        intent.putExtra("selectData", new Gson().toJson(param));
        setResult(Activity.RESULT_OK, intent);
        finish();
    }*/

    private void getAppData() {
        Map<String, String> headMap = new HashMap<>(1);
        headMap.put("app-yysq-token", RuanseeApplication.getAppCache().getApply_token());
        ApiModel.request(RetrofitService.getBaseInstance().applyGet(ApplyForMainActivity.BASE_URL + "role/alllist", headMap, new HashMap<>()),
                new BaseRequestCallback<JsonObject>() {
                    @Override
                    public void onRequestFailure(String msg) {
                        viewBinding.srlRefresh.finishRefresh();
                        LogUtils.e(TAG, msg);
                        List<BaseBean> dataList = new ArrayList<>();
                        BaseBean baseBean = new BaseBean() {
                        };
                        baseBean.setBaseType(-1);
                        baseBean.setBaseMessage(msg);
                        dataList.add(baseBean);
                        initAppData(dataList);
                    }

                    @Override
                    public void onRequestSuccess(JsonObject result) {
                        LogUtils.w(TAG, result.toString());
                        viewBinding.srlRefresh.finishRefresh();
                        try {
                            ApplyAppBean applyAppBean = new Gson().fromJson(result.toString(), ApplyAppBean.class);
                            if (!applyAppBean.isSuccess()) {
                                List<BaseBean> dataList = new ArrayList<>();
                                BaseBean baseBean = new BaseBean() {
                                };
                                baseBean.setBaseType(-1);
                                baseBean.setBaseMessage(applyAppBean.getMsg());
                                dataList.add(baseBean);
                                initAppData(dataList);
                                return;
                            }
                            List<ApplyAppBean.DataBean2> data = applyAppBean.getData();
                            handlerData2(data);
                        } catch (Exception e) {
                            e.printStackTrace();
                            List<BaseBean> dataList = new ArrayList<>();
                            BaseBean baseBean = new BaseBean() {
                            };
                            baseBean.setBaseType(-1);
                            baseBean.setBaseMessage(e.getMessage());
                            dataList.add(baseBean);
                            initAppData(dataList);
                        }
                    }
                });
    }

    private void handlerData2(List<ApplyAppBean.DataBean2> data) {
        List<BaseBean> dataList = new ArrayList<>();
        if (data == null || data.isEmpty()) {
            BaseBean baseBean = new BaseBean() {
            };
            baseBean.setBaseType(0);
            baseBean.setBaseMessage("暂无应用");
            dataList.add(baseBean);
        } else {
            for (ApplyAppBean.DataBean2 b : data) {
                b.setBaseType(4);
                dataList.add(b);
            }
        }
        initAppData(dataList);
    }


    private void handlerData(List<ApplyAppBean.DataBean> data) {
        Map<String, String[]> stringMap = null;
        if (StringUtil.hasContent(selectData)) {
            Type type = new TypeToken<Map<String, String[]>>() {
            }.getType();
            stringMap = new Gson().fromJson(StringUtil.toJsonParaphrase(selectData), type);
        }
        List<BaseBean> dataList = new ArrayList<>();
        if (data == null || data.isEmpty()) {
            BaseBean baseBean = new BaseBean() {
            };
            baseBean.setBaseType(0);
            baseBean.setBaseMessage("暂无应用");
            dataList.add(baseBean);
        } else {
            for (ApplyAppBean.DataBean b : data) {
                b.setBaseType(1);
                dataList.add(b);
            }
            if (stringMap != null) {
                Set<String> strings = stringMap.keySet();
                for (String key : strings) {
                    String[] strings1 = stringMap.get(key);
                    for (int i = 0; i < dataList.size(); i++) {
                        BaseBean baseBean = dataList.get(i);
                        if (baseBean instanceof ApplyAppBean.DataBean) {
                            ApplyAppBean.DataBean bean = (ApplyAppBean.DataBean) baseBean;
                            int selectId = TypConversion.strToInt(key);
                            if (bean.getId() == selectId) {
                                bean.setSelect(true);
                                SelectRoleBean bean1 = new SelectRoleBean();
                                bean1.setBaseType(3);
                                bean1.setName(strings1[1]);
                                bean1.setAppId(key);
                                bean1.setAppName(strings1[0]);
                                dataList.add(i + 1, bean1);
                            }
                        }
                    }
                }
            }
        }
        initAppData(dataList);
    }

    private void showItemSelectDialog(List<Object> list) {
        OptionsPickerView build = new OptionsPickerBuilder(getContext(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                Object o = list.get(options1);
                BaseBean dataItem = appAdapter.getDataItem(selectPointer);
                if (dataItem instanceof ApplyAppBean.DataBean) {
                    ApplyAppBean.DataBean bean = (ApplyAppBean.DataBean) dataItem;
                    if (selectPointer < appAdapter.getItemCount() - 1) {
                        BaseBean dataItem1 = appAdapter.getDataItem(selectPointer + 1);
                        if (dataItem1 instanceof SelectRoleBean) {
                            SelectRoleBean bean1 = (SelectRoleBean) dataItem1;
                            bean1.setName(o.toString());
                            bean1.setAppId(String.valueOf(bean.getId()));
                            bean1.setAppName(bean.getName());
                            appAdapter.notifyItemChanged(selectPointer + 1, 6);
                        } else {
                            SelectRoleBean bean1 = new SelectRoleBean();
                            bean1.setBaseType(3);
                            bean1.setName(o.toString());
                            bean1.setAppId(String.valueOf(bean.getId()));
                            bean1.setAppName(bean.getName());
                            appAdapter.addItem(selectPointer + 1, bean1);
                        }
                    } else if (selectPointer == appAdapter.getItemCount() - 1) {
                        SelectRoleBean bean1 = new SelectRoleBean();
                        bean1.setBaseType(3);
                        bean1.setName(o.toString());
                        bean1.setAppId(String.valueOf(bean.getId()));
                        bean1.setAppName(bean.getName());
                        appAdapter.addItem(selectPointer + 1, bean1);

                    }
                    bean.setSelect(true);
                    appAdapter.notifyItemChanged(selectPointer, 1);
                }
            }
        }).setCancelText("取消")
                .setCancelColor(getColors(R.color.colorGreen6))
                .setSubmitText("确定")
                .setSubmitColor(getColors(R.color.colorBluen7))
                .setContentTextSize(16)
                .setTitleText("请选择角色")
                .setTitleSize(16)
                .setTitleColor(getColors(R.color.colorBluen8))
                .setSubCalSize(14)
                .build();
        build.setPicker(list);
        build.show();
    }

    private int selectPointer = 0;

    private String[] selectContent = new String[2];

    //
    private void initAppData(List<BaseBean> dataList) {
        if (appAdapter == null) {
            appAdapter = new SelectSystemAdapter(getContext(), dataList);
            viewBinding.rvAppList.setAdapter(appAdapter);
            appAdapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    BaseBean item = appAdapter.getDataItem(pointer);
                    if (item instanceof ApplyAppBean.DataBean2) {
                        ApplyAppBean.DataBean2 dataItem = (ApplyAppBean.DataBean2) item;
                        if (dataItem.isSelect()) {
                            dataItem.setSelect(false);
                            appAdapter.notifyItemChanged(pointer, 1);
                            selectContent[0] = "";
                            selectContent[1] = "";
                            return;
                        }
                        List<BaseBean> data = appAdapter.getData();
                        int lastIndex = -1;
                        for (int i = 0; i < data.size(); i++) {
                            BaseBean baseBean = data.get(i);
                            if (baseBean instanceof ApplyAppBean.DataBean2) {
                                ApplyAppBean.DataBean2 d = (ApplyAppBean.DataBean2) baseBean;
                                if (d.isSelect()) {
                                    lastIndex = i;
                                    d.setSelect(false);
                                    break;
                                }
                            }
                        }
                        dataItem = (ApplyAppBean.DataBean2) item;
                        dataItem.setSelect(true);
                        appAdapter.notifyItemChanged(pointer, 1);
                        selectContent[0] = String.valueOf(dataItem.getId());
                        selectContent[1] = dataItem.getRoleName();
                        if (lastIndex == -1)return;
                        appAdapter.notifyItemChanged(lastIndex, 1);
                        return;
                    }

                    if (item instanceof ApplyAppBean.DataBean) {
                        ApplyAppBean.DataBean dataItem = (ApplyAppBean.DataBean) item;
                        if (dataItem.getBaseType() != 1) return;
                        if (dataItem.isSelect()) {
                            dataItem.setSelect(false);
                            appAdapter.notifyItemChanged(pointer, 1);
                            List<BaseBean> data = appAdapter.getData();
                            for (int i = 0; i < data.size(); i++) {
                                BaseBean baseBean = data.get(i);
                                if (baseBean instanceof SelectRoleBean) {
                                    SelectRoleBean bean = (SelectRoleBean) baseBean;
                                    if (bean.getAppId().equals(String.valueOf(dataItem.getId()))) {
                                        data.remove(i);
                                        appAdapter.notifyItemRemoved(i);
                                        return;
                                    }
                                }
                            }
                            return;
                        }
                        List<ApplyAppBean.DataBean.RolesBean> roles = dataItem.getRoles();
                        if (roles != null) {
                            List<Object> list = new ArrayList<>();
                            list.addAll(roles);
                            selectPointer = pointer;
                            showItemSelectDialog(list);
                        }
                    }
                    if (item instanceof SelectRoleBean) {
                        SelectRoleBean dataItem = (SelectRoleBean) item;
                        if (dataItem.getBaseType() != 2) return;
                        int sygxz = -1;
                        for (int i = 0; i < appAdapter.getItemCount(); i++) {
                            BaseBean dataItem1 = appAdapter.getDataItem(i);
                            if (dataItem1 instanceof SelectRoleBean) {
                                SelectRoleBean bean = (SelectRoleBean) dataItem1;
                                if (bean.isSelect()) {
                                    sygxz = i;
                                    bean.setSelect(false);
                                    break;
                                }
                            }
                        }
                        if (sygxz != -1) {
                            appAdapter.notifyItemChanged(sygxz, 1);
                        }
                        dataItem.setSelect(true);
                        appAdapter.notifyItemChanged(pointer, 1);
                    }
                }
            });
        } else {
            appAdapter.upData(dataList);
        }
    }
}