package com.tenlionsoft.oamodule.activity.car;

import android.content.Intent;
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.ChooseDeptUserAdapter;
import com.tenlionsoft.oamodule.adapter.SelDeptAdapter;
import com.tenlionsoft.oamodule.adapter.SelectedPersonAdapter;
import com.tenlionsoft.oamodule.beans.ChoosePersonListBean;
import com.tenlionsoft.oamodule.beans.DepartmentListBean;
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 butterknife.Unbinder;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * 作者: Adam
 * 日期: 2022年04月13日16:33:50
 * 邮箱: itgaojian@163.com
 * 描述: 人员选择
 */
@Route(path = PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_PERSON)
public class ChooseUserActivity extends BaseActivity {

    @BindView(R2.id.rlv_choose_items)
    RecyclerView mRlvChooseItems;
    @BindView(R2.id.rlv_higher_dept)
    RecyclerView mRlvHigherDept;
    @BindView(R2.id.rlv_content)
    RecyclerView mRlvContent;
    @BindView(R2.id.srl_content)
    SmartRefreshLayout mSrlContent;
    @BindView(R2.id.pb_loading)
    ProgressBar mPbLoading;
    @BindView(R2.id.iv_empty_data)
    ImageView mIvEmptyData;
    @BindView(R2.id.tv_error_hint)
    TextView mTvErrorHint;
    private Unbinder mBind;

    private String mDeptId;//当前选中的部门
    private String mDeptName;//当前选中的部门名称
    private List<DepartmentListBean> mSelBeans = new ArrayList<>();
    private List<Object> mDatas = new ArrayList<>();
    private SelDeptAdapter mSelAdapter;
    private ChooseDeptUserAdapter mAdapter;

    private List<ChoosePersonListBean> mSelectedBeans = new ArrayList<>();
    private SelectedPersonAdapter mSelectedDeptAdapter;
    private boolean mIsSingle;//是否是单选

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


    @Override
    public void initData() {
        mBind = ButterKnife.bind(this);
        mIsSingle = getIntent().getBooleanExtra("isSingle", true);
        mTvBaseTitle.setText("选择人员");
        mTvPublish.setVisibility(View.VISIBLE);
        mTvPublish.setText("确定");
        mTvPublish.setOnClickListener(v -> doConfirm());
        initViews();
        //获取部门列表
        getDepartmentListByPid();
    }


    /**
     * TODO 确认选择
     */
    private void doConfirm() {
        if (mSelectedBeans != null && mSelectedBeans.size() > 0) {
            if (mIsSingle) {
                ChoosePersonListBean 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++) {
                    ChoosePersonListBean bean = mSelectedBeans.get(i);
                    ids += bean.getUserId() + ",";
                    names += bean.getUserName() + ",";
                }
                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() {
        refreshView(STATE_LOAD_SUCCESS);
        setStateView(13);
        DepartmentListBean bean = new DepartmentListBean();
        mDeptName = "组织部门";
        mDeptId = "0";

        bean.setDepartmentName(mDeptName);
        bean.setDepartmentId(mDeptId);
        mSelBeans.add(bean);
        mSelAdapter = new SelDeptAdapter(mActivity, mSelBeans);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRlvHigherDept.setLayoutManager(linearLayoutManager);
        mRlvHigherDept.setAdapter(mSelAdapter);
        mAdapter = new ChooseDeptUserAdapter(mActivity, mDatas);
        mRlvContent.setLayoutManager(new LinearLayoutManager(mActivity));
        mRlvContent.setAdapter(mAdapter);
        mAdapter.addOnItemCheckChange(new ChooseDeptUserAdapter.OnItemCheckChange() {
            @Override
            public void onItemCheckChange(ChoosePersonListBean bean, boolean isCheck, int pos) {
                //TODO 选中人员
                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) instanceof ChoosePersonListBean) {
                                ChoosePersonListBean bean1 = (ChoosePersonListBean) mAdapter.getData().get(i);
                                if (bean1.getUserId().equals(bean.getUserId())) {
                                    continue;
                                } else {
                                    bean1.setCheck(false);
                                }
                            }
                        }
                    }
                }
                mAdapter.notifyDataSetChanged();
                if (isCheck) {
                    if (mIsSingle) {
                        mSelectedBeans.clear();
                        mSelectedBeans.add(bean);
                    } else {
                        //TODO 去重
                        mSelectedBeans.add(bean);
                    }
                } else {
                    Iterator<ChoosePersonListBean> iterator = mSelectedBeans.iterator();
                    while (iterator.hasNext()) {
                        ChoosePersonListBean next = iterator.next();
                        if (next.getUserId().equals(bean.getUserId())) {
                            iterator.remove();
                        }
                    }
                }
                mSelectedDeptAdapter.setData(mSelectedBeans);
            }

            @Override
            public void onLowerDept(DepartmentListBean bean, int pos) {
                // 获取下级部门
                mSelBeans.add(bean);
                mSelAdapter.setData(mSelBeans);
                mDeptId = bean.getDepartmentId();
                mDeptName = bean.getDepartmentName();
                mDatas.clear();
                setStateView(13);
                getDepartmentListByPid();
                //获取当前选中的下一级
                mRlvHigherDept.scrollToPosition(mSelBeans.size() - 1);
            }
        });
        mSelAdapter.setOnItemChoose((bean12, pos) -> {
            List<DepartmentListBean> departmentListBeans = mSelBeans.subList(0, pos + 1);
            mSelBeans = departmentListBeans;
            mSelAdapter.setData(mSelBeans);
            mRlvHigherDept.scrollToPosition(mSelBeans.size() - 1);
            mDeptName = bean12.getDepartmentName();
            mDeptId = bean12.getDepartmentId();
            mDatas.clear();
            setStateView(13);
            getDepartmentListByPid();
        });

        mSrlContent.setEnableLoadMore(false);
        mSrlContent.setOnRefreshListener(refreshLayout -> {
            mDatas.clear();
            setStateView(13);
            getDepartmentListByPid();
        });
        // 当前选中的
        mSelectedDeptAdapter = new SelectedPersonAdapter(mActivity, mSelectedBeans);
        FlexboxLayoutManager manage = new FlexboxLayoutManager(mActivity, FlexDirection.ROW, FlexWrap.WRAP) {
            @Override
            public boolean canScrollHorizontally() {
                return false;
            }
        };
        mRlvChooseItems.setLayoutManager(manage);
        mRlvChooseItems.setAdapter(mSelectedDeptAdapter);
        mSelectedDeptAdapter.addOnDelListener((bean1, pos) -> {
            mSelectedBeans.remove(pos);
            mSelectedDeptAdapter.setData(mSelectedBeans);
        });
    }

    /**
     * 获取部门列表
     */
    private void getDepartmentListByPid() {
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getDeptListByPid(mDeptId, UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<List<DepartmentListBean>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull List<DepartmentListBean> departmentListBeans) {
                    mSrlContent.finishRefresh();
                    if (departmentListBeans.size() > 0) {
                        setStateView(14);
                        mDatas.addAll(departmentListBeans);
                        mAdapter.setData(mDatas);
                    } else {
                        if ("0".equals(mDeptId)) {
                            setStateView(12);
                        }
                    }
                    if (!"0".equals(mDeptId)) {
                        getPersonByDeptId(mDeptId);
                    }
                }

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

                @Override
                public void onComplete() {

                }
            });
    }

    /**
     * 获取部门下所有人员
     *
     * @param deptId
     */
    private void getPersonByDeptId(String deptId) {
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getPersonListByDeptId(deptId, UserLgUtils.getToken())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<ChoosePersonListBean>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull List<ChoosePersonListBean> communityListBean) {
                    mSrlContent.finishRefresh();
                    if (communityListBean.size() > 0) {
                        for (int i = 0; i < mSelectedBeans.size(); i++) {
                            ChoosePersonListBean bean = mSelectedBeans.get(i);
                            for (int j = 0; j < communityListBean.size(); j++) {
                                ChoosePersonListBean listBean = communityListBean.get(j);
                                if (listBean.getUserId().equals(bean.getUserId())) {
                                    listBean.setCheck(true);
                                }
                            }
                        }
                        mDatas.addAll(communityListBean);
                        mAdapter.setData(mDatas);
                    }
                    if (mDatas.size() > 0) {
                        setStateView(14);
                    } else {
                        setStateView(12);
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    mSrlContent.finishRefresh();
                    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 clearSearch() {

    }

    @Override
    protected void doSearchByTitle() {

    }
}