package com.tenlionsoft.oamodule.activity.car;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
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.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.google.gson.reflect.TypeToken;
import com.hjq.toast.ToastUtils;
import com.tenlionsoft.baselib.constant.PathConfig;
import com.tenlionsoft.baselib.core.beans.BaseSuccessBean;
import com.tenlionsoft.baselib.core.beans.UserInfoBean;
import com.tenlionsoft.baselib.core.retrofit_net.RetrofitManager;
import com.tenlionsoft.baselib.core.retrofit_net.conver.RxTransformer;
import com.tenlionsoft.baselib.core.widget.AstrictLengthFilter;
import com.tenlionsoft.baselib.core.widget.base.BaseActivity;
import com.tenlionsoft.baselib.interfaces.TextChange;
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.CarBean;
import com.tenlionsoft.oamodule.beans.DriverBean;
import com.tenlionsoft.oamodule.beans.SaveByCarBean;
import com.tenlionsoft.oamodule.net.OAApi;

import java.util.ArrayList;

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月12日18:08:17
 * 邮箱: itgaojian@163.com
 * 描述: 用车申请
 */
@Route(path = PathConfig.PATH_MODULE_OA_ACTIVITY_CAR_ADD)
public class ByCarAddActivity extends BaseActivity {


    @BindView(R2.id.et_name)
    EditText mEtName;//姓名
    @BindView(R2.id.tv_dept)
    TextView mTvDept;//部门
    @BindView(R2.id.tv_apply_date)
    TextView mTvApplyDate;
    @BindView(R2.id.tv_fare)
    TextView mTvFare;//乘车人
    @BindView(R2.id.et_reason)
    EditText mEtReason;//原由
    @BindView(R2.id.tv_hint_num)
    TextView mTvHintNum;//原由字数
    @BindView(R2.id.tv_start_date)
    TextView mTvStartDate;//开始日期
    @BindView(R2.id.tv_end_date)
    TextView mTvEndDate;//结束日期
    @BindView(R2.id.tv_car)
    TextView mTvCar;//车辆
    @BindView(R2.id.tv_driver)
    TextView mTvDriver;//司机
    @BindView(R2.id.et_before)
    EditText mEtBefore;//前里程
    @BindView(R2.id.et_after)
    EditText mEtAfter;//后里程
    @BindView(R2.id.et_mileage)
    EditText mEtMileage;//里程
    @BindView(R2.id.et_remark)
    EditText mEtRemark;//备注
    @BindView(R2.id.btn_confirm)
    Button mBtnConfirm;
    @BindView(R2.id.et_leave)
    EditText mEtLeave;
    @BindView(R2.id.et_des)
    EditText mEtDes;
    private DriverBean mSelDriver;
    private CarBean mSelCar;
    private ArrayList<UserInfoBean.DepartmentsBean> mDepBeans;
    private OptionsPickerView mDeptPicker;
    private UserInfoBean.DepartmentsBean mSelDept;
    private final int mReasonMax = 140;
    private String mSelFare;

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

    @Override
    public void initData() {
        ButterKnife.bind(this);
        mTvBaseTitle.setText("用车申请");
        refreshView(STATE_LOAD_SUCCESS);
        initView();
    }

