package com.tenlionsoft.oamodule.activity.workreports;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.text.Html;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
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.beans.DicBean;
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.SaveWorkReportBean;
import com.tenlionsoft.oamodule.beans.WorkReportDetailBean;
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 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月19日15:37:36
 * 邮箱: itgaojian@163.com
 * 描述: 编辑工作报告
 */
@Route(path = PathConfig.PATH_MODULE_OA_ACTIVITY_WORK_REPORT_EDIT)
public class EditWorkReportActivity extends BaseActivity {


    @BindView(R2.id.et_name)
    EditText mEtName;
    @BindView(R2.id.tv_type)
    TextView mTvType;
    @BindView(R2.id.et_out)
    EditText mEtOut;
    @BindView(R2.id.et_content)
    EditText mEtContent;
    @BindView(R2.id.rlv_files)
    RecyclerView mRlvFiles;
    @BindView(R2.id.btn_confirm)
    Button mBtnConfirm;
    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;


    private OptionsPickerView<DicBean> mTypePicker;
    private List<DicBean> mTyps;
    private DicBean mSelType;
    private String mId;

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

    @Override
    public void initData() {
        ButterKnife.bind(this);
        mTvBaseTitle.setText("工作报告编辑");
        initViews();
        mId = getIntent().getStringExtra("id");
        if (TextUtils.isEmpty(mId)) {
            ToastUtils.show("数据有误");
            finish();
        } else {
            getDetailById();
        }
    }

    private void getDetailById() {
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getWorkReportDetail(mId, UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<WorkReportDetailBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull WorkReportDetailBean workReportDetailBean) {
                    setDataToView(workReportDetailBean);
                }

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

                @Override
                public void onComplete() {

                }
            });
    }

    private void setDataToView(WorkReportDetailBean bean) {
        refreshView(STATE_LOAD_SUCCESS);
        mEtName.setText(bean.getReportTitle());
        for (DicBean typ : mTyps) {
            if (typ.getDataId().equals(bean.getReportType())) {
                mSelType = typ;
                break;
            }
        }
        mTvType.setText(mSelType.getDataName());
        mEtOut.setText(Html.fromHtml(bean.getReportEgress()));
        mEtContent.setText(Html.fromHtml(bean.getReportContent()));
        if (!TextUtils.isEmpty(bean.getReportFiles())) {
            mFileBeans.clear();
            String[] split = bean.getReportFiles().split(",");
            for (int i = 0; i < split.length; i++) {
                AddFileBean fileBean = new AddFileBean();
                fileBean.setId(split[i]);
                fileBean.setPath(BaseUrlApi.BASE_IMG_URL + split[i]);
                fileBean.setFileType(1);
                mFileBeans.add(0, fileBean);
                --mFileMax;
            }
            mFileBeans.add(new AddFileBean());
            mAddFileAdapter.setData(mFileBeans);
        }
    }

    private void initViews() {
        mTyps = new ArrayList<>();
        DicBean type1 = new DicBean();
        type1.setDataId("1");
        type1.setDataName("工作日报");

        DicBean type2 = new DicBean();
        type2.setDataId("2");
        type2.setDataName("工作月报");

        DicBean type3 = new DicBean();
        type3.setDataId("3");
        type3.setDataName("工作年报");

        mTyps.add(type1);
        mTyps.add(type2);
        mTyps.add(type3);

        mTvType.setOnClickListener(v -> onShowType());
        mFileBeans.add(new AddFileBean());
        mAddFileAdapter = new AddFileAdapter(mActivity, mFileBeans);
        mAddFileAdapter.addOnItemClickListener(addFileBean -> {
            LogUtils.e("添加文件");
            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 -> doConfirm());
    }

    /**
     * 显示类型
     */
    private void onShowType() {
        hideSoftKeyboard();
        if (mTyps != null && mTyps.size() > 0) {
            if (mTypePicker == null) {
                mTypePicker = new OptionsPickerBuilder(mActivity, (o1, o2, o3, v) -> {
                    mSelType = mTyps.get(o1);
                    mTvType.setText(mSelType.getDataName());
                })
                    .setTitleText("请选择")
                    .setCancelColor(Color.parseColor("#1189FF"))
                    .setSubmitColor(Color.parseColor("#1189FF"))
                    .setTitleColor(Color.parseColor("#1189FF"))
                    .build();
                mTypePicker.setPicker(mTyps);
            }
            mTypePicker.show();
        } else {
            ToastUtils.show("数据有误,请重新打开页面");
        }
    }


    @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) {
        ProgressDialog progressDialog = UIUtil.initDialog(mActivity, "上传中...");
        progressDialog.show();
        List<Observable<BaseSuccessBean>> requests = new ArrayList<>();
        List<String> fileNames = new ArrayList<>();
        for (int i = 0; i < paths.size(); i++) {
            File file = new File(paths.get(i));
            Observable<BaseSuccessBean> observable = createObservable(file);
            fileNames.add(file.getName());
            if (observable == null) return;
            requests.add(observable);
        }
        Observable<BaseSuccessBean>[] 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());
                        fileBean.setFileType(1);
                        fileBean.setFileName(fileNames.get(mUploadCount - 1));
                        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<BaseSuccessBean> createObservable(File file) {
        LogUtils.e(file.exists());
        RequestBody requestFile = RequestBody.create(file, MediaType.parse("multipart/form-data"));
        MultipartBody.Part body;
        body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        return RetrofitManager.getInstance()
            .create(BaseApiService.class)
            .uploadFile(body, UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer());
    }


    private RequestBody buildParams() {
        SaveWorkReportBean bean = new SaveWorkReportBean();
        String name = mEtName.getText().toString().trim();
        bean.setReportTitle(name);
        String out = mEtOut.getText().toString().trim();
        bean.setReportEgress(out);
        String content = mEtContent.getText().toString().trim();
        bean.setReportContent(content);
        bean.setReportType(mSelType.getDataId());
        if (mFileBeans.size() >= 2) {
            StringBuilder fileId = new StringBuilder();
            for (AddFileBean fileBean : mFileBeans) {
                if (!TextUtils.isEmpty(fileBean.getId())) {
                    fileId.append(fileBean.getId()).append(",");
                }
            }
            if (fileId.toString().endsWith(",")) {
                fileId = new StringBuilder(fileId.substring(0, fileId.length() - 1));
            }
            bean.setReportFiles(fileId.toString().trim());
        } else {
            bean.setReportFiles("");
        }
        return RequestBody.create(new Gson().toJson(bean), MediaType.parse("application/json; charset=utf-8"));
    }

    private boolean checkParams() {
        String name = mEtName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            ToastUtils.show("请输入上报标题");
            return false;
        }
        if (mSelType == null) {
            ToastUtils.show("请选择上报类型");
            return false;
        }
        String content = mEtContent.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            ToastUtils.show("请输入工作内容");
            return false;
        }
        return true;
    }


    private void doConfirm() {
        if (checkParams()) {
            ProgressDialog dialog = UIUtil.initDialog(mActivity, "保存中...");
            dialog.show();
            RequestBody body = buildParams();
            RetrofitManager.getInstance()
                .create(OAApi.class)
                .doEditWorkReport(mId, 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 doSearchByTitle() {

    }

    @Override
    protected void clearSearch() {

    }
}