package com.tenlionsoft.oamodule.fragments;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
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.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
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.BaseFragment;
import com.tenlionsoft.baselib.utils.ExceptionHandler;
import com.tenlionsoft.baselib.utils.LogUtils;
import com.tenlionsoft.baselib.utils.UIUtil;
import com.tenlionsoft.baselib.utils.UserLgUtils;
import com.tenlionsoft.oamodule.R;
import com.tenlionsoft.oamodule.R2;
import com.tenlionsoft.oamodule.activity.document.DocumentAddActivity;
import com.tenlionsoft.oamodule.activity.document.DocumentDetailActivity;
import com.tenlionsoft.oamodule.adapter.DocumentAdapter;
import com.tenlionsoft.oamodule.beans.DocTypeBean;
import com.tenlionsoft.oamodule.beans.DocumentListBean;
import com.tenlionsoft.oamodule.net.OAApi;

import org.jetbrains.annotations.NotNull;

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

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
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/4/12 - 3:20 下午
 * 邮箱: itgaojian@163.com
 * 描述: 文档
 */
@Route(path = PathConfig.PATH_MODULE_OA_FRAGMENT_DOC)
public class DocFragment extends BaseFragment {

    @BindView(R2.id.tv_title_type)
    TextView mTvTitleType;
    @BindView(R2.id.iv_add)
    ImageView mIvAdd;
    @BindView(R2.id.rl_title)
    RelativeLayout mRlTitle;
    @BindView(R2.id.et_search)
    EditText mEtSearch;
    @BindView(R2.id.tv_cancel)
    TextView mTvCancel;
    @BindView(R2.id.rb_pri)
    RadioButton mRbPri;
    @BindView(R2.id.rb_share)
    RadioButton mRbShare;
    @BindView(R2.id.rb_pub)
    RadioButton mRbPub;
    @BindView(R2.id.rg_type)
    RadioGroup mRgType;
    @BindView(R2.id.rlv_doc)
    RecyclerView mRlvDoc;
    @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.ll_hint)
    LinearLayout mLlHint;
    @BindView(R2.id.srl_content)
    SmartRefreshLayout mSrlContent;
    private Unbinder mBind;

    private List<DocumentListBean.RowsBean> mDatas;
    private DocumentAdapter mAdapter;
    private int mCurrentPage = 1;
    private String mKeywords = "";
    private String mType = "个人文档";//个人文档  共享文档  公共文档
    private ProgressDialog mDialog;

    private OptionsPickerView mDataSourcePicker;
    private List<DocTypeBean> mDocTypes;
    private DocTypeBean mSelType;
    private ActivityResultLauncher<Intent> mLauncher;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_oa_document;
    }

    @Override
    protected void setDataToView(View dataView) {
        mBind = ButterKnife.bind(this, dataView);
        LogUtils.e("DocFragment");

        initViews();
    }

    /**
     * 初始化视图
     */
    private void initViews() {
        setStateView(STATE_SUCCESS);
        mDialog = UIUtil.initDialog(mActivity, "搜索中...");
        mSrlView.setEnableLoadMore(false);
        mSrlView.setEnableRefresh(false);
        mRgType.setOnCheckedChangeListener((group, checkedId) -> {
            refreshStateView(LionActions.STATE_LOAD);
            if (checkedId == R.id.rb_pri) {
                mType = "个人文档";//个人
            } else if (checkedId == R.id.rb_share) {
                mType = "共享文档";//共享
            } else if (checkedId == R.id.rb_pub) {
                mType = "公共文档";//公共
            }
            doRefresh();
        });
        mSrlContent.setOnLoadMoreListener(v -> doLoadMore());
        mSrlContent.setOnRefreshListener(v -> doRefresh());
        mDatas = new ArrayList<>();
        mAdapter = new DocumentAdapter(mActivity, mDatas);
        mRlvDoc.setLayoutManager(new LinearLayoutManager(mActivity));
        mRlvDoc.setAdapter(mAdapter);
        mAdapter.addOnItemClickListener(rowsBean -> {
            Intent intent = new Intent(mActivity, DocumentDetailActivity.class);
            intent.putExtra("id", rowsBean.getFileUploadId());
            intent.putExtra("type", mType);
            mLauncher.launch(intent);
        });


        mEtSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                mActivity.hideSoftKeyboard();
                mEtSearch.clearFocus();
                mKeywords = v.getText().toString();
                mDialog.show();
                doRefresh();
                return true;
            } else {
                return false;
            }
        });
        mIvAdd.setOnClickListener(v -> mLauncher.launch(new Intent(mActivity, DocumentAddActivity.class)));
        mTvTitleType.setOnClickListener(v -> onShowDocType());
        doRefresh();
    }

    /**
     * 刷新
     */
    private void doRefresh() {
        mDatas.clear();
        mAdapter.setData(mDatas);
        getDocumentList(1);
    }

    /**
     * 显示文档类型
     */
    private void onShowDocType() {
        if (mDocTypes != null && mDocTypes.size() > 0) {
            if (mDataSourcePicker == null) {
                mDataSourcePicker = new OptionsPickerBuilder(mActivity, (o1, o2, o3, v) -> {
                    if (!"文档类型".equals(mDocTypes.get(o1).getTypeName())) {
                        //全部
                        mSelType = null;
                    } else {
                        mSelType = mDocTypes.get(o1);
                    }
                    mTvTitleType.setText(mSelType.getTypeName());
                    doRefresh();
                })
                    .setTitleText("请选择")
                    .setCancelColor(Color.parseColor("#1189FF"))
                    .setSubmitColor(Color.parseColor("#1189FF"))
                    .setTitleColor(Color.parseColor("#1189FF"))
                    .build();
                mDataSourcePicker.setPicker(mDocTypes);
            }
            mDataSourcePicker.show();
        } else {
            getDocTypes();
        }
    }

    /**
     * 获取文档类型
     */
    private void getDocTypes() {
        ProgressDialog dialog = UIUtil.initDialog(mActivity, "加载中...");
        dialog.show();
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getDocTypes(UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<List<DocTypeBean>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull List<DocTypeBean> docTypeBeans) {
                    dialog.dismiss();
                    if (docTypeBeans.size() > 0) {
                        mDocTypes = docTypeBeans;
                        DocTypeBean allBean = new DocTypeBean();
                        allBean.setTypeName("文档类型");
                        mDocTypes.add(0, allBean);
                        onShowDocType();
                    } else {
                        ToastUtils.show("暂无数据");
                    }
                }

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

                @Override
                public void onComplete() {

                }
            });
    }

    @Override
    public void onAttach(@androidx.annotation.NonNull @NotNull Context context) {
        super.onAttach(context);
        mLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (Activity.RESULT_OK == result.getResultCode()) {
                doRefresh();
            }
        });
    }

    /**
     * 加载更多
     */
    private void doLoadMore() {
        getDocumentList(mCurrentPage);
    }

    /**
     * 获取文档列表
     */
    private void getDocumentList(int currentPage) {
        mCurrentPage = currentPage;
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getDocumentList(mKeywords, mType, mCurrentPage + "", UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<DocumentListBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

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

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

                @Override
                public void onComplete() {

                }
            });
    }

    private void refreshStateView(int state) {
        switch (state) {
            case LionActions.STATE_LOAD:
                mRlvDoc.setVisibility(View.GONE);
                mLlHint.setVisibility(View.VISIBLE);
                mPbLoading.setVisibility(View.VISIBLE);
                mIvEmptyData.setVisibility(View.GONE);
                mTvErrorHint.setVisibility(View.VISIBLE);
                mTvErrorHint.setText("加载中...");
                break;
            case LionActions.STATE_EMPTY:
                mRlvDoc.setVisibility(View.GONE);
                mLlHint.setVisibility(View.VISIBLE);
                mPbLoading.setVisibility(View.GONE);
                mIvEmptyData.setVisibility(View.VISIBLE);
                mIvEmptyData.setImageResource(R.drawable.ic_empty_data);
                mTvErrorHint.setVisibility(View.VISIBLE);
                mTvErrorHint.setText("暂无数据");
                break;
            case LionActions.STATE_ERROR:
                mRlvDoc.setVisibility(View.GONE);
                mLlHint.setVisibility(View.VISIBLE);
                mPbLoading.setVisibility(View.GONE);
                mIvEmptyData.setVisibility(View.VISIBLE);
                mIvEmptyData.setImageResource(R.drawable.ic_load_error);
                mTvErrorHint.setVisibility(View.VISIBLE);
                mTvErrorHint.setText("加载失败,请稍后重试");
                break;
            case LionActions.STATE_SUCCESS:
                mRlvDoc.setVisibility(View.VISIBLE);
                mLlHint.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    protected void refreshView() {

    }

    @Override
    protected void loadMoreData() {

    }
}
