package com.tenlionsoft.oamodule.activity.meeting;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.CheckBox;
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.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
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.DicIds;
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.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.adapter.BasePersonShowAdapter;
import com.tenlionsoft.oamodule.beans.ChoosePersonListBean;
import com.tenlionsoft.oamodule.beans.MeetingRoomBean;
import com.tenlionsoft.oamodule.beans.PersonShowBean;
import com.tenlionsoft.oamodule.beans.SaveMeetingBean;
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.android.schedulers.AndroidSchedulers;
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 io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 作者: Adam
 * 日期: 2022年04月14日11:32:05
 * 邮箱: itgaojian@163.com
 * 描述: 会议申请
 */
@Route(path = PathConfig.PATH_MODULE_OA_ACTIVITY_MEETING_APPLY)
public class MeetingApplyActivity extends BaseActivity {

    @BindView(R2.id.et_name)
    EditText mEtName;
    @BindView(R2.id.tv_type)
    TextView mTvType;//会议类型
    @BindView(R2.id.tv_emcee)
    TextView mTvEmcee;//主持人
    @BindView(R2.id.tv_start_time)
    TextView mTvStartTime;//开始时间
    @BindView(R2.id.tv_end_time)
    TextView mTvEndTime;//结束时间
    @BindView(R2.id.rlv_join)
    RecyclerView mRlvJoin;//参会人员
    @BindView(R2.id.et_content)
    EditText mEtContent;//会议内容
    @BindView(R2.id.rlv_files)
    RecyclerView mRlvFiles;//会议文件
    @BindView(R2.id.btn_confirm)
    Button mBtnConfirm;
    @BindView(R2.id.tv_room)
    TextView mTvRoom;
    @BindView(R2.id.cb_notice_msg)
    CheckBox mCbNoticeMsg;
    @BindView(R2.id.cb_notice_email)
    CheckBox mCbNoticeEmail;

    private List<AddFileBean> mFileBeans = new ArrayList<>();
    private AddFileAdapter mAddFileAdapter;
    private String[] fileFilter = new String[]{".doc", ".docx", ".xls", ".xlsx", ".pptx", ".ppt", ".txt", ".pdf"};

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

    private int mFileMax = 9;
    private ChoosePersonListBean mSelEmcee;
    private MeetingRoomBean mSelRoom;
    private List<PersonShowBean> mJoinPerson;
    private BasePersonShowAdapter mPersonShowAdapter;


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

    @Override
    public void initData() {
        ButterKnife.bind(this);
        mTvBaseTitle.setText("会议申请");
        refreshView(STATE_LOAD_SUCCESS);
        initViews();
    }

    private void initViews() {
        mTvType.setOnClickListener(v -> onShowType());
        mTvEmcee.setOnClickListener(v -> ARouter.getInstance()
            .build(PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_PERSON)
            .withBoolean("isSingle", true)
            .navigation(mActivity, 12));//主持人
        mTvStartTime.setOnClickListener(v -> onShowDate(1));
        mTvEndTime.setOnClickListener(v -> {
            String trim = mTvStartTime.getText().toString().trim();
            if (TextUtils.isEmpty(trim)) {
                ToastUtils.show("请选择开始时间");
            } else {
                onShowDate(2);
            }
        });
        mTvRoom.setOnClickListener(v -> ARouter.getInstance()
            .build(PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_MEETING_ROOM)
            .navigation(mActivity, 14));//选择会议室

        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);


        mJoinPerson = new ArrayList<>();
        mJoinPerson.add(new PersonShowBean());
        mPersonShowAdapter = new BasePersonShowAdapter(mActivity, mJoinPerson, 1);
        mRlvJoin.setLayoutManager(new GridLayoutManager(mActivity, 4));
        mRlvJoin.setAdapter(mPersonShowAdapter);
        mPersonShowAdapter.addOnDelListener(this::showConfirmDialog);
        mPersonShowAdapter.addOnItemClickListener(bean -> {
            if (TextUtils.isEmpty(bean.getId())) {
                ARouter.getInstance()
                    .build(PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_PERSON)
                    .withBoolean("isSingle", false)
                    .navigation(mActivity, 13);
            }
        });
        mBtnConfirm.setOnClickListener(v -> doConfirm());
    }

    private void showConfirmDialog(PersonShowBean bean, int i) {
        new AlertDialog.Builder(mActivity)
            .setTitle("提示")
            .setMessage("确定要删除该参会人员吗?")
            .setPositiveButton("确定", (dialog, which) -> {
                mJoinPerson.remove(i);
                mPersonShowAdapter.notifyDataSetChanged();
            })
            .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
            .create()
            .show();
    }

    /**
     * 时间选择
     */
    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));
                    if (span >= 0) {
                        mTvEndTime.setText(TimeUtils.date2String(date));
                    } 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) {
                //主持人
                mSelEmcee = (ChoosePersonListBean) data.getSerializableExtra("bean");
                mTvEmcee.setText(mSelEmcee.getUserName());
            } else if (requestCode == 13) {
                //参会人员
                String name = data.getStringExtra("name");
                String id = data.getStringExtra("id");
                String[] names = name.split(",");
                String[] ids = id.split(",");
                for (int i = 0; i < names.length; i++) {
                    boolean isExist = false;
                    for (PersonShowBean person : mJoinPerson) {
                        if (TextUtils.isEmpty(person.getId())) continue;
                        if (person.getId().equals(ids[i])) {
                            isExist = true;
                            break;
                        }
                    }
                    if (!isExist) {
                        PersonShowBean bean = new PersonShowBean();
                        bean.setName(names[i]);
                        bean.setId(ids[i]);
                        mJoinPerson.add(0, bean);
                    }
                }
                mPersonShowAdapter.notifyDataSetChanged();
            } else if (requestCode == 14) {
                //会议室
                mSelRoom = (MeetingRoomBean) data.getSerializableExtra("bean");
                mTvRoom.setText(mSelRoom.getRoomName());
            } 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 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 {
            getDicListByType(DicIds.DIC_MEETING_TYPE, 1);
        }
    }

    /**
     * 字典
     */
    private void getDicListByType(String pId, int i) {
        ProgressDialog dialog = UIUtil.initDialog(mActivity, "获取中...");
        dialog.show();
        RetrofitManager.getInstance()
            .create(BaseApiService.class)
            .getDictListAllByPid(pId, UserLgUtils.getToken())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<DicBean>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull List<DicBean> beans) {
                    dialog.dismiss();
                    if (beans.size() > 0) {
                        switch (i) {
                            case 1://会议室类型
                                mTyps = beans;
                                onShowType();
                                break;

                        }
                    } else {
                        ToastUtils.show("暂无数据");
                    }
                }

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

                @Override
                public void onComplete() {

                }
            });
    }

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

                    }
                });
        }
    }

    private RequestBody buildParams() {
        SaveMeetingBean bean = new SaveMeetingBean();
        String name = mEtName.getText().toString().trim();
        bean.setMeetingTitle(name);
        bean.setMeetingType(mSelType.getDataId());
        bean.setMeetingHostUserId(mSelEmcee.getUserId());
        bean.setMeetingHostUserName(mSelEmcee.getUserName());
        bean.setMeetingStartTime(mTvStartTime.getText().toString().trim());
        bean.setMeetingEndTime(mTvEndTime.getText().toString().trim());
        bean.setMeetingRoomId(mSelRoom.getRoomId());
        bean.setMeetingRoomName(mSelRoom.getRoomName());
        bean.setMeetingRoomType(mSelRoom.getRoomType());
        bean.setMeetingContent(mEtContent.getText().toString().trim());
        StringBuilder notice = new StringBuilder();
        if (mCbNoticeMsg.isChecked()) {
            notice.append("1").append(",");
        }
        if (mCbNoticeEmail.isChecked()) {
            notice.append("2");
        }
        if (!TextUtils.isEmpty(notice.toString().trim())) {
            bean.setMeetingNoticeType(notice.toString().trim());
        }
        StringBuilder ids = new StringBuilder();
        StringBuilder names = new StringBuilder();
        for (PersonShowBean person : mJoinPerson) {
            if (TextUtils.isEmpty(person.getId())) continue;
            ids.append(person.getId()).append("_");
            names.append(person.getName()).append(",");
        }
        if (ids.toString().endsWith("_")) {
            String id = ids.substring(0, ids.toString().length() - 1);
            String jname = names.substring(0, names.toString().length() - 1);
            bean.setMeetingUserNames(jname);
            bean.setMeetingUserIds(id);
        }
        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.setMeetingFile(fileId.toString().trim());
        }
        LogUtils.e(bean);
        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;
        }
        if (mSelEmcee == null) {
            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;
        }
        if (mSelRoom == null) {
            ToastUtils.show("请选择要使用的会议室");
            return false;
        }
        if (mJoinPerson.size() <= 1) {
            ToastUtils.show("请选择参会人员");
            return false;
        }
        String contetn = mEtContent.getText().toString().trim();
        if (TextUtils.isEmpty(contetn)) {
            ToastUtils.show("请输入会议内容");
            return false;
        }
        return true;
    }

    @Override
    protected void doSearchByTitle() {

    }

    @Override
    protected void clearSearch() {

    }
}