package com.tenlionsoft.oamodule.activity.meeting;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
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.DicIds;
import com.tenlionsoft.baselib.constant.PathConfig;
import com.tenlionsoft.baselib.constant.TimeConstants;
import com.tenlionsoft.baselib.core.beans.DicBean;
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.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.adapter.MeetingRoomRecordAdapter;
import com.tenlionsoft.oamodule.beans.MeetingRoomBean;
import com.tenlionsoft.oamodule.beans.MeetingRoomRecordBean;
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.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * 作者: Adam
 * 日期: 2022年04月14日14:34:21
 * 邮箱: itgaojian@163.com
 * 描述: 选择会议室
 */
@Route(path = PathConfig.PATH_MODULE_OA_ACTIVITY_SEL_MEETING_ROOM)
public class ChooseMeetingRoomActivity extends BaseActivity implements
    CalendarView.OnCalendarSelectListener,
    CalendarView.OnMonthChangeListener {


    @BindView(R2.id.tv_type)
    TextView mTvType;
    @BindView(R2.id.tv_room)
    TextView mTvRoom;
    @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.rl_record)
    RelativeLayout mRlRecord;
    @BindView(R2.id.calendarLayout)
    CalendarLayout mCalendarLayout;


    private int mCurYear;
    private int mCurMonth;
    private int mCurDay;
    private OptionsPickerView<DicBean> mTypePicker;
    private List<DicBean> mRoomTypes;
    private DicBean mSelType;

    private OptionsPickerView<MeetingRoomBean> mRoomPicker;
    private List<MeetingRoomBean> mRooms;
    private MeetingRoomBean mSelRoom;

    private List<MeetingRoomRecordBean> mRoomRecords;
    private MeetingRoomRecordAdapter mAdapter;

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

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

    private void initView() {
        refreshView(STATE_LOAD_SUCCESS);
        mTvType.setOnClickListener(v -> onShowType());
        mTvRoom.setOnClickListener(v -> {
            if (mSelType == null) {
                ToastUtils.show("请选择会议室类型");
            } else {
                onShowRoom();
            }
        });
        mCalendarView.setOnCalendarSelectListener(this);
        mCalendarView.setOnMonthChangeListener(this);
        mCurYear = mCalendarView.getCurYear();
        mCurMonth = mCalendarView.getCurMonth();
        mCurDay = mCalendarView.getCurDay();

        mTvYear.setText(mCurYear + "");
        mTvMonth.setText(mCurMonth + "");
        mTvDay.setText(mCurDay + "");


        mTvPublish.setVisibility(View.VISIBLE);
        mTvPublish.setText("确定");
        mTvPublish.setOnClickListener(v -> {
            if (mSelRoom != null) {
                Intent intent = new Intent();
                intent.putExtra("bean", mSelRoom);
                setResult(RESULT_OK, intent);
                finish();
            } else {
                ToastUtils.show("请选择会议室");
            }
        });


        mRoomRecords = new ArrayList<>();
        mAdapter = new MeetingRoomRecordAdapter(mActivity, mRoomRecords);
        mRlvContent.setLayoutManager(new LinearLayoutManager(mActivity));
        mRlvContent.setAdapter(mAdapter);
    }

    /**
     * 选择会议室
     */
    private void onShowRoom() {
        hideSoftKeyboard();
        if (mRooms != null && mRooms.size() > 0) {
            if (mRoomPicker == null) {
                mRoomPicker = new OptionsPickerBuilder(mActivity, (o1, o2, o3, v) -> {
                    mSelRoom = mRooms.get(o1);
                    mTvRoom.setText(mSelRoom.getRoomName());
                    getRoomRecord(2);
                })
                    .setTitleText("请选择")
                    .setCancelColor(Color.parseColor("#1189FF"))
                    .setSubmitColor(Color.parseColor("#1189FF"))
                    .setTitleColor(Color.parseColor("#1189FF"))
                    .build();
                mRoomPicker.setPicker(mRooms);
            }
            mRoomPicker.show();
        } else {
            getRooms();
        }
    }

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

                }

                @Override
                public void onNext(@NonNull List<MeetingRoomBean> meetingRoomBeans) {
                    if (dialog.isShowing()) dialog.dismiss();
                    if (meetingRoomBeans.size() > 0) {
                        mRooms = meetingRoomBeans;
                        onShowRoom();
                    } else {
                        ToastUtils.show("无会议室信息");
                    }
                }

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

                @Override
                public void onComplete() {

                }
            });
    }

    /**
     * 选择会议室类型
     */
    private void onShowType() {
        hideSoftKeyboard();
        if (mRoomTypes != null && mRoomTypes.size() > 0) {
            if (mTypePicker == null) {
                mTypePicker = new OptionsPickerBuilder(mActivity, (o1, o2, o3, v) -> {
                    mSelType = mRoomTypes.get(o1);
                    mTvType.setText(mSelType.getDataName());

                    mSelRoom = null;
                    mTvRoom.setText("");
                    mRoomRecords.clear();
                    mCalendarView.clearSchemeDate();
                })
                    .setTitleText("请选择")
                    .setCancelColor(Color.parseColor("#1189FF"))
                    .setSubmitColor(Color.parseColor("#1189FF"))
                    .setTitleColor(Color.parseColor("#1189FF"))
                    .build();
                mTypePicker.setPicker(mRoomTypes);
            }
            mTypePicker.show();
        } else {
            getDicListByType(DicIds.DIC_MEETING_ROOM_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://会议室类型
                                mRoomTypes = beans;
                                onShowType();
                                break;

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

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

                @Override
                public void onComplete() {

                }
            });
    }

    private void getRoomRecord(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)
            .getMeetingRoomRecordList(mSelRoom.getRoomId(), startTime, endTime, UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<List<MeetingRoomRecordBean>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull List<MeetingRoomRecordBean> beans) {
                    if (dialog.isShowing()) dialog.dismiss();
                    if (beans.size() > 0) {
                        mRlvContent.setVisibility(View.VISIBLE);
                        mLlHint.setVisibility(View.GONE);
                        mRoomRecords = beans;
                        mAdapter.setData(mRoomRecords);
                    } else {
                        mRoomRecords.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 (mRoomRecords != null && mRoomRecords.size() > 0) {

            for (int i = 0; i < mRoomRecords.size(); i++) {
                MeetingRoomRecordBean bean = mRoomRecords.get(i);
                int ofStr = TimeUtils.getDayOfStr(bean.getMeetingStartTime());
                //计算开始时间和结束时间相差几天
                long timeSpan = TimeUtils.getTimeSpan(bean.getMeetingEndTime(), bean.getMeetingStartTime(), TimeConstants.DAY);
                if (timeSpan > 0) {
                    for (int j = 1; j < timeSpan + 1; j++) {
                        String timeSpan1 = TimeUtils.getTimeSpan(bean.getMeetingStartTime(), 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.getMeetingStartTime());
                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;
    }

    @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 (mSelRoom != null) {
            if (isClick) {
                getRoomRecord(1);
            } else {
                getRoomRecord(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 + "");
    }
}