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.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

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

import com.google.gson.Gson;
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.DimensionConvert;
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.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.ActivityApplicationGuideBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.AppInfoBean;
import com.ycgis.macall.personalcenter.m.adapterbean.SelectAddressBean;
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.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.callback.SelectReturnCallback;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;
import com.ycgis.macall.personalcenter.v.adapter.ApplicationGuideAdapter;
import com.ycgis.macall.personalcenter.v.custom.SelectAddressPopupWindow;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 应用指南
 */
public class ApplicationGuideActivity extends BaseViewBindActivity<ActivityApplicationGuideBinding> {
    private ApplicationGuideAdapter adapter;
    private int pageNum, pageSize = 10, totalCount;
    private int refreshType = 0;
    private String selectCode;
    private String appName;

    private SelectAddressPopupWindow selectAddressPopupWindow;

    @Override
    protected ActivityApplicationGuideBinding getViewBinding() {
        return ActivityApplicationGuideBinding.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);
        SmartRefreshLayoutHelp.setRefreshAndLoad(getContext(), viewBinding.srlRefresh);
        setViewOnClickListener(viewBinding.btnSelect);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void start() {
        viewBinding.tvSelectName.setText(RuanseeApplication.getUserData().getDepartmentName());
        selectCode = RuanseeApplication.getUserData().getDepartmentCode() + "00000000";
        viewBinding.baseTitle.leftImage.setImageDrawable(getDrawable(R.drawable.back_cliener));
        viewBinding.baseTitle.contentTitle.setText("应用指南");
        setViewOnClickListener(viewBinding.baseTitle.titleleft);
        setViewOnClickListener(viewBinding.btnSelect);
        viewBinding.search.editQuery.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        queryEvent();
        refreshEvent();
        viewBinding.srlRefresh.autoRefresh();
        viewBinding.btnSelect.setClickable(false);
    }

    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();
            }
        });
    }

    private void queryEvent() {
        viewBinding.search.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.search.btnClean);
                    appName = null;
                    return;
                }
                visibleView(viewBinding.search.btnClean);
            }
        });
        viewBinding.search.btnClean.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                viewBinding.search.editQuery.setText("");
                goneView(viewBinding.search.btnClean);
                appName = null;
            }
        });
        viewBinding.search.editQuery.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    appName = getEditText(viewBinding.search.editQuery);
                    viewBinding.srlRefresh.autoRefresh();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected void bindViewClick(View v) {
        if (v.getId() == R.id.titleleft) {
            finish();
        } else if (v.getId() == R.id.btn_select) {
            if (RuanseeApplication.getUserData().getDepartmentCode().equals("3400")) {
                showSelectAll();
            } else {
                if (selectCode.startsWith("3400")) {
                    viewBinding.tvSelectName.setText(RuanseeApplication.getUserData().getDepartmentName());
                    selectCode = RuanseeApplication.getUserData().getDepartmentCode() + "00000000";
                } else {
                    selectCode = "340000000000";
                    viewBinding.tvSelectName.setText("省厅");
                }
                viewBinding.srlRefresh.autoRefresh();
            }
            viewBinding.btnSelect.setClickable(false);
        }
    }

    private void showSelectAll() {
        showSelectAll(getActivity(), viewBinding.baseTitle.contentTitle, new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                yanshishezhi();
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
            }
        }, new SelectReturnCallback<SelectAddressBean>() {
            @Override
            public void returnMsg(SelectAddressBean message) {
                selectCode = message.getCode() + "00000000";
                viewBinding.tvSelectName.setText(message.getName());
                viewBinding.srlRefresh.autoRefresh();
            }
        });
    }

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

    private void getAppData() {
//        ApiModel.request(RetrofitService.getBaseInstance().applicationPage(null, selectCode, pageNum, pageSize, appName, null),
        ApiModel.request(RetrofitService.getBaseInstance().applicationCzsc(appName, selectCode, pageNum, pageSize),
                new BaseRequestCallback<BaseRequestModel<PagingModel<AppInfoBean>>>() {
                    @Override
                    public void onRequestFailure(String msg) {
                        if (refreshType == 1) {
                            List<AppInfoBean> beanList = new ArrayList<>();
                            AppInfoBean bean = new AppInfoBean();
                            bean.setBaseType(-1);
                            bean.setBaseMessage(msg);
                            beanList.add(bean);
                            initAppData(beanList);
                            viewBinding.srlRefresh.finishRefresh();
                        } else if (refreshType == 2) {
                            viewBinding.srlRefresh.finishLoadMore();
                        }
                        refreshType = 0;
                        ToastUtil.centered(getContext(), msg);
                        yanshishezhi();
                    }

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

    private void initAppData(List<AppInfoBean> dataList) {
        if (adapter == null) {
            adapter = new ApplicationGuideAdapter(getContext(), dataList);
            viewBinding.rvAppList.setAdapter(adapter);
            adapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    if (adapter.getItemViewType(pointer) == 1) {
                        AppInfoBean dataItem = adapter.getDataItem(pointer);
                        Intent intent = new Intent(getContext(), AppGuideDetailsActivity.class);
                        intent.putExtra("appJson", new Gson().toJson(dataItem));
                        startActivity(intent);
                    }
                }
            });
        } else {
            adapter.upData(dataList);
        }
    }

    private void yanshishezhi() {
        Observable.timer(800, TimeUnit.MILLISECONDS)
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NotNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NotNull Long aLong) {

                    }

                    @Override
                    public void onError(@NotNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        viewBinding.btnSelect.setClickable(true);
                    }
                });
    }

    public void showSelectAll(Activity activity, View view, PopupWindow.OnDismissListener dismissListener, SelectReturnCallback<SelectAddressBean> selectReturnCallback) {
        if (selectAddressPopupWindow == null) {
            int i = getResources().getDisplayMetrics().heightPixels - DimensionConvert.dip2px(activity, 88) - DimensionConvert.dip2px(activity, 118);
            selectAddressPopupWindow = new SelectAddressPopupWindow(activity, selectReturnCallback, LinearLayout.LayoutParams.MATCH_PARENT,
                    i);
        }
        //监听窗口的焦点事件，点击窗口外面则取消显示
        selectAddressPopupWindow.getContentView().setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                selectAddressPopupWindow.dismiss();
            }
        });
        selectAddressPopupWindow.setOnDismissListener(dismissListener);
        //popWindow消失监听方法
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = 0.7f;
        activity.getWindow().setAttributes(lp);
        //设置默认获取焦点
        selectAddressPopupWindow.setFocusable(true);
        int xOffset = 10;
        //以某个控件的x和y的偏移量位置开始显示窗口
        selectAddressPopupWindow.showAsDropDown(view, xOffset, 30);
        //如果窗口存在，则更新
        selectAddressPopupWindow.update();
    }
}