package com.tenlionsoft.oamodule.activity.routine;

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.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
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.constant.TimeConstants;
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.TimeUtils;
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.ChoosePersonListBean;
import com.tenlionsoft.oamodule.beans.SaveRoutineBean;
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 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月15日16:14:46
 * 邮箱: itgaojian@163.com
 * 描述: 发起日常工作
 */
@Route(path = PathConfig.PATH_MODULE_OA_ACTIVITY_ROUTINE_WORK_MINE_LAUNCH_ADD)
public class ApplyRoutineWorkActivity extends BaseActivity {


    @BindView(R2.id.et_name)
    EditText mEtName;
    @BindView(R2.id.tv_start_time)
    TextView mTvStartTime;
    @BindView(R2.id.tv_end_time)
    TextView mTvEndTime;
    @BindView(R2.id.et_tl)
    EditText mEtTl;
    @BindView(R2.id.tv_undertake)
    TextView mTvUndertake;//承办人
    @BindView(R2.id.tv_assisted)
    TextView mTvAssisted;//协办人
    @BindView(R2.id.sw_schedule)
    SwitchCompat mSwSchedule;
    @BindView(R2.id.et_request)
    EditText mEtRequest;
    @BindView(R2.id.tv_request_num)
    TextView mTvRequestNum;
    @BindView(R2.id.et_remark)
    EditText mEtRemark;
    @BindView(R2.id.tv_remark_num)
    TextView mTvRemarkNum;
    @BindView(R2.id.rlv_files)
    RecyclerView mRlvFiles;
    @BindView(R2.id.btn_confirm)
    Button mBtnConfirm;

    private int isWriteSchedule = 0;
    private int mFileMax = 9;
    private List<AddFileBean> mFileBeans = new ArrayList<>();
    private AddFileAdapter mAddFileAdapter;
    private String[] fileFilter = new String[]{".doc", ".docx", ".xls", ".xlsx", ".pptx", ".ppt", ".txt", ".pdf"};
    private ChoosePersonListBean mSelUndertake;
    private String mIds;

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

    @Override
    public void initData() {
        ButterKnife.bind(this);
        mTvBaseTitle.setText("发起工作");
        refreshView(STATE_LOAD_SUCCESS);
        initViews();
    }

    /**
     * 初始化页面
     */
    private void initViews() {
        mTvStartTime.setOnClickListener(v -> onShowDate(1));
        mTvEndTime.setOnClickListener(v -> onShowDate(2));

        mTvUndertake.setOnClickListener(v -> ARouter.getInstance()
            .build(PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_PERSON)
            .withBoolean("isSingle", true)
            .navigation(mActivity, 12));//承办人

        mTvAssisted.setOnClickListener(v -> ARouter.getInstance()
            .build(PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_PERSON)
            .withBoolean("isSingle", false)
            .navigation(mActivity, 13));//协办人
        mSwSchedule.setOnCheckedChangeListener((buttonView, isChecked) -> isWriteSchedule = isChecked ? 1 : 0);
        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 onShowDate(int i) {
        TimePickerView mTimePickerView = new TimePickerBuilder(mActivity, (date, v) -> {
            switch (i) {
                case 1:
                    mTvStartTime.setText(TimeUtils.date2String(date));
                    break;
                case 2:
                    //判断时间大小
                    String start = mTvStartTime.getText().toString().trim();
                    int span = TimeUtils.compareDate(date, TimeUtils.string2Date(start));
                    long timeSpan = TimeUtils.getTimeSpan(TimeUtils.dateToString2(date), start, TimeConstants.DAY);
                    if (span >= 0) {
                        mTvEndTime.setText(TimeUtils.date2String(date));
                        mEtTl.setText(timeSpan + "");
                    } else {
                        ToastUtils.show("结束时间须大于开始时间");
                    }
                    break;
            }
        })
            .setTitleText("请选时间")
            .setCancelColor(Color.parseColor("#1189FF"))
            .setSubmitColor(Color.parseColor("#1189FF"))
            .isDialog(false)
            .setType(new boolean[]{true, true, true, true, true, true})
            .setTitleColor(Color.parseColor("#1189FF"))
            .build();
        mTimePickerView.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 12) {
                //承办人
                mSelUndertake = (ChoosePersonListBean) data.getSerializableExtra("bean");
                mTvUndertake.setText(mSelUndertake.getUserName());
            } else if (requestCode == 13) {
                //协办人
                mIds = data.getStringExtra("id");
                String name = data.getStringExtra("name");
                mTvAssisted.setText(name);
            } else 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<>();
        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 boolean checkParams() {
        String name = mEtName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            ToastUtils.show("请输入工作名称");
            return false;
        }
        String startTime = mTvStartTime.getText().toString().trim();
        if (TextUtils.isEmpty(startTime)) {
            ToastUtils.show("请输入开始时间");
            return false;
        }
        String endTime = mTvEndTime.getText().toString().trim();
        if (TextUtils.isEmpty(endTime)) {
            ToastUtils.show("请输入结束时间");
            return false;
        }
        String tl = mEtTl.getText().toString().trim();
        if (TextUtils.isEmpty(tl)) {
            ToastUtils.show("请输入完成时限");
            return false;
        }
        if (mSelUndertake == null) {
            ToastUtils.show("请选择承办人");
            return false;
        }
        String require = mEtRequest.getText().toString().trim();
        if (TextUtils.isEmpty(require)) {
            ToastUtils.show("请输入结果要求");
            return false;
        }
        return true;
    }

    private RequestBody buildParams() {
        SaveRoutineBean bean = new SaveRoutineBean();
        bean.setWorkName(mEtName.getText().toString().trim());
        bean.setWorkCompleteStartTime(mTvStartTime.getText().toString().trim());
        bean.setWorkCompleteEndTime(mTvEndTime.getText().toString().trim());
        bean.setWorkCompleteDay(Integer.parseInt(mEtTl.getText().toString().trim()));
        bean.setWorkUndertakerUserId(mSelUndertake.getUserId());
        bean.setWorkUndertakerUserName(mSelUndertake.getUserName());
        if (!TextUtils.isEmpty(mIds)) {
            bean.setWorkSponsorUserIds(mIds.replace(",", "_"));
            bean.setWorkSponsorUserNames(mTvAssisted.getText().toString().trim());
        }
        bean.setIsSchedule(isWriteSchedule + "");
        bean.setWorkResultReq(mEtRequest.getText().toString().trim());
        String remark = mEtRemark.getText().toString().trim();
        if (!TextUtils.isEmpty(remark)) {
            bean.setWorkRemarks(remark);
        }
        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.setWorkFiles(fileId.toString().trim());
        }
        return RequestBody.create(new Gson().toJson(bean), MediaType.parse("application/json; charset=utf-8"));
    }

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

    }
}