package com.tenlionsoft.oamodule.activity.routine;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.toast.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.tenlionsoft.baselib.constant.LionActions;
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.TimeUtils;
import com.tenlionsoft.baselib.utils.UserLgUtils;
import com.tenlionsoft.oamodule.R;
import com.tenlionsoft.oamodule.R2;
import com.tenlionsoft.oamodule.adapter.RoutineAdapter;
import com.tenlionsoft.oamodule.beans.RoutineAcceptListBean;
import com.tenlionsoft.oamodule.beans.RoutineListBean;
import com.tenlionsoft.oamodule.net.OAApi;

import java.util.ArrayList;
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.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 作者: Adam
 * 日期: 2022年04月15日14:41:37
 * 邮箱: itgaojian@163.com
 * 描述: 日常工作
 */
@Route(path = PathConfig.PATH_MODULE_OA_ACTIVITY_ROUTINE_WORK)
public class RoutineWorkActivity extends BaseActivity {


    @BindView(R2.id.iv_back)
    ImageView mIvBack;
    @BindView(R2.id.rb_apply)
    RadioButton mRbApply;
    @BindView(R2.id.rb_accept)
    RadioButton mRbAccept;
    @BindView(R2.id.rg_type)
    RadioGroup mRgType;
    @BindView(R2.id.iv_control)
    TextView mIvControl;
    @BindView(R2.id.rl_content_title)
    RelativeLayout mRlContentTitle;
    @BindView(R2.id.et_base_search_cancel)
    EditText mEtBaseSearchCancel;
    @BindView(R2.id.tv_base_search_cancel)
    TextView mTvBaseSearchCancel;
    @BindView(R2.id.ll_base_search_cancel)
    LinearLayout mLlBaseSearchCancel;
    @BindView(R2.id.tv_start_date)
    TextView mTvStartDate;
    @BindView(R2.id.tv_end_date)
    TextView mTvEndDate;
    @BindView(R2.id.rlv_content)
    RecyclerView mRlvContent;
    @BindView(R2.id.srl_content)
    SmartRefreshLayout mSrlContent;
    @BindView(R2.id.pb_loading)
    ProgressBar mLoading;
    @BindView(R2.id.iv_empty_data)
    ImageView mIvData;
    @BindView(R2.id.tv_error_hint)
    TextView mTvHint;
    @BindView(R2.id.tv_state)
    TextView mTvState;
    private Unbinder mBind;
    private int mType = 1;//1我发起的  2我接受的
    private int mCurrentPage = 1;
    private String mKeywords = "";

    private List<Object> mDatas;
    private RoutineAdapter mAdapter;

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

    @Override
    public void initData() {
        mBind = ButterKnife.bind(this);
        mRlTitleBar.setVisibility(View.GONE);
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .statusBarColor(R.color.gray_bg)
            .titleBar(mRlContentTitle)
            .init();
        mIvControl.setOnClickListener(v -> ARouter.getInstance()
            .build(PathConfig.PATH_MODULE_OA_ACTIVITY_ROUTINE_WORK_MINE_LAUNCH_ADD)
            .navigation(mActivity, 12));
        refreshView(STATE_LOAD_SUCCESS);
        refreshPageState(STATE_LOAD_LOADING);
        initViews();
    }

    private void initViews() {
        mTvStartDate.setOnClickListener(v -> onShowDate(1));
        mTvEndDate.setOnClickListener(v -> onShowDate(2));
        mDatas = new ArrayList<>();
        mAdapter = new RoutineAdapter(mActivity, mDatas);
        mRlvContent.setLayoutManager(new LinearLayoutManager(mActivity));
        mRlvContent.setAdapter(mAdapter);
        mRgType.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_apply) {
                //我发起的
                mType = 1;
            } else if (checkedId == R.id.rb_accept) {
                //我接受的
                mType = 2;
            }
            //重置搜索条件
            resetCondition();
        });
        mSrlContent.setOnRefreshListener(v -> doRefresh());
        mSrlContent.setOnLoadMoreListener(v -> doLoadMore());
        doRefresh();
    }

    private void resetCondition() {
        mEtBaseSearchCancel.setText("");
        mTvStartDate.setText("");
        mTvEndDate.setText("");
        mTvState.setText("");
        refreshPageState(STATE_LOAD_LOADING);
        mDatas.clear();
        doRefresh();
    }

    /**
     * 我接受的工作
     */
    private void getMineAcceptRoutineList(int currentPage) {
        mCurrentPage = currentPage;
        String start = mTvStartDate.getText().toString().trim();
        String end = mTvEndDate.getText().toString().trim();
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getMineAcceptRoutineList(start, end, mKeywords, mCurrentPage + "", UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<RoutineAcceptListBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull RoutineAcceptListBean listBean) {
                    if (listBean.getRows() != null && listBean.getRows().size() > 0) {
                        ++mCurrentPage;
                        if (currentPage == 1) {
                            mDatas.clear();
                            mDatas.addAll(listBean.getRows());
                        } else {
                            mDatas.addAll(listBean.getRows());
                        }
                        refreshPageState(STATE_LOAD_SUCCESS);
                        mAdapter.notifyDataSetChanged();
                        mSrlContent.finishRefresh();
                        if (mDatas.size() >= listBean.getTotal()) {
                            mSrlContent.finishLoadMore();
                            mSrlContent.setNoMoreData(true);
                        } else {
                            mSrlContent.finishLoadMore();
                            mSrlContent.setNoMoreData(false);
                        }
                    } else {
                        mSrlContent.finishRefresh();
                        mSrlContent.finishLoadMore();
                        if (currentPage > 1) {
                            mSrlContent.setNoMoreData(true);
                        } else {
                            refreshPageState(STATE_LOAD_EMPTY);
                            if (!TextUtils.isEmpty(mKeywords)) {
                                ToastUtils.show("未查询到相关内容");
                            }
                        }
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    mSrlContent.finishLoadMore();
                    mSrlContent.finishRefresh();
                    ExceptionHandler.handleException(e);
                    refreshPageState(STATE_LOAD_ERROR);
                }

                @Override
                public void onComplete() {

                }
            });
    }

    /**
     * 我发起的工作
     */
    private void getMineApplyRoutineList(int currentPage) {
        mCurrentPage = currentPage;
        String start = mTvStartDate.getText().toString().trim();
        String end = mTvEndDate.getText().toString().trim();
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getMineRoutineList(start, end, mKeywords, mCurrentPage + "", UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<RoutineListBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull RoutineListBean listBean) {
                    if (listBean.getRows() != null && listBean.getRows().size() > 0) {
                        ++mCurrentPage;
                        if (currentPage == 1) {
                            mDatas.clear();
                            mDatas.addAll(listBean.getRows());
                        } else {
                            mDatas.addAll(listBean.getRows());
                        }
                        refreshPageState(STATE_LOAD_SUCCESS);
                        mAdapter.notifyDataSetChanged();
                        mSrlContent.finishRefresh();
                        if (mDatas.size() >= listBean.getTotal()) {
                            mSrlContent.finishLoadMore();
                            mSrlContent.setNoMoreData(true);
                        } else {
                            mSrlContent.finishLoadMore();
                            mSrlContent.setNoMoreData(false);
                        }
                    } else {
                        mSrlContent.finishRefresh();
                        mSrlContent.finishLoadMore();
                        if (currentPage > 1) {
                            mSrlContent.setNoMoreData(true);
                        } else {
                            if (TextUtils.isEmpty(mKeywords)) {
                                //无数据
                                refreshPageState(STATE_LOAD_EMPTY);
                            } else {
                                refreshPageState(STATE_LOAD_EMPTY);
                                ToastUtils.show("未查询到相关内容");
                            }
                        }
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    mSrlContent.finishLoadMore();
                    mSrlContent.finishRefresh();
                    ExceptionHandler.handleException(e);
                    refreshPageState(LionActions.STATE_ERROR);
                }

                @Override
                public void onComplete() {

                }
            });
    }


    /**
     * 时间选择
     */
    private void onShowDate(int i) {
        TimePickerView mTimePickerView = new TimePickerBuilder(mActivity, (date, v) -> {
            switch (i) {
                case 1:
                    mTvStartDate.setText(TimeUtils.date2String(date));
                    break;
                case 2:
                    //判断时间大小
                    String start = mTvStartDate.getText().toString().trim();
                    int span = TimeUtils.compareDate(date, TimeUtils.string2Date(start));
                    if (span >= 0) {
                        mTvEndDate.setText(TimeUtils.date2String(date));
                        refreshPageState(STATE_LOAD_LOADING);
                        doRefresh();
                    } else {
                        ToastUtils.show("结束时间须大于开始时间");
                    }
                    break;
            }
        })
            .setTitleText("请选时间")
            .setCancelColor(Color.parseColor("#1189FF"))
            .setSubmitColor(Color.parseColor("#1189FF"))
            .isDialog(false)
            .setType(new boolean[]{true, true, true, false, false, false})
            .setTitleColor(Color.parseColor("#1189FF"))
            .build();
        mTimePickerView.show();
    }


    /**
     * 刷新页面
     *
     * @param state 页面状态码
     */
    public void refreshPageState(int state) {
        switch (state) {
            case STATE_LOAD_LOADING://加载中
                mLoading.setVisibility(View.VISIBLE);
                mIvData.setVisibility(View.GONE);
                mTvHint.setVisibility(View.VISIBLE);
                mTvHint.setText(getResources().getString(com.tenlionsoft.baselib.R.string.loading));
                mRlvContent.setVisibility(View.INVISIBLE);
                break;
            case STATE_LOAD_SUCCESS://加载成功
                mLoading.setVisibility(View.GONE);
                mIvData.setVisibility(View.GONE);
                mTvHint.setVisibility(View.GONE);
                mRlvContent.setVisibility(View.VISIBLE);
                break;
            case STATE_LOAD_EMPTY://空数据
                mLoading.setVisibility(View.GONE);
                mIvData.setVisibility(View.VISIBLE);
                mIvData.setBackgroundResource(com.tenlionsoft.baselib.R.drawable.ic_empty_data);
                mTvHint.setVisibility(View.VISIBLE);
                mTvHint.setText(getResources().getString(com.tenlionsoft.baselib.R.string.empty_data));
                mRlvContent.setVisibility(View.INVISIBLE);
                break;
            case STATE_LOAD_ERROR:
                mLoading.setVisibility(View.GONE);
                mIvData.setVisibility(View.VISIBLE);
                mTvHint.setVisibility(View.VISIBLE);
                mIvData.setBackgroundResource(com.tenlionsoft.baselib.R.drawable.ic_load_error);
                mTvHint.setText(getResources().getString(com.tenlionsoft.baselib.R.string.loading_error));
                mRlvContent.setVisibility(View.INVISIBLE);
                break;
        }
    }

    /**
     * 加载更多
     */
    private void doLoadMore() {
        if (mType == 1) {
            getMineApplyRoutineList(mCurrentPage);
        } else {
            getMineAcceptRoutineList(mCurrentPage);
        }
    }

    /**
     * 刷新
     */
    private void doRefresh() {
        mDatas.clear();
        mAdapter.setData(mDatas);
        if (mType == 1) {
            getMineApplyRoutineList(1);
        } else {
            getMineAcceptRoutineList(1);
        }
    }


    @Override
    protected void doSearchByTitle() {

    }

    @Override
    protected void clearSearch() {

    }

}