package com.tenlionsoft.oamodule.activity.document;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
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.google.gson.Gson;
import com.hjq.toast.ToastUtils;
import com.leon.lfilepickerlibrary.LFilePicker;
import com.leon.lfilepickerlibrary.utils.Constant;
import com.tenlionsoft.baselib.constant.LionActions;
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.api.BaseApiService;
import com.tenlionsoft.baselib.core.retrofit_net.conver.RxTransformer;
import com.tenlionsoft.baselib.core.widget.base.AddFileAdapter;
import com.tenlionsoft.baselib.core.widget.base.BaseActivity;
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.beans.DocTypeBean;
import com.tenlionsoft.oamodule.beans.SaveFileBean;
import com.tenlionsoft.oamodule.net.OAApi;

import org.jetbrains.annotations.NotNull;

import java.io.File;
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.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 作者: Adam
 * 日期: 2022年04月11日14:33:58
 * 邮箱: itgaojian@163.com
 * 描述: 文档上传
 */
@Route(path = PathConfig.PATH_MODULE_OA_ACTIVITY_DOCUMENT_ADD)
public class DocumentAddActivity extends BaseActivity {

    @BindView(R2.id.tv_doc_type)
    TextView mTvDocType;
    @BindView(R2.id.rg_type)
    RadioGroup mRgType;
    @BindView(R2.id.rlv_files)
    RecyclerView mRlvFiles;
    @BindView(R2.id.et_summary)
    EditText mEtSummary;
    @BindView(R2.id.et_remark)
    EditText mEtRemark;
    @BindView(R2.id.btn_confirm)
    Button mBtnConfirm;
    private Unbinder mBind;
    private String mDocType = "文件";
    private OptionsPickerView mDataSourcePicker;
    private List<DocTypeBean> mDocTypes;
    private DocTypeBean mSelType;
    private List<AddFileBean> mFileBeans = new ArrayList<>();
    private AddFileAdapter mAddFileAdapter;
    private String[] fileFilter = new String[]{".doc", ".docx", ".xls", ".xlsx", ".pptx", ".ppt", ".txt", ".pdf"};
    private int mFileMax = 9;

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

    @Override
    public void initData() {
        mBind = ButterKnife.bind(this);
        mTvBaseTitle.setText("文档上传");
        refreshView(STATE_LOAD_SUCCESS);
        initViews();
    }

