package com.tenlionsoft.oamodule.activity.car;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.hjq.toast.ToastUtils;
import com.tenlionsoft.baselib.constant.PathConfig;
import com.tenlionsoft.baselib.constant.TimeConstants;
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.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.ByCarRecordAdapter;
import com.tenlionsoft.oamodule.beans.ByCarRecordBean;
import com.tenlionsoft.oamodule.beans.CarBean;
import com.tenlionsoft.oamodule.net.OAApi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 作者: Adam
 * 日期: 2022年04月13日14:02:20
 * 邮箱: itgaojian@163.com
 * 描述: 车辆选择
 */
@Route(path = PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_CAR)
public class ChooseCarActivity extends BaseActivity implements
    CalendarView.OnCalendarSelectListener,
    CalendarView.OnMonthChangeListener {

    @BindView(R2.id.tv_car)
    TextView mTvCar;
    @BindView(R2.id.tv_year)
    TextView mTvYear;
    @BindView(R2.id.tv_month)
    TextView mTvMonth;
    @BindView(R2.id.tv_day)
    TextView mTvDay;
    @BindView(R2.id.calendarView)
    CalendarView mCalendarView;
    @BindView(R2.id.rlv_content)
    RecyclerView mRlvContent;
    @BindView(R2.id.ll_hint)
    LinearLayout mLlHint;
    @BindView(R2.id.calendarLayout)
    CalendarLayout mCalendarLayout;


    private List<CarBean> mDriverBeanList;
    private CarBean mSelCar;
    private OptionsPickerView<CarBean> mDataSourcePicker;
    private int mCurYear;
    private int mCurMonth;
    private int mCurDay;
    private List<ByCarRecordBean> mCarRecordBeans;
    private ByCarRecordAdapter mAdapter;

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


    @Override
    public void initData() {
        ButterKnife.bind(this);
        mTvBaseTitle.setText("车辆选择");
        initView();
    }

    private void initView() {
        refreshView(STATE_LOAD_SUCCESS);
        mTvCar.setOnClickListener(v -> onShowCar());
        mCalendarView.setOnCalendarSelectListener(this);
        mCalendarView.setOnMonthChangeListener(this);
        mCurYear = mCalendarView.getCurYear();
        mCurMonth = mCalendarView.getCurMonth();
        mCurDay = mCalendarView.getCurDay();

        mTvYear.setText(mCurYear + "");
        mTvMonth.setText(mCurMonth + "");
        mTvDay.setText(mCurDay + "");
        mCarRecordBeans = new ArrayList<>();
        mAdapter = new ByCarRecordAdapter(mActivity, mCarRecordBeans);
        mRlvContent.setLayoutManager(new LinearLayoutManager(mActivity));
        mRlvContent.setAdapter(mAdapter);
        mTvPublish.setVisibility(View.VISIBLE);
        mTvPublish.setText("确定");
        mTvPublish.setOnClickListener(v -> {
            if (mSelCar != null) {
                Intent intent = new Intent();
                intent.putExtra("bean", mSelCar);
                setResult(RESULT_OK, intent);
                finish();
            } else {
                ToastUtils.show("请选择驾驶车辆");
            }
        });
    }

    /**
     * 选择驾驶员
     */
    private void onShowCar() {
        if (mDriverBeanList != null && mDriverBeanList.size() > 0) {
            if (mDataSourcePicker == null) {
                mDataSourcePicker = new OptionsPickerBuilder(mActivity, (o1, o2, o3, v) -> {
                    mSelCar = mDriverBeanList.get(o1);
                    mTvCar.setText(mSelCar.getCarNum());
                    //获取当前人员排班记录
                    getCarRecord(2);
                })
                    .setTitleText("请选择")
                    .setCancelColor(Color.parseColor("#1189FF"))
                    .setSubmitColor(Color.parseColor("#1189FF"))
                    .setTitleColor(Color.parseColor("#1189FF"))
                    .build();
                mDataSourcePicker.setPicker(mDriverBeanList);
            }
            mDataSourcePicker.show();
        } else {
            getCarList();
        }
    }

    /**
     * 获取选定时间内驾驶员排班记录
     */
    private void getCarRecord(int type) {
        ProgressDialog dialog = UIUtil.initDialog(mActivity, "加载中...");
        dialog.show();
        String startTime;
        String endTime;
        if (type == 2) {
            //全月
            int dayEnd = TimeUtils.getDayEnd(mCurYear, mCurMonth);
            startTime = mCurYear + "-" + (mCurMonth < 10 ? ("0" + mCurMonth) : mCurMonth) + "-01";
            endTime = mCurYear + "-" + (mCurMonth < 10 ? ("0" + mCurMonth) : mCurMonth) + "-" + dayEnd;
        } else {
            startTime = mCurYear + "-" + (mCurMonth < 10 ? ("0" + mCurMonth) : mCurMonth) + "-" + (mCurDay < 10 ? "0" + mCurDay : mCurDay);
            endTime = mCurYear + "-" + (mCurMonth < 10 ? ("0" + mCurMonth) : mCurMonth) + "-" + (mCurDay < 10 ? "0" + mCurDay : mCurDay);
        }
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getByCarRecord(mSelCar.getCarId(), startTime, endTime, UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<List<ByCarRecordBean>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull List<ByCarRecordBean> byCarRecordBeans) {
                    LogUtils.e(byCarRecordBeans.size());
                    if (dialog.isShowing()) dialog.dismiss();
                    if (byCarRecordBeans.size() > 0) {
                        mRlvContent.setVisibility(View.VISIBLE);
                        mLlHint.setVisibility(View.GONE);
                        mCarRecordBeans = byCarRecordBeans;
                        mAdapter.setData(mCarRecordBeans);
                    } else {
                        mCarRecordBeans.clear();
                        mRlvContent.setVisibility(View.GONE);
                        mLlHint.setVisibility(View.VISIBLE);
                    }
                    if (type == 2) {
                        buildMonthDay();
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    mLlHint.setVisibility(View.VISIBLE);
                    mRlvContent.setVisibility(View.GONE);
                    if (dialog.isShowing()) dialog.dismiss();
                    ExceptionHandler.handleException(e);
                }

                @Override
                public void onComplete() {

                }
            });
    }

    /**
     * 更新月视图
     */
    private void buildMonthDay() {
        int year = mCalendarView.getSelectedCalendar().getYear();
        int month = mCalendarView.getSelectedCalendar().getMonth();
        mCalendarView.clearSchemeDate();
        Map<String, Calendar> map = new HashMap<>();
        if (mCarRecordBeans != null && mCarRecordBeans.size() > 0) {

            for (int i = 0; i < mCarRecordBeans.size(); i++) {
                ByCarRecordBean bean = mCarRecordBeans.get(i);
                int ofStr = TimeUtils.getDayOfStr(bean.getCarApplyStartTime());
                //计算开始时间和结束时间相差几天
                long timeSpan = TimeUtils.getTimeSpan(bean.getCarApplyEndTime(), bean.getCarApplyStartTime(), TimeConstants.DAY);
                if (timeSpan > 0) {
                    for (int j = 1; j < timeSpan + 1; j++) {
                        String timeSpan1 = TimeUtils.getTimeSpan(bean.getCarApplyStartTime(), j);
                        int dayOfStr = TimeUtils.getDayOfStr(timeSpan1);
                        if (month == TimeUtils.getMonth(timeSpan1)) {
                            map.put(getSchemeCalendar(year, month, dayOfStr, 0xFF40db25, "忙").toString(),
                                getSchemeCalendar(year, month, dayOfStr, 0xFF40db25, "忙"));
                        }
                    }
                }
                int month1 = TimeUtils.getMonth(bean.getCarApplyStartTime());
                if (month == month1) {
                    map.put(getSchemeCalendar(year, month, ofStr, 0xFF40db25, "忙").toString(),
                        getSchemeCalendar(year, month, ofStr, 0xFF40db25, "忙"));
                }
            }

        }
        mCalendarView.setSchemeDate(map);
    }


    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        return calendar;
    }

    /**
     * 获取驾驶员列表
     */
    private void getCarList() {
        ProgressDialog dialog = UIUtil.initDialog(mActivity, "加载中...");
        dialog.show();
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getCarList(UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<List<CarBean>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull List<CarBean> driverBeans) {
                    if (dialog.isShowing()) dialog.dismiss();
                    if (driverBeans.size() > 0) {
                        mDriverBeanList = driverBeans;
                        onShowCar();
                    } else {
                        ToastUtils.show("暂无驾驶员信息,请联系管理员");
                    }
                }

                @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() {

    }

    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

    }

    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
        mCurDay = calendar.getDay();
        mCurYear = calendar.getYear();
        mCurMonth = calendar.getMonth();
        mTvYear.setText(calendar.getYear() + "");
        mTvMonth.setText(calendar.getMonth() + "");
        mTvDay.setText(calendar.getDay() + "");
        if (mSelCar != null) {
            if (isClick) {
                getCarRecord(1);
            } else {
                getCarRecord(2);
            }
        }
    }

    @Override
    public void onMonthChange(int year, int month) {
        int dayEnd = TimeUtils.getDayEnd(year, month);
        String startDate = year + "-" + ((month < 10) ? "0" + month : month) + "-01";
        String endDate = year + "-" + ((month < 10) ? "0" + month : month) + "-" + dayEnd;
        mTvYear.setText(year + "");
        mTvMonth.setText(month + "");
    }
}