    private void initView() {
        mTvApplyDate.setText(TimeUtils.getCurrentTime());
        mEtName.setText(UserLgUtils.getName());
        String userDeptId = UserLgUtils.getUserDeptId();
        Gson gson = new Gson();
        mDepBeans = gson.fromJson(userDeptId, new TypeToken<ArrayList<UserInfoBean.DepartmentsBean>>() {
        }.getType());
        if (mDepBeans != null && mDepBeans.size() > 0) {
            mTvDept.setText(mDepBeans.get(0).getDepartmentName());
            mSelDept = mDepBeans.get(0);
        }
        mTvApplyDate.setOnClickListener(v -> onShowDate(3));
        mTvStartDate.setOnClickListener(v -> onShowDate(1));
        mTvEndDate.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(mTvStartDate.getText().toString().trim())) {
                onShowDate(2);
            } else {
                ToastUtils.show("请先选择开始时间");
            }
        });
        mTvFare.setOnClickListener(v -> ARouter.getInstance()
            .build(PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_PERSON)
            .withBoolean("isSingle", false)
            .navigation(mActivity, 12));//乘车人
        mTvDriver.setOnClickListener(v -> ARouter.getInstance()
            .build(PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_DRIVER)
            .navigation(mActivity, 13));//驾驶员
        mTvCar.setOnClickListener(v -> ARouter.getInstance()
            .build(PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_CAR)
            .navigation(mActivity, 14));//车辆
        mTvDept.setOnClickListener(v -> onShowDept());
        mTvHintNum.setText("0/" + mReasonMax);
        mEtReason.addTextChangedListener(new TextChange() {
            @Override
            public void afterTextChanged(Editable s) {
                int length = s.toString().length();
                mTvHintNum.setText(length + "/" + mReasonMax);
            }
        });
        mEtAfter.addTextChangedListener(new TextChange() {
            @Override
            public void afterTextChanged(Editable s) {
                String num = s.toString().trim();
                if (!TextUtils.isEmpty(num)) {
                    float v = Float.parseFloat(num);
                    String after = mEtBefore.getText().toString().trim();
                    if (!TextUtils.isEmpty(after)) {
                        float af = Float.parseFloat(after);
                        float dis = v - af;
                        mEtMileage.setText(dis + "");
                    } else {
                        mEtMileage.setText(after);
                    }
                }
            }
        });//自动计算行驶里程
        //限制事由输入文字长度
        AstrictLengthFilter filter = new AstrictLengthFilter(mReasonMax);
        mEtReason.setFilters(new InputFilter[]{filter});
        mBtnConfirm.setOnClickListener(v -> doConfirm());
    }

    private void onShowDept() {
        if (mDepBeans != null && mDepBeans.size() > 0) {
            if (mDeptPicker == null) {
                mDeptPicker = new OptionsPickerBuilder(mActivity, (o1, o2, o3, v) -> {
                    mSelDept = mDepBeans.get(o1);
                    mTvDept.setText(mSelDept.getDepartmentName());
                })
                    .setTitleText("请选择")
                    .setCancelColor(Color.parseColor("#1189FF"))
                    .setSubmitColor(Color.parseColor("#1189FF"))
                    .setTitleColor(Color.parseColor("#1189FF"))
                    .build();
                mDeptPicker.setPicker(mDepBeans);
            }
            mDeptPicker.show();
        } else {
            ToastUtils.show("您暂无部门信息,请联系管理员");
        }
    }

    private void onShowDate(int type) {
        TimePickerView mTimePickerView = new TimePickerBuilder(mActivity, (date, v) -> {
            switch (type) {
                case 1:
                    mTvStartDate.setText(TimeUtils.date2String(date));
                    break;
                case 2:
                    //判断时间大小
                    String start = mTvStartDate.getText().toString().trim();
                    int i = TimeUtils.compareDate(date, TimeUtils.string2Date(start));
                    if (i >= 0) {
                        mTvEndDate.setText(TimeUtils.date2String(date));
                    } else {
                        ToastUtils.show("结束时间须大于开始时间");
                    }
                    break;
                case 3:
                    mTvApplyDate.setText(TimeUtils.date2String(date));
                    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) {
                //乘车人
                String name = data.getStringExtra("name");
                mSelFare = data.getStringExtra("id");
                mTvFare.setText(name);
            } else if (13 == requestCode) {
                //驾驶人
                mSelDriver = (DriverBean) data.getSerializableExtra("bean");
                mTvDriver.setText(mSelDriver.getDriverName());
            } else if (14 == requestCode) {
                //车辆
                mSelCar = (CarBean) data.getSerializableExtra("bean");
                mTvCar.setText(mSelCar.getCarNum());
            }
        }
    }


    private boolean checkParams() {
        if (mSelDept == null) {
            ToastUtils.show("请选择部门");
            return false;
        }
        String applyTime = mTvApplyDate.getText().toString().trim();
        if (TextUtils.isEmpty(applyTime)) {
            ToastUtils.show("请选择申请时间");
            return false;
        }
        if (TextUtils.isEmpty(mSelFare)) {
            ToastUtils.show("请选择乘车人");
            return false;
        }
        String reason = mEtReason.getText().toString().trim();
        if (TextUtils.isEmpty(reason)) {
            ToastUtils.show("请输入用车事由");
            return false;
        }
        String startTime = mTvStartDate.getText().toString().trim();
        if (TextUtils.isEmpty(startTime)) {
            ToastUtils.show("请选择开始时间");
            return false;
        }
        String endTime = mTvEndDate.getText().toString().trim();
        if (TextUtils.isEmpty(endTime)) {
            ToastUtils.show("请选择结束时间");
            return false;
        }
        String leave = mEtLeave.getText().toString().trim();
        if (TextUtils.isEmpty(leave)) {
            ToastUtils.show("请输入出发地址");
            return false;
        }
        String des = mEtDes.getText().toString().trim();
        if (TextUtils.isEmpty(des)) {
            ToastUtils.show("请输入目的地址");
            return false;
        }
        if (mSelCar == null) {
            ToastUtils.show("请选择使用车辆");
            return false;
        }
        if (mSelDriver == null) {
            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)
                .doSaveByCar(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() {
        SaveByCarBean bean = new SaveByCarBean();
        bean.setCarApplyUserId(UserLgUtils.getUserId());
        bean.setCarApplyUserName(UserLgUtils.getName());
        bean.setCarApplyUserDeptId(mSelDept.getDepartmentId());
        bean.setCarApplyUserDeptName(mSelDept.getDepartmentName());
        bean.setCarApplyPassengerIds(mSelFare.replace(",", "_"));
        bean.setCarApplyPassengerNames(mTvFare.getText().toString().trim());
        bean.setCarApplyReason(mEtReason.getText().toString().trim());
        bean.setCarApplyStartTime(mTvStartDate.getText().toString().trim());
        bean.setCarApplyEndTime(mTvEndDate.getText().toString().trim());
        bean.setCarApplyStartPlace(mEtLeave.getText().toString().trim());
        bean.setCarApplyEndPlace(mEtDes.getText().toString().trim());
        bean.setCarApplyCarId(mSelCar.getCarId());
        bean.setCarApplyCarName(mSelCar.getCarName());
        bean.setCarApplyDriverId(mSelDriver.getDriverId());
        bean.setCarApplyDriverName(mSelDriver.getDriverName());

        String before = mEtBefore.getText().toString().trim();
        if (!TextUtils.isEmpty(before)) {
            bean.setCarApplyStartMileage(Float.parseFloat(before));
        }//用车前里程

        String after = mEtAfter.getText().toString().trim();
        if (!TextUtils.isEmpty(after)) {
            bean.setCarApplyEndMileage(Float.parseFloat(after));
        }
        String mileage = mEtMileage.getText().toString().trim();
        if (!TextUtils.isEmpty(mileage)) {
            bean.setCarApplyMileage(Float.parseFloat(mileage));
        }
        String remark = mEtRemark.getText().toString().trim();
        if (!TextUtils.isEmpty(remark)) {
            bean.setCarApplyRemark(remark);
        }
        Gson gson = new Gson();
        String obj = gson.toJson(bean);
        return RequestBody.create(obj, MediaType.parse("application/json; charset=utf-8"));
    }

    @Override
    protected void doSearchByTitle() {

    }

    @Override
    protected void clearSearch() {

    }
}