package com.tenlionsoft.oamodule.activity.routine;

import android.app.ProgressDialog;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
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.core.widget.base.ShowFileAdapter;
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.RoutineBean;
import com.tenlionsoft.oamodule.beans.SaveRoutineAcceptBean;
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.appcompat.widget.SwitchCompat;
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月18日14:07:04
 * 邮箱: itgaojian@163.com
 * 描述: 日常工作完成
 */
@Route(path = PathConfig.PATH_MODULE_OA_ACTIVITY_ROUTINE_WORK_RESTORE)
public class RoutineRestoreActivity extends BaseActivity {

    @BindView(R2.id.tv_name)
    TextView mTvName;
    @BindView(R2.id.tv_start_time)
    TextView mTvStartTime;
    @BindView(R2.id.tv_end_time)
    TextView mTvEndTime;
    @BindView(R2.id.tv_tl)
    TextView mTvTl;
    @BindView(R2.id.tv_undertake)
    TextView mTvUndertake;
    @BindView(R2.id.tv_assisted)
    TextView mTvAssisted;
    @BindView(R2.id.sw_schedule)
    SwitchCompat mSwSchedule;
    @BindView(R2.id.tv_request)
    TextView mTvRequest;
    @BindView(R2.id.tv_remark)
    TextView mTvRemark;
    @BindView(R2.id.rlv_files)
    RecyclerView mRlvFiles;
    @BindView(R2.id.et_restore)
    EditText mEtRestore;
    @BindView(R2.id.rlv_restore_files)
    RecyclerView mRlvRestoreFiles;
    @BindView(R2.id.ll_restore)
    LinearLayout mLlRestore;
    @BindView(R2.id.btn_confirm)
    Button mBtnConfirm;
    private Unbinder mBind;
    private String mId;
    private RoutineBean mBean;
    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 String mUserId;
    private String mUserType;

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

    @Override
    public void initData() {
        mBind = ButterKnife.bind(this);
        mTvBaseTitle.setText("日常工作");
        mId = getIntent().getStringExtra("id");
        mUserId = getIntent().getStringExtra("userId");
        mUserType = getIntent().getStringExtra("userType");
        if (TextUtils.isEmpty(mId)) {
            ToastUtils.show("数据有误");
            finish();
        } else {
            getDetailById();
        }
        initViews();
    }

    private void initViews() {
        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;
        });
        mRlvRestoreFiles.setLayoutManager(new GridLayoutManager(mActivity, 4));
        mRlvRestoreFiles.setAdapter(mAddFileAdapter);
        mBtnConfirm.setOnClickListener(v -> doConfirm());
    }

    private boolean checkParams() {
        String restore = mEtRestore.getText().toString().trim();
        if (TextUtils.isEmpty(restore)) {
            ToastUtils.show("请输入回复内容");
            return false;
        }
        return true;
    }

    private RequestBody buildParams() {
        SaveRoutineAcceptBean bean = new SaveRoutineAcceptBean();
        String restore = mEtRestore.getText().toString().trim();
        bean.setContent(restore);
        bean.setUserId(UserLgUtils.getUserId());
        bean.setUserName(UserLgUtils.getName());
        bean.setRoutineWorkId(mBean.getRoutineWorkId());
        bean.setUserType(mUserType);
        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.setFiles(fileId.toString().trim());
        }
        return RequestBody.create(new Gson().toJson(bean), MediaType.parse("application/json; charset=utf-8"));
    }

    private void doConfirm() {
        if (checkParams()) {
            RequestBody body = buildParams();
            ProgressDialog dialog = UIUtil.initDialog(mActivity, "保存中...");
            dialog.show();
            RetrofitManager.getInstance()
                .create(OAApi.class)
                .doSaveAcceptRoutine(mUserId, 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("路径有误,请稍后重试");
                }
            }
        }
    }

    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<>();
        List<String> fileNames = new ArrayList<>();
        for (int i = 0; i < paths.size(); i++) {
            File file = new File(paths.get(i));
            Observable observable = createObservable(file);
            fileNames.add(file.getName());
            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());
                        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 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 void getDetailById() {
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getRoutineDetail(mId, UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<RoutineBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull RoutineBean routineBean) {
                    setDataToView(routineBean);
                }

                @Override
                public void onError(@NonNull Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
    }

    /**
     * 回显数据
     */
    private void setDataToView(RoutineBean routineBean) {
        refreshView(STATE_LOAD_SUCCESS);
        mBean = routineBean;
        mTvName.setText(mBean.getWorkName());
        mTvStartTime.setText(mBean.getWorkCompleteStartTime());
        mTvEndTime.setText(mBean.getWorkCompleteEndTime());
        mTvTl.setText(mBean.getWorkCompleteDay() + "");
        mTvUndertake.setText(mBean.getWorkUndertakerUserName());
        mTvAssisted.setText(mBean.getWorkSponsorUserNames());
        mSwSchedule.setChecked(mBean.getIsSchedule().equals("1"));
        mTvRequest.setText(Html.fromHtml(mBean.getWorkResultReq()));
        mTvRemark.setText(Html.fromHtml(mBean.getWorkRemarks()));
        if (!TextUtils.isEmpty(mBean.getWorkFiles())) {
            List<AddFileBean> files = new ArrayList<>();
            String[] split = mBean.getWorkFiles().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]);
                bean.setFileType(1);
                files.add(bean);
            }
            ShowFileAdapter adapter = new ShowFileAdapter(mActivity, files);
            mRlvFiles.setLayoutManager(new GridLayoutManager(mActivity, 4));
            mRlvFiles.setAdapter(adapter);
        }
    }

    @Override
    protected void doSearchByTitle() {

    }

    @Override
    protected void clearSearch() {

    }
}