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

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
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.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

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.OnRefreshLoadMoreListener;

import com.ycgis.macall.personalcenter.R;

import com.ycgis.macall.personalcenter.databinding.ActivityWorkbenchCenterBinding;

import com.ycgis.macall.personalcenter.m.adapterbean.AppInfoBean;
import com.ycgis.macall.personalcenter.m.adapterbean.SelectAddressBean;
import com.ycgis.macall.personalcenter.m.enumbean.AppOpenType;
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.m.requestbean.WorkbenchModel;
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.util.ToThirdPartyAppUtils;
import com.ycgis.macall.personalcenter.v.adapter.WorkbenchCenterAdapter;
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 WorkbenchCenterActivity extends BaseViewBindActivity<ActivityWorkbenchCenterBinding> {
    private int total, pageNum, pageSize = 30;
    private String searchWord, selectCode;
    private WorkbenchCenterAdapter appListAdapter;
    private ToThirdPartyAppUtils appUtils;
    private boolean isSt = false;
    private List<String> commonAppName;
    private SelectAddressPopupWindow selectAddressPopupWindow;

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

    @Override
    protected void init() {
        SmartRefreshLayoutHelp.setRefreshAndLoad(getContext(), viewBinding.appCenterSrlRefresh);
//        viewBinding.appCenterRvList.addItemDecoration(new GridDividerItemDecoration(getContext()));
        setViewOnClickListener(viewBinding.btnSwitchSs);
        setViewOnClickListener(viewBinding.btnSwitchSsV);
    }

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

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void start() {
        viewBinding.leftImage.setImageDrawable(getDrawables(R.drawable.back_cliener));
        viewBinding.leftImage.setOnClickListener(v -> finish());
        viewBinding.appCenterSrlRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                if (total <= pageSize * pageNum) {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                    return;
                }
                pageNum++;
                getAppData();
            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                refreshLayout.resetNoMoreData();
                pageNum = 1;
                getAppData();
            }
        });
        viewBinding.search.editQuery.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        queryEvent();
        selectCode = RuanseeApplication.getUserData().getDepartmentCode() + "00000000";
        if ("3400".equals(RuanseeApplication.getUserData().getDepartmentCode())) {
            viewBinding.btnSwitchSs.setText("省厅");
        } else {
            viewBinding.btnSwitchSs.setText(RuanseeApplication.getUserData().getDepartmentName());
        }
        selectCode = RuanseeApplication.getUserData().getDepartmentCode() + "00000000";
        viewBinding.appCenterSrlRefresh.autoRefresh();
    }

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

    @Override
    protected void onPause() {
        super.onPause();
        baseDismissDialog();
    }


    @Override
    protected void bindViewClick(View v) {
        switch (v.getId()) {
            case R.id.btn_switch_ss:
            case R.id.btn_switch_ss_v:
                viewBinding.btnSwitchSs.setClickable(false);
                viewBinding.btnSwitchSsV.setClickable(false);
                if (RuanseeApplication.getUserData().getDepartmentCode().equals("3400")) {
                    showSelectAll();
                } else {
                    if (selectCode.startsWith("3400")) {
                        viewBinding.btnSwitchSs.setText(RuanseeApplication.getUserData().getDepartmentName());
                        selectCode = RuanseeApplication.getUserData().getDepartmentCode() + "00000000";
                    } else {
                        selectCode = "340000000000";
                        viewBinding.btnSwitchSs.setText("省厅");
                    }
                    viewBinding.appCenterSrlRefresh.autoRefresh();
                }
                break;
        }
    }

    private void showSelectAll() {
        showSelectAll(getActivity(), viewBinding.btnSwitchSs, new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                yanshishezhi();
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
            }
        }, message -> {
            selectCode = message.getCode() + "00000000";
            viewBinding.btnSwitchSs.setText(message.getName());
            viewBinding.appCenterSrlRefresh.autoRefresh();
        });
    }

    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.btnSwitchSs.setClickable(true);
                        viewBinding.btnSwitchSsV.setClickable(true);
                    }
                });
    }

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

    private void initError(int type, String msg) {
        if (viewBinding.appCenterSrlRefresh.isRefreshing()) {
            viewBinding.appCenterSrlRefresh.finishRefresh();
            AppInfoBean error = error(type, msg);
            List<AppInfoBean> items = new ArrayList<>();
            items.add(error);
            initData(items);
        }
        if (viewBinding.appCenterSrlRefresh.isLoading()) {
            viewBinding.appCenterSrlRefresh.finishLoadMore();
            ToastUtil.centered(getContext(), msg);
        }
    }

    /**
     * 选择省厅 地市
     *
     * @param activity             当前Activity
     * @param view                 显示View
     * @param dismissListener      取消监听
     * @param selectReturnCallback 选择监听
     */
    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();
    }

    private void getAppData() {
        ApiModel.request("getAppListData", RetrofitService.getBaseInstance().applicationPage(selectCode, pageNum, pageSize, searchWord, 0),
                new BaseRequestCallback<BaseRequestModel<PagingModel<AppInfoBean>>>() {
                    @Override
                    public void onRequestFailure(String msg) {
                        LogUtils.e(TAG, msg);
                        initError(-1, msg);
                    }

                    @Override
                    public void onRequestSuccess(BaseRequestModel<PagingModel<AppInfoBean>> result) {
                        LogUtils.w(TAG, result.toString());
                        if (result.getCode() == 20041) {
                            PagingModel<AppInfoBean> data = result.getData();
                            total = data.getCounts();
                            List<AppInfoBean> items = data.getItems();
                            if (items.isEmpty()) {
                                initError(0, "暂无应用");
                                return;
                            }
                            for (int i = 0; i < items.size(); i++) {
                                items.get(i).setBaseType(1);
                            }
                            if (viewBinding.appCenterSrlRefresh.isRefreshing()) {
                                viewBinding.appCenterSrlRefresh.finishRefresh();
                                if (pageSize * pageNum >= total) {
                                    viewBinding.appCenterSrlRefresh.finishLoadMoreWithNoMoreData();
                                }
                                initData(items);
                            }
                            if (viewBinding.appCenterSrlRefresh.isLoading()) {
                                viewBinding.appCenterSrlRefresh.finishLoadMore();
                                appListAdapter.addData(items);
                                if (pageSize * pageNum >= total) {
                                    viewBinding.appCenterSrlRefresh.finishLoadMoreWithNoMoreData();
                                }
                            }
                        } else {
                            if (result.getCode() == 20040) {
                                total = 0;
                                initError(0, "暂无应用");
                                return;
                            }
                            initError(-1, result.getMsg());
                        }
                    }
                });

    }

    private void initData(List<AppInfoBean> items) {
        if (items.size() == 1) {
            int baseType = items.get(0).getBaseType();
            if (baseType != 1) {
                viewBinding.appCenterRvList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
            }else {
                viewBinding.appCenterRvList.setLayoutManager(new GridLayoutManager(getContext(), 4));
            }
        }else {
            viewBinding.appCenterRvList.setLayoutManager(new GridLayoutManager(getContext(), 4));
        }
        if (appListAdapter == null) {
            appListAdapter = new WorkbenchCenterAdapter(getContext(), items);
            viewBinding.appCenterRvList.setAdapter(appListAdapter);
            appListAdapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    AppInfoBean dataItem = appListAdapter.getDataItem(pointer);
                    if (appUtils == null) {
                        appUtils = new ToThirdPartyAppUtils(getContext());
                    }
                    baseShowDialog("正在打开应用，请稍后。。。");
                    appUtils.skipApp(dataItem, AppOpenType.LOGIN);
                }
            });
        } else {
            appListAdapter.upData(items);
        }

    }

}