    private void initViews() {
        mRgType.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_doc) {
                mDocType = "文件";
                fileFilter = new String[]{".doc", ".docx", ".xls", ".xlsx", ".pptx", ".ppt", ".txt", ".pdf"};
                mFileMax = 9;//9
            } else if (checkedId == R.id.rb_pic) {
                mDocType = "图片";
                fileFilter = new String[]{".jpg", ".jpeg", ".png"};
                mFileMax = 20;//20
            } else if (checkedId == R.id.rb_video) {
                mDocType = "视频";
                fileFilter = new String[]{".mp4", ".avi", ".mkv", ".flv"};
                mFileMax = 5;//5
            } else if (checkedId == R.id.rb_audio) {
                mDocType = "音频";
                fileFilter = new String[]{".mp3", ".wmv", ".amr"};
                mFileMax = 5;//5
            }
            mFileBeans.clear();
            mFileBeans.add(new AddFileBean());
            mAddFileAdapter.notifyDataSetChanged();
        });
        mTvDocType.setOnClickListener(v -> onShowDocType());

        mFileBeans.add(new AddFileBean());
        mAddFileAdapter = new AddFileAdapter(mActivity, mFileBeans);
        mAddFileAdapter.addOnItemClickListener(addFileBean -> {
            if (TextUtils.isEmpty(addFileBean.getId())) {
                //选择
                if (mFileMax == 0) {
                    ToastUtils.show("超过最大上传数量限制");
                } else {
                    //TODO 校验是否有权限
                    new LFilePicker()
                        .withActivity(this)
                        .withRequestCode(LionActions.REQUEST_CODE_AC)
                        .withTitle("文件选择")
                        .withMaxNum(mFileMax)
                        .withFileFilter(fileFilter)
                        .start();
                }
            } else {
                //预览
                //判断文件类型
            }
        });
        //删除上传的文件
        mAddFileAdapter.addOnDeleteListener((bean, i) -> {
            //删除list中的某个数据
            mFileBeans.remove(i);
            mAddFileAdapter.notifyDataSetChanged();
            ++mFileMax;
        });
        mRlvFiles.setLayoutManager(new GridLayoutManager(mActivity, 4));
        mRlvFiles.setAdapter(mAddFileAdapter);
        mBtnConfirm.setOnClickListener(v -> doSave());
    }

    /**
     * 保存文件
     */
    private void doSave() {
        if (checkParams()) {
            RequestBody body = buildParams();
            ProgressDialog dialog = UIUtil.initDialog(mActivity, "保存中...");
            dialog.show();
            RetrofitManager.getInstance()
                .create(OAApi.class)
                .doSaveFiles(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("保存成功");
                        setResult(RESULT_OK);
                        finish();
                    }

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

                    @Override
                    public void onComplete() {

                    }
                });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == LionActions.REQUEST_CODE_AC) {
                if (data != null) {
                    ArrayList<String> paths = data.getStringArrayListExtra(Constant.RESULT_INFO);
                    if (paths != null && paths.size() > 0) {
                        doUploadFiles(paths);
                    } else {
                        ToastUtils.show("未选择文件");
                    }
                } else {
                    ToastUtils.show("路径有误,请稍后重试");
                }
            }
        }
    }

    /**
     * 上传文件
     *
     * @param paths
     */
    private int mUploadCount = 0;

    private void doUploadFiles(ArrayList<String> paths) {
        LogUtils.e(paths);

        ProgressDialog progressDialog = UIUtil.initDialog(mActivity, "上传中...");
        progressDialog.show();
        List<Observable> requests = new ArrayList<>();
        for (int i = 0; i < paths.size(); i++) {
            File file = new File(paths.get(i));
            Observable observable = createObservable(file);
            if (observable == null) return;
            requests.add(observable);
        }
        Observable[] observables1 = requests.toArray(new Observable[requests.size()]);

        Observable.mergeArrayDelayError(observables1)
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NotNull Object o) {
                    ++mUploadCount;
                    if (o instanceof BaseSuccessBean) {
                        --mFileMax;
                        //刷新文件
                        BaseSuccessBean bean = (BaseSuccessBean) o;
                        AddFileBean fileBean = new AddFileBean();
                        fileBean.setId(bean.getData());
                        fileBean.setPath(BaseUrlApi.BASE_IMG_URL + bean.getData());
//                        判断文件类型
                        if ("文件".equals(mDocType)) {
                            fileBean.setFileType(1);
                        } else if ("图片".equals(mDocType)) {
                            fileBean.setFileType(2);
                        } else if ("视频".equals(mDocType)) {
                            fileBean.setFileType(3);
                        } else if ("音频".equals(mDocType)) {
                            fileBean.setFileType(4);
                        }
                        mFileBeans.add(0, fileBean);
                    }
                    mAddFileAdapter.notifyDataSetChanged();
                    if (mUploadCount == paths.size()) {
                        mUploadCount = 0;
                        if (progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    e.printStackTrace();
                    mUploadCount = 0;
                    if (progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    ToastUtils.show("上传失败,请稍后重试.");
                }

                @Override
                public void onComplete() {

                }
            });
    }

    private Observable createObservable(File file) {
        LogUtils.e(file.exists());
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body;
        if ("文件".equals(mDocType)) {
            body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
            return RetrofitManager.getInstance()
                .create(BaseApiService.class)
                .uploadFile(body, UserLgUtils.getToken())
                .compose(RxTransformer.getTransformer());

        } else if ("图片".equals(mDocType)) {

            body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
            return RetrofitManager.getInstance()
                .create(BaseApiService.class)
                .uploadImage(body, UserLgUtils.getToken())
                .compose(RxTransformer.getTransformer());

        } else if ("视频".equals(mDocType)) {

            body = MultipartBody.Part.createFormData("video", file.getName(), requestFile);
            return RetrofitManager.getInstance()
                .create(BaseApiService.class)
                .uploadVideo(body, UserLgUtils.getToken())
                .compose(RxTransformer.getTransformer());

        } else if ("音频".equals(mDocType)) {
            body = MultipartBody.Part.createFormData("audio", file.getName(), requestFile);

            return RetrofitManager.getInstance()
                .create(BaseApiService.class)
                .uploadAudio(body, UserLgUtils.getToken())
                .compose(RxTransformer.getTransformer());

        } else {
            return null;
        }
    }

    /**
     * 显示文档类型
     */
    private void onShowDocType() {
        hideSoftKeyboard();
        if (mDocTypes != null && mDocTypes.size() > 0) {
            if (mDataSourcePicker == null) {
                mDataSourcePicker = new OptionsPickerBuilder(mActivity, (o1, o2, o3, v) -> {
                    mSelType = mDocTypes.get(o1);
                    mTvDocType.setText(mSelType.getTypeName());
                })
                    .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;
                        onShowDocType();
                    } else {
                        ToastUtils.show("暂无数据");
                    }
                }

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

                @Override
                public void onComplete() {

                }
            });
    }

    private boolean checkParams() {
        if (mSelType == null) {
            ToastUtils.show("请选择文档类型");
            return false;
        }
        LogUtils.e(mFileBeans.size());
        if (mFileBeans.size() < 2) {
            ToastUtils.show("请上传文件");
            return false;
        }
        String summary = mEtSummary.getText().toString().trim();
        if (TextUtils.isEmpty(summary)) {
            ToastUtils.show("请输入文件说明");
            return false;
        }

        return true;
    }

    /**
     * 构建提交参数
     */
    private RequestBody buildParams() {
        SaveFileBean fileBean = new SaveFileBean();
        //fileBean.setCatalogueId(mSelType.get)
        fileBean.setFileType(mDocType);
        fileBean.setFileTypeId(mSelType.getFileTypeId());
        if (mFileBeans.size() == 2) {
            fileBean.setFileModular("单文件");
        } else {
            fileBean.setFileModular("多文件");
        }

        StringBuilder fileId = new StringBuilder();
        for (AddFileBean bean : mFileBeans) {
            if (!TextUtils.isEmpty(bean.getId())) {
                fileId.append(bean.getId()).append(",");
            }
        }
        if (fileId.toString().endsWith(",")) {
            fileId = new StringBuilder(fileId.substring(0, fileId.length() - 1));
        }
        fileBean.setFileId(fileId.toString());
        String summary = mEtSummary.getText().toString().trim();
        fileBean.setContent(summary);
        String remark = mEtRemark.getText().toString().trim();
        fileBean.setRemake(remark);
        Gson gson = new Gson();
        String obj = gson.toJson(fileBean);
        return RequestBody.create(obj, MediaType.parse("application/json; charset=utf-8"));
    }

    @Override
    protected void doSearchByTitle() {

    }

    @Override
    protected void clearSearch() {

    }
}