package com.tenlionsoft.oamodule.activity.supervise;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.hjq.toast.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.tenlionsoft.baselib.constant.PathConfig;
import com.tenlionsoft.baselib.core.retrofit_net.RetrofitManager;
import com.tenlionsoft.baselib.core.retrofit_net.conver.RxTransformer;
import com.tenlionsoft.baselib.core.widget.base.BaseActivity;
import com.tenlionsoft.baselib.utils.ExceptionHandler;
import com.tenlionsoft.baselib.utils.UserLgUtils;
import com.tenlionsoft.oamodule.R;
import com.tenlionsoft.oamodule.R2;
import com.tenlionsoft.oamodule.adapter.RelevanceOptionsAdapter;
import com.tenlionsoft.oamodule.adapter.SelectedRelevanceOptionsAdapter;
import com.tenlionsoft.oamodule.beans.SuperviseRelevanceOptionsListBean;
import com.tenlionsoft.oamodule.net.OAApi;

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

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 作者: Adam
 * 日期: 2022年04月18日16:17:39
 * 邮箱: itgaojian@163.com
 * 描述: 选择督办关联事项
 */
@Route(path = PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_RELEVANCE_OPTIONS)
public class SelRelevanceOptionActivity extends BaseActivity {

    @BindView(R2.id.rlv_choose_items)
    RecyclerView mRlvChooseItems;
    @BindView(R2.id.rlv_content)
    RecyclerView mRlvContent;
    @BindView(R2.id.pb_loading)
    ProgressBar mPbLoading;
    @BindView(R2.id.iv_empty_data)
    ImageView mIvEmptyData;
    @BindView(R2.id.tv_error_hint)
    TextView mTvErrorHint;
    @BindView(R2.id.srl_content)
    SmartRefreshLayout mSrlContent;
    private String mId;
    private boolean mIsSingle;
    private int mCurrentPage = 1;
    private List<SuperviseRelevanceOptionsListBean.RowsBean> mDatas;
    private RelevanceOptionsAdapter mAdapter;
    private List<SuperviseRelevanceOptionsListBean.RowsBean> mSelectedBeans;
    private SelectedRelevanceOptionsAdapter mSelectedRelevanceOptionsAdapter;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_sel_relevance_option;
    }

    @Override
    public void initData() {
        ButterKnife.bind(this);
        refreshView(STATE_LOAD_SUCCESS);
        mTvBaseTitle.setText("关联事项");
        mTvPublish.setVisibility(View.VISIBLE);
        mTvPublish.setText("确定");
        mTvPublish.setOnClickListener(v -> doConfirm());
        mId = getIntent().getStringExtra("id");
        mIsSingle = getIntent().getBooleanExtra("isSingle", true);
        mSrlContent.setOnLoadMoreListener(v -> doLoadMore());
        mSrlContent.setOnRefreshListener(v -> doRefresh());
        initViews();
        if (TextUtils.isEmpty(mId)) {
            ToastUtils.show("数据有误");
            finish();
        } else {
            getOptionsById(mCurrentPage);
        }
    }

    private void doLoadMore() {
        getOptionsById(mCurrentPage);
    }

    private void doRefresh() {
        mDatas.clear();
        getOptionsById(1);
    }

    /**
     * TODO 确认选择
     */
    private void doConfirm() {
        if (mSelectedBeans != null && mSelectedBeans.size() > 0) {
            if (mIsSingle) {
                SuperviseRelevanceOptionsListBean.RowsBean bean = mSelectedBeans.get(0);
                Intent intent = new Intent();
                intent.putExtra("bean", bean);
                setResult(RESULT_OK, intent);
                finish();
            } else {
                String ids = "";
                String names = "";
                for (int i = 0; i < mSelectedBeans.size(); i++) {
                    SuperviseRelevanceOptionsListBean.RowsBean bean = mSelectedBeans.get(i);
                    ids += bean.getDataId() + ",";
                    names += bean.getDataTitle() + ",";
                }
                ids = ids.substring(0, ids.length() - 1);
                names = names.substring(0, names.length() - 1);
                Intent intent = new Intent();
                intent.putExtra("name", names);
                intent.putExtra("id", ids);
                setResult(RESULT_OK, intent);
                finish();
            }
        } else {
            ToastUtils.show("请选择事项");
        }
    }

    private void initViews() {
        mDatas = new ArrayList<>();
        mAdapter = new RelevanceOptionsAdapter(mActivity, mDatas);
        mRlvContent.setLayoutManager(new LinearLayoutManager(mActivity));
        mRlvContent.setAdapter(mAdapter);

        mAdapter.addOnItemCheckChange((bean, isCheck, pos) -> {
            if (isCheck) {
                if (mIsSingle) {
                    mAdapter.mSelBeans.clear();
                    mAdapter.mSelBeans.add(bean);
                } else {
                    mAdapter.mSelBeans.add(bean);
                }
            } else {
                mAdapter.mSelBeans.remove(bean);
            }
            bean.setCheck(isCheck);
            if (isCheck) {
                if (mIsSingle) {
                    for (int i = 0; i < mAdapter.getData().size(); i++) {
                        if (mAdapter.getData().get(i) != null) {
                            SuperviseRelevanceOptionsListBean.RowsBean bean1 = mAdapter.getData().get(i);
                            if (bean1.getDataId().equals(bean.getDataId())) {
                                continue;
                            } else {
                                bean1.setCheck(false);
                            }
                        }
                    }
                }
            }
            mAdapter.notifyDataSetChanged();
            if (isCheck) {
                if (mIsSingle) {
                    mSelectedBeans.clear();
                    mSelectedBeans.add(bean);
                } else {
                    //TODO 去重
                    mSelectedBeans.add(bean);
                }
            } else {
                Iterator<SuperviseRelevanceOptionsListBean.RowsBean> iterator = mSelectedBeans.iterator();
                while (iterator.hasNext()) {
                    SuperviseRelevanceOptionsListBean.RowsBean next = iterator.next();
                    if (next.getDataId().equals(bean.getDataId())) {
                        iterator.remove();
                    }
                }
            }
            mSelectedRelevanceOptionsAdapter.setData(mSelectedBeans);
        });

        //选中的
        mSelectedBeans = new ArrayList<>();
        mSelectedRelevanceOptionsAdapter = new SelectedRelevanceOptionsAdapter(mActivity, mSelectedBeans);
        FlexboxLayoutManager manage = new FlexboxLayoutManager(mActivity, FlexDirection.ROW, FlexWrap.WRAP) {
            @Override
            public boolean canScrollHorizontally() {
                return false;
            }
        };
        mRlvChooseItems.setLayoutManager(manage);
        mRlvChooseItems.setAdapter(mSelectedRelevanceOptionsAdapter);
        mSelectedRelevanceOptionsAdapter.addOnDelListener((bean1, pos) -> {
            mSelectedBeans.remove(pos);
            mSelectedRelevanceOptionsAdapter.setData(mSelectedBeans);
        });
    }

    private void getOptionsById(int currentPage) {
        mCurrentPage = currentPage;
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getRelevanceOptionList(mId, mCurrentPage + "", UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<SuperviseRelevanceOptionsListBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull SuperviseRelevanceOptionsListBean listBean) {
                    mSrlContent.finishLoadMore();
                    mSrlContent.finishRefresh();

                    if (listBean.getRows().size() > 0) {
                        ++mCurrentPage;
                        //有数据
                        //回显选中数据
                        for (int i = 0; i < listBean.getRows().size(); i++) {
                            for (int j = 0; j < mSelectedBeans.size(); j++) {
                                if (listBean.getRows().get(i).getDataId().equals(mSelectedBeans.get(j).getDataId())) {
                                    listBean.getRows().get(i).setCheck(true);
                                    break;
                                }
                            }
                        }
                        mDatas.addAll(listBean.getRows());
                        mAdapter.notifyDataSetChanged();
                        setStateView(14);
                    } else {
                        //没有数据
                        if (mCurrentPage == 1) {
                            setStateView(15);
                        } else {
                            setStateView(14);
                            mSrlContent.setNoMoreData(true);
                        }
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    setStateView(16);
                    ExceptionHandler.handleException(e);
                }

                @Override
                public void onComplete() {

                }
            });
    }


    private void setStateView(int state) {
        switch (state) {
            case 12://默认
            case 15://默认
                mPbLoading.setVisibility(View.GONE);
                mRlvContent.setVisibility(View.GONE);
                mIvEmptyData.setVisibility(View.VISIBLE);
                mTvErrorHint.setVisibility(View.VISIBLE);
                mTvErrorHint.setText("暂无数据");
                break;
            case 13://搜索中
                mPbLoading.setVisibility(View.VISIBLE);
                mRlvContent.setVisibility(View.GONE);
                mIvEmptyData.setVisibility(View.GONE);
                mTvErrorHint.setVisibility(View.VISIBLE);
                mTvErrorHint.setText("加载中...");
                break;
            case 14://搜索完成有数据
                mPbLoading.setVisibility(View.GONE);
                mRlvContent.setVisibility(View.VISIBLE);
                mIvEmptyData.setVisibility(View.GONE);
                mTvErrorHint.setVisibility(View.GONE);
                break;
            case 16://搜索失败
                mPbLoading.setVisibility(View.GONE);
                mRlvContent.setVisibility(View.GONE);
                mIvEmptyData.setVisibility(View.VISIBLE);
                mTvErrorHint.setVisibility(View.VISIBLE);
                mTvErrorHint.setText("加载失败,请稍后重试");
                break;
        }
    }

    @Override
    protected void doSearchByTitle() {

    }

    @Override
    protected void clearSearch() {

    }
}