package com.tenlionsoft.oamodule.activity.supervise;

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.tenlionsoft.baselib.constant.PathConfig;
import com.tenlionsoft.baselib.core.beans.BaseSuccessBean;
import com.tenlionsoft.baselib.core.retrofit_net.RetrofitManager;
import com.tenlionsoft.baselib.core.retrofit_net.conver.RxTransformer;
import com.tenlionsoft.baselib.core.widget.base.BaseActivity;
import com.tenlionsoft.baselib.utils.ExceptionHandler;
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.SaveSuperviseBean;
import com.tenlionsoft.oamodule.beans.SuperviseRelevanceOptionsListBean;
import com.tenlionsoft.oamodule.beans.SuperviseTypeBean;
import com.tenlionsoft.oamodule.net.OAApi;

import java.util.List;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 作者: Adam
 * 日期: 2022年04月18日15:50:08
 * 邮箱: itgaojian@163.com
 * 描述: 发起督办
 */
@Route(path = PathConfig.PATH_MODULE_OA_ACTIVITY_APPLY_SUPERVISE)
public class ApplySuperviseActivity extends BaseActivity {


    @BindView(R2.id.et_name)
    EditText mEtName;
    @BindView(R2.id.tv_type)
    TextView mTvType;
    @BindView(R2.id.tv_end_time)
    TextView mTvEndTime;
    @BindView(R2.id.tv_relevance)
    TextView mTvRelevance;
    @BindView(R2.id.tv_users)
    TextView mTvUsers;
    @BindView(R2.id.et_request)
    EditText mEtRequest;
    @BindView(R2.id.tv_request_num)
    TextView mTvRequestNum;
    @BindView(R2.id.cb_notice_msg)
    CheckBox mCbNoticeMsg;
    @BindView(R2.id.cb_notice_email)
    CheckBox mCbNoticeEmail;
    @BindView(R2.id.btn_confirm)
    Button mBtnConfirm;


    private OptionsPickerView<SuperviseTypeBean> mTypePicker;
    private List<SuperviseTypeBean> mTypes;
    private SuperviseTypeBean mSelType;
    private String mIds;
    private String mUserNames;
    private SuperviseRelevanceOptionsListBean.RowsBean mSelRelevance;

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

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

    /**
     * 初始化页面
     */
    private void initViews() {
        mTvType.setOnClickListener(v -> onShowType());
        mTvEndTime.setOnClickListener(v -> onShowDate());
        mTvRelevance.setOnClickListener(v -> {
            if (mSelType == null) {
                ToastUtils.show("请先选择督办类型");
            } else {
                ARouter.getInstance()
                    .build(PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_RELEVANCE_OPTIONS)
                    .withBoolean("isSingle", true)
                    .withString("id", mSelType.getTypeCode())
                    .navigation(mActivity, 12);
            }
        });
        mTvUsers.setOnClickListener(v -> ARouter.getInstance()
            .build(PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_PERSON)
            .withBoolean("isSingle", false)
            .navigation(mActivity, 13));
        mBtnConfirm.setOnClickListener(v -> doConfirm());
    }

    /**
     * 督办类型
     */
    private void onShowType() {
        hideSoftKeyboard();
        if (mTypes != null && mTypes.size() > 0) {
            if (mTypePicker == null) {
                mTypePicker = new OptionsPickerBuilder(mActivity, (o1, o2, o3, v) -> {
                    mSelType = mTypes.get(o1);
                    mTvType.setText(mSelType.getTypeName());

                })
                    .setTitleText("请选择")
                    .setCancelColor(Color.parseColor("#1189FF"))
                    .setSubmitColor(Color.parseColor("#1189FF"))
                    .setTitleColor(Color.parseColor("#1189FF"))
                    .build();
                mTypePicker.setPicker(mTypes);
            }
            mTypePicker.show();
        } else {
            getSuperviseTypeList();
        }
    }

    private void getSuperviseTypeList() {
        ProgressDialog dialog = UIUtil.initDialog(mActivity, "加载中...");
        dialog.show();
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getSuperviseTypeList(UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<List<SuperviseTypeBean>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull List<SuperviseTypeBean> superviseTypeBeans) {
                    if (dialog.isShowing()) dialog.dismiss();
                    if (superviseTypeBeans.size() > 0) {
                        mTypes = superviseTypeBeans;
                        onShowType();
                    } else {
                        ToastUtils.show("暂无数据");
                    }
                }

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

                @Override
                public void onComplete() {

                }
            });
    }

    private void onShowDate() {
        TimePickerView mTimePickerView = new TimePickerBuilder(mActivity, (date, v) -> {
            //判断时间大小
            mTvEndTime.setText(TimeUtils.date2String(date));
        })
            .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 @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 12) {
                //关联事项
                mSelRelevance = (SuperviseRelevanceOptionsListBean.RowsBean) data.getSerializableExtra("bean");
                mTvRelevance.setText(mSelRelevance.getDataTitle());
            } else if (requestCode == 13) {
                //督办人员
                mIds = data.getStringExtra("id");
                mUserNames = data.getStringExtra("name");
                mTvUsers.setText(mUserNames);
            }
        }
    }


    private void doConfirm() {
        if (checkParams()) {
            ProgressDialog dialog = UIUtil.initDialog(mActivity, "提交中...");
            dialog.show();
            RequestBody body = buildParams();
            RetrofitManager.getInstance()
                .create(OAApi.class)
                .doSaveSupervise(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 boolean checkParams() {
        String name = mEtName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            ToastUtils.show("请输入督办名称");
            return false;
        }
        String endTime = mTvEndTime.getText().toString().trim();
        if (TextUtils.isEmpty(endTime)) {
            ToastUtils.show("请选择完成时限");
            return false;
        }
        if (TextUtils.isEmpty(mIds)) {
            ToastUtils.show("请选择督办人员");
            return false;
        }
        String request = mEtRequest.getText().toString().trim();
        if (TextUtils.isEmpty(request)) {
            ToastUtils.show("请输入督办内容");
            return false;
        }
        return true;
    }

    private RequestBody buildParams() {
        SaveSuperviseBean bean = new SaveSuperviseBean();
        String name = mEtName.getText().toString().trim();
        bean.setOverseeTitle(name);
        if (mSelType != null) {
            bean.setOverseeType(mSelType.getOverseeTypeId());
        }
        String endTime = mTvEndTime.getText().toString().trim();
        bean.setOverseeCompleteTime(endTime);
        if (mSelRelevance != null) {
            bean.setOverseeItemId(mSelRelevance.getDataId());
            bean.setOverseeItemName(mSelRelevance.getDataTitle());
        }
        bean.setOverseeUserIds(mIds.replace(",", "_"));
        bean.setOverseeUserNames(mUserNames);
        String reqeust = mEtRequest.getText().toString().trim();
        bean.setOverseeContent(reqeust);
        StringBuilder notice = new StringBuilder();
        if (mCbNoticeMsg.isChecked()) {
            notice.append("1").append(",");
        }
        if (mCbNoticeEmail.isChecked()) {
            notice.append("2");
        }
        if (!TextUtils.isEmpty(notice.toString().trim())) {
            bean.setOverseeNoticeType(notice.toString().trim());
        }
        return RequestBody.create(new Gson().toJson(bean), MediaType.parse("application/json; charset=utf-8"));
    }

    @Override
    protected void doSearchByTitle() {

    }

    @Override
    protected void clearSearch() {

    }
}