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


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

import androidx.annotation.NonNull;
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.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.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.ActivitySelectAppBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.AppInfoBean;
import com.ycgis.macall.personalcenter.m.adapterbean.BaseBean;
import com.ycgis.macall.personalcenter.m.adapterbean.SelectRoleBean;
import com.ycgis.macall.personalcenter.m.requestbean.AppInfoModel;
import com.ycgis.macall.personalcenter.m.requestbean.BaseRequestModel;
import com.ycgis.macall.personalcenter.m.requestbean.PagingModel;
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.SelectAppAdapter;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;

import java.util.ArrayList;
import java.util.List;

public class SelectAppActivity extends BaseViewBindActivity<ActivitySelectAppBinding> {
    private int counts,pageNum,pageSize=20;
    private String searchWord;
    private SelectAppAdapter appAdapter;
    private String appId,appName;

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

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

    @Override
    protected void init() {
        viewBinding.selappRvList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        viewBinding.selappRvList.addItemDecoration(new MyDividerItemDecoration(getContext(),LinearLayoutManager.VERTICAL));
        SmartRefreshLayoutHelp.setRefreshAndLoad(getContext(),viewBinding.selappSrlRefresh);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void start() {
        viewBinding.selappTitle.contentTitle.setText("选择应用");
        viewBinding.selappTitle.leftImage.setImageDrawable(getDrawable(R.drawable.back_cliener));
        viewBinding.selappTitle.titleleft.setOnClickListener(v -> finish());
        viewBinding.selappSearch.editQuery.setHint("输入应用名称进行搜索");
        viewBinding.selappTitle.rightText.setText("确定");
        viewBinding.selappTitle.titleright.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                if (StringUtil.isNullOrEmptyAll(appId,appName)){
                    ToastUtil.centered(getContext(),"请先选择应用！");
                    return;
                }
                Intent i = new Intent();
                i.putExtra("appId",appId);
                i.putExtra("appName",appName);
                setResult(Activity.RESULT_OK,i);
                finish();
            }
        });
        viewBinding.selappSearch.editQuery.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        viewBinding.selappSearch.btnClean.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                viewBinding.selappSearch.editQuery.setText("");
            }
        });

        viewBinding.selappSearch.editQuery.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                searchWord = getEditText(viewBinding.selappSearch.editQuery);
                viewBinding.selappSrlRefresh.autoRefresh();
                return true;
            }
            return false;
        });

        viewBinding.selappSearch.editQuery.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s == null || StringUtil.isNullOrEmpty(s.toString())) {
                    goneView(viewBinding.selappSearch.btnClean);
                    return;
                }
                visibleView(viewBinding.selappSearch.btnClean);
            }
        });
        viewBinding.selappSrlRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                if (pageSize*pageNum>=counts){
                    viewBinding.selappSrlRefresh.finishLoadMoreWithNoMoreData();
                    return;
                }
                pageNum++;
                searchApp();
            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                viewBinding.selappSrlRefresh.resetNoMoreData();
                pageNum=1;
                searchApp();
            }
        });
        viewBinding.selappSrlRefresh.autoRefresh();
    }

    private AppInfoBean error(int type,String msg){
        AppInfoBean b = new AppInfoBean();
        b.setBaseType(type);
        b.setBaseMessage(msg);
        return b;
    }

    private void searchApp(){
        ApiModel.request(RetrofitService.getBaseInstance().selectAppList( searchWord, pageNum, pageSize),
                new BaseRequestCallback<BaseRequestModel<PagingModel<AppInfoBean>>>() {
            @Override
            public void onRequestFailure(String msg) {
                LogUtils.e(TAG,msg);
                if (viewBinding.selappSrlRefresh.isRefreshing()){
                    viewBinding.selappSrlRefresh.finishRefresh();
                    AppInfoBean error = error(-1, msg);
                    List<AppInfoBean> items = new ArrayList<>();
                    items.add(error);
                    initData(items);
                }
                if (viewBinding.selappSrlRefresh.isLoading()){
                    viewBinding.selappSrlRefresh.finishLoadMore();
                    ToastUtil.centered(getContext(),msg);
                }
            }

            @Override
            public void onRequestSuccess(BaseRequestModel<PagingModel<AppInfoBean>> result) {
                LogUtils.w(TAG,result.toString());
                if (result.getCode() == 20041){
                    PagingModel data = result.getData();
                    counts = data.getCounts();
                    List<AppInfoBean> items = data.getItems();
                    for (AppInfoBean b : items) {
                        b.setBaseType(1);
                    }
                    if (viewBinding.selappSrlRefresh.isRefreshing()){
                        viewBinding.selappSrlRefresh.finishRefresh();
                        if (items.isEmpty()){
                           items.add(error(0,"暂无应用"));
                        }else {
                            if (pageSize*pageNum>=counts){
                                viewBinding.selappSrlRefresh.finishLoadMoreWithNoMoreData();
                            }
                        }
                        initData(items);
                    }
                    if (viewBinding.selappSrlRefresh.isLoading()){
                        viewBinding.selappSrlRefresh.finishLoadMore();
                        if (!items.isEmpty()){
                            appAdapter.addData(items);
                            if (pageSize*pageNum>=counts){
                                viewBinding.selappSrlRefresh.finishLoadMoreWithNoMoreData();
                            }
                        }
                    }
                }else {
                    if (viewBinding.selappSrlRefresh.isRefreshing()){
                        viewBinding.selappSrlRefresh.finishRefresh();
                        AppInfoBean error = error(-1, result.getMsg());
                        List<AppInfoBean> items = new ArrayList<>();
                        items.add(error);
                        initData(items);
                    }
                    if (viewBinding.selappSrlRefresh.isLoading()){
                        viewBinding.selappSrlRefresh.finishLoadMore();
                        ToastUtil.centered(getContext(),result.getMsg());
                    }
                }
            }
        });
    }

    private void initData(List<AppInfoBean> items) {
        if (appAdapter == null){
            appAdapter = new SelectAppAdapter(getContext(),items);
            viewBinding.selappRvList.setAdapter(appAdapter);
            appAdapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    AppInfoBean dataItem = appAdapter.getDataItem(pointer);
                    if (dataItem.getBaseType()!=1) return;
                    if (dataItem.isSelect()){
                        dataItem.setSelect(false);
                        appAdapter.notifyItemChanged(pointer,5);
                        appId = "";
                        appName = "";
                        return;
                    }
                    List<AppInfoBean> data = appAdapter.getData();
                    for (int i = 0; i <data.size(); i++) {
                        AppInfoBean appInfoBean = data.get(i);
                        if (appInfoBean.isSelect()){
                            appInfoBean.setSelect(false);
                            appAdapter.notifyItemChanged(i,5);
                        }
                    }
                    appId = String.valueOf(dataItem.getId());
                    appName = dataItem.getName();
                    dataItem.setSelect(true);
                    appAdapter.notifyItemChanged(pointer,5);

                }
            });
        }else {
            appAdapter.upData(items);
        }
    }

}