package com.tenlionsoft.oamodule.activity.document;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.hjq.toast.ToastUtils;
import com.tenlionsoft.baselib.constant.PathConfig;
import com.tenlionsoft.baselib.core.beans.AddFileBean;
import com.tenlionsoft.baselib.core.beans.BaseSuccessBean;
import com.tenlionsoft.baselib.core.retrofit_net.BaseUrlApi;
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.core.widget.base.ShowFileAdapter;
import com.tenlionsoft.baselib.core.widget.views.ShareDocDialog;
import com.tenlionsoft.baselib.utils.ExceptionHandler;
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.beans.DocumentDetailBean;
import com.tenlionsoft.oamodule.beans.SaveDocShareBean;
import com.tenlionsoft.oamodule.net.OAApi;

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

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
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;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 作者: Adam
 * 日期: 2022年04月12日11:09:11
 * 邮箱: itgaojian@163.com
 * 描述: 文档中心-文档详情
 */
@Route(path = PathConfig.PATH_MODULE_OA_ACTIVITY_DOCUMENT_DETAIL)
public class DocumentDetailActivity extends BaseActivity {

    @BindView(R2.id.tv_doc_type)
    TextView mTvDocType;
    @BindView(R2.id.rb_doc)
    RadioButton mRbDoc;
    @BindView(R2.id.rb_pic)
    RadioButton mRbPic;
    @BindView(R2.id.rb_video)
    RadioButton mRbVideo;
    @BindView(R2.id.rb_audio)
    RadioButton mRbAudio;
    @BindView(R2.id.rg_type)
    RadioGroup mRgType;
    @BindView(R2.id.rlv_files)
    RecyclerView mRlvFiles;
    @BindView(R2.id.tv_summary)
    TextView mTvSummary;
    @BindView(R2.id.tv_remark)
    TextView mTvRemark;
    @BindView(R2.id.btn_del)
    Button mBtnDel;
    @BindView(R2.id.btn_edit)
    Button mBtnEdit;
    @BindView(R2.id.btn_share)
    Button mBtnShare;
    private Unbinder mBind;
    private String mId;
    private DocumentDetailBean mDetailBean;
    private ShareDocDialog mDialog;
    private String mSelUserIds;
    private String mSelUserNames;
    private String mType;

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

    @Override
    public void initData() {
        mBind = ButterKnife.bind(this);
        mTvBaseTitle.setText("文档详情");
        mId = getIntent().getStringExtra("id");
        mType = getIntent().getStringExtra("type");
        if (TextUtils.isEmpty(mId)) {
            ToastUtils.show("文档数据有误");
            finish();
        } else {
            getDocumentDetail();
        }

        mBtnDel.setOnClickListener(v -> onShowConfirm());//删除
        mBtnEdit.setOnClickListener(v -> ARouter.getInstance()
            .build(PathConfig.PATH_MODULE_OA_ACTIVITY_DOCUMENT_EDIT)
            .withString("id", mId)
            .navigation(mActivity, 12));//编辑
        mBtnShare.setOnClickListener(v -> ARouter.getInstance()
            .build(PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_PERSON)
            .withBoolean("isSingle", false)
            .navigation(mActivity, 13));//分享
    }

    private void showShare() {
        mDialog = new ShareDocDialog.DialogBuilder(mActivity).build();
        mDialog.addOnChangeListener(new ShareDocDialog.OnChangeListener() {
            @Override
            public void doChange(String ids, String add, String edit, String del, String share) {
                mDialog.dismiss();
                doShare(ids, add, edit, del, share);
            }

            @Override
            public void doSel() {
                ARouter.getInstance()
                    .build(PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_PERSON)
                    .withBoolean("isSingle", false)
                    .navigation(mActivity, 13);
            }
        });
        mDialog.show();
        mDialog.setNames(mSelUserIds, mSelUserNames);
    }

    /**
     * 分享成功
     */
    private void doShare(String ids, String add, String edit, String del, String share) {
        ProgressDialog dialog = UIUtil.initDialog(mActivity, "共享中...");
        dialog.show();
        RequestBody body = buildShareParams(ids, add, edit, del, share);
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .doShareDoc(body, UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<BaseSuccessBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull BaseSuccessBean baseSuccessBean) {
                    if (dialog.isShowing()) dialog.dismiss();
                    ToastUtils.show("共享成功");
                }

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

                @Override
                public void onComplete() {

                }
            });
    }

    private RequestBody buildShareParams(String ids, String add, String edit, String del, String share) {
        SaveDocShareBean bean = new SaveDocShareBean();
        bean.setUserId(ids);
        bean.setFileUploadId(mId);
        bean.setAddRole(add);
        bean.setDelRole(del);
        bean.setEditRole(edit);
        bean.setShareRole(share);
        return RequestBody.create(new Gson().toJson(bean), MediaType.parse("application/json; charset=utf-8"));
    }

    private void onShowConfirm() {
        new AlertDialog.Builder(mActivity)
            .setTitle("提示")
            .setMessage("确定要删除该文档吗?")
            .setPositiveButton("确定", (dialog, which) -> {
                dialog.dismiss();
                doDelDoc();
            })
            .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
            .create()
            .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 12) {
                //编辑成功返回
                refreshView(STATE_LOAD_LOADING);
                getDocumentDetail();
            } else if (requestCode == 13) {
                //文档共享
                mSelUserIds = data.getStringExtra("id");
                mSelUserNames = data.getStringExtra("name");
                if ("个人文档".equals(mDetailBean.getCatalogueType())) {
                    doShare(mSelUserIds, "", "", "", "");
                } else if ("公共文档".equals(mDetailBean.getCatalogueType())) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.setNames(mSelUserIds, mSelUserNames);
                    } else {
                        showShare();
                    }
                }
            }
        }
    }

    /**
     * 删除文档
     */
    private void doDelDoc() {
        ProgressDialog dialog = UIUtil.initDialog(mActivity, "删除中...");
        dialog.show();
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .doDelDoc(mId, UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<BaseSuccessBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull BaseSuccessBean baseSuccessBean) {
                    if (dialog.isShowing()) dialog.dismiss();
                    ToastUtils.show("删除成功");
                    setResult(RESULT_OK);
                    finish();
                }

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

                @Override
                public void onComplete() {

                }
            });
    }

    /**
     * 获取文档详情
     */
    private void getDocumentDetail() {
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getDocumentDetail(mId, UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<DocumentDetailBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull DocumentDetailBean documentDetailBean) {
                    setDataToView(documentDetailBean);
                }

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

                @Override
                public void onComplete() {

                }
            });
    }

    /**
     * 回显数据
     */
    private void setDataToView(DocumentDetailBean documentDetailBean) {
        refreshView(STATE_LOAD_SUCCESS);
        mDetailBean = documentDetailBean;
        mTvDocType.setText(mDetailBean.getFileTypeName());
        switch (mDetailBean.getFileType()) {
            case "文件":
                mRbDoc.setChecked(true);
                break;
            case "图片":
                mRbPic.setChecked(true);
                break;
            case "视频":
                mRbVideo.setChecked(true);
                break;
            case "音频":
                mRbAudio.setChecked(true);
                break;
        }
        //回显文件数据
        List<AddFileBean> files = new ArrayList<>();
        String[] split = mDetailBean.getFileId().split(",");
        for (int i = 0; i < split.length; i++) {
            AddFileBean bean = new AddFileBean();
            bean.setId(split[i]);
            bean.setPath(BaseUrlApi.BASE_IMG_URL + split[i]);
            switch (mDetailBean.getFileType()) {
                case "文件":
                    bean.setFileType(1);
                    break;
                case "图片":
                    bean.setFileType(2);
                    break;
                case "视频":
                    bean.setFileType(3);
                    break;
                case "音频":
                    bean.setFileType(4);
                    break;
            }
            files.add(bean);
        }
        ShowFileAdapter adapter = new ShowFileAdapter(mActivity, files);
        mRlvFiles.setLayoutManager(new GridLayoutManager(mActivity, 4));
        mRlvFiles.setAdapter(adapter);
        adapter.addOnItemClickListener(addFileBean -> {
            //TODO 在线预览文件
        });
        mTvSummary.setText(Html.fromHtml(mDetailBean.getContent()));
        mTvRemark.setText(Html.fromHtml(mDetailBean.getRemake()));

        if ("个人文档".equals(mType)) {
            mBtnDel.setVisibility(View.VISIBLE);
            mBtnEdit.setVisibility(View.VISIBLE);
            mBtnShare.setVisibility(View.VISIBLE);
        } else {
            if ("是".equals(mDetailBean.getDelRole())) mBtnDel.setVisibility(View.VISIBLE);
            if ("是".equals(mDetailBean.getEditRole())) mBtnEdit.setVisibility(View.VISIBLE);
            if ("是".equals(mDetailBean.getShareRole())) mBtnShare.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected void doSearchByTitle() {

    }

    @Override
    protected void clearSearch() {

    }
}