package com.rv.plugin.calendar;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.frame.base.url.Constance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.control.WheelView;
import com.rv.component.utils.AppCookie;
import com.rv.component.utils.Cookie;
import com.rv.component.utils.DateUtils;
import com.rv.component.utils.MyUtils;
import com.rv.plugin.calendar.bean.DateInfo;
import com.rv.plugin.calendar.presenter.CalendarPresenter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 日历
 */
@Route(path = Constance.ACTIVITY_URL_CALENDAR)
public class CalendarActivity extends BaseStatusActivity<CalendarPresenter> {

    @BindView(R2.id.v_calendarView)
    CalendarView2 vCalendarView;
    @BindView(R2.id.tv_get_date)
    TextView tvGetDate;
    @BindView(R2.id.tv_get_time)
    TextView tvGetTime;
    @BindView(R2.id.tv_out_date)
    TextView tvOutDate;
    @BindView(R2.id.tv_out_time)
    TextView tvOutTime;
    @BindView(R2.id.wheelView_left)
    WheelView wheelViewLeft;
    @BindView(R2.id.wheelView_right)
    WheelView wheelViewRight;


    private List<DateInfo> listCalendarDay;
    private String s_begDate, s_endDate, s_begTime, s_endTime, begDay, begTime, endDay, endTime;
    private Context context;
    /**
     * 最大的日历期限
     */
    private int MAX_SPAN;
    private int spanIndex = 1;


    private ArrayList<String> timeList = new ArrayList<>();

    @Autowired()
    String begDate;
    @Autowired()
    String endDate;
    @Autowired()
    int begSelected;
    @Autowired()
    int endSelected;

    public static Intent getIntent(Context context) {
        return new Intent(context, CalendarActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        context = this;
        MAX_SPAN = AppCookie.getIntValue(AppCookie.KEY_PRERENT_DAYS, 30);
        begDay = DateUtils.formatDate16(begDate);
        begTime = DateUtils.formatDate17(begDate);
        endDay = DateUtils.formatDate16(endDate);
        endTime = DateUtils.formatDate17(endDate);
        s_begDate = begDay;
        s_endDate = endDay;
        s_begTime = begTime;
        s_endTime = endTime;
        initTime();
        initView();
        tvGetTime.setText(begTime);
        tvGetDate.setText(DateUtils.formatDate(s_begDate) + "\t星期" + MyUtils.getWeek(s_begDate));
        tvOutTime.setText(endTime);
        tvOutDate.setText(DateUtils.formatDate(s_endDate) + "\t星期" + MyUtils.getWeek(s_endDate));

        listCalendarDay = initDate();

        vCalendarView.setOnDayClickListener(new CalendarView2.OnDayClickListener() {
            @Override
            public void inClick(DateInfo date) {
                s_begDate = date.getDay();
                String content = DateUtils.formatDate(s_begDate) + "\t星期" + MyUtils.getWeek(s_begDate);
                tvGetDate.setText(content);

                s_endDate = date.getDay();
                String content2 = DateUtils.formatDate(s_endDate) + "\t星期" + MyUtils.getWeek(s_endDate);
                tvOutDate.setText(content2);
            }

            @Override
            public void outClick(DateInfo date) {
                s_endDate = date.getDay();
                String content = DateUtils.formatDate(s_endDate) + "\t星期" + MyUtils.getWeek(s_endDate);
                tvOutDate.setText(content);
            }
        });

        vCalendarView.setData(listCalendarDay);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_calendar2;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        showTitle(false);
    }

    private void initView() {

        wheelViewLeft.setOffset(1);// 对话框中当前项上面和下面的项数
        wheelViewLeft.setItems(timeList);// 设置数据源
        wheelViewLeft.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                begSelected = selectedIndex;
                s_begTime = item;
                tvGetTime.setText(item);
            }
        });

        wheelViewRight.setOffset(1);// 对话框中当前项上面和下面的项数
        wheelViewRight.setItems(timeList);// 设置数据源
        wheelViewRight.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                s_endTime = item;
                tvOutTime.setText(item);
                endSelected = selectedIndex;
            }
        });

        if (timeList != null) {
            for (int i = 0; i < timeList.size(); i++) {
                if (timeList.get(i).equals(begTime)) {
                    begSelected = i;
                    wheelViewLeft.setSeletion(i);
                    s_begTime = begTime;
                }

                if (timeList.get(i).equals(endTime)) {
                    endSelected = i;
                    wheelViewRight.setSeletion(i);
                    s_endTime = endTime;
                }
            }
        }

    }


    @OnClick({R2.id.iv_close, R2.id.tv_ok})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.iv_close) {
            finish();
        } else if (id == R.id.tv_ok) {
            if (TextUtils.isEmpty(s_begDate)) {
                showToast("请选择租车日期！");
                return;
            }
            if (TextUtils.isEmpty(s_endDate)) {
                showToast("请选择还车日期！");
                return;
            }

            String s = DateUtils.formatDate17(DateUtils.formatDate8(DateUtils.getCurDateTime()));
            if (s_begDate.equals(DateUtils.getCurDate()) && DateUtils.formatDate20(s_begTime) < DateUtils.formatDate20(s)) {
                showToast("取车时刻必须大于等于现在时刻！");
                return;
            }

            if (s_begDate.equals(s_endDate) && DateUtils.formatDate20(s_endTime) <= DateUtils.formatDate20(s_begTime)) {
                showToast("还车时刻要大于取车时刻！");
                return;
            }

            Intent intent = new Intent();
            intent.putExtra("begDate", s_begDate + " " + s_begTime);
            intent.putExtra("endDate", s_endDate + " " + s_endTime);
            setResult(200, intent);
            finish();
        }
    }


    /**
     * 初始化日期
     */
    private List<DateInfo> initDate() {

        List<DateInfo> list = new ArrayList<DateInfo>();
        Date date = new Date();
        int monthIndex = 0;
        while (spanIndex < MAX_SPAN) {
            DateInfo dateInfo = new DateInfo();
            Date curDate = CalendarDateUtil.addDate(date, Calendar.MONTH, monthIndex);
            String yyyy = CalendarDateUtil.formatYear(curDate);
            String mm = CalendarDateUtil.formatMonth(curDate);
            String strMonth = yyyy + "年" + mm + "月";
            dateInfo.setMonth(strMonth);
            dateInfo.setTypeDay(DateInfo.VIEW_TYPE_MONTH_TITLE);
            dateInfo.setCanBeChoose(false);
            list.add(dateInfo);
            //添加当月日期
            setCurMonthDay(curDate, list);
            monthIndex++;
        }
        return list;
    }

    /**
     * 计算出当月的每天信息
     *
     * @param date 当月
     * @return
     */
    private void setCurMonthDay(Date date, List<DateInfo> listDay) {

        String yyyyMM = CalendarDateUtil.formatYearMonth(date);
        // 计算当前月的日期
        Calendar cal = Calendar.getInstance();// 获取日历实例
        cal.setTime(date);
        cal.set(Calendar.DATE, 1);// cal设置当前day为当前月第一天
        int firstWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;// 获取当前月第一天为星期几
        int dayNumInMonth = cal.getActualMaximum(Calendar.DATE);// 获取当前月有多少天

        //月头空格
        addSpaceDay(firstWeek, listDay);

        //正常日期
        for (int j = 1; j <= dayNumInMonth; j++) {

            String strDay = "" + j;
            if (j < 10) {
                strDay = "0" + j;
            }
            String curDay = yyyyMM + "-" + strDay;

            // 农历
            DateInfo day = CalendarDateUtil.getLunar(curDay);
            day.setCanBeChoose(true);
            day.setTypeDay(DateInfo.VIEW_TYPE_DAY);
            day.setDefNongTextColor(context.getResources().getColor(R.color.ri_lhui));
            if (day.isHoliday()) {
                day.setDefNongTextColor(context.getResources().getColor(R.color.ri_dhuang));
            }
            day.setDefNongTextSize(context.getResources().getDimension(R.dimen.sp_12));

            // 如果是初一，则计算前一天是否为除夕
            if (day.getDisplayNongliDate().equals("春节")) {
                for (int k = listDay.size() - 1; k > 0; k++) {
                    DateInfo beforeDay = listDay.get(k);// 前一天
                    if (beforeDay.getTypeDay() == DateInfo.VIEW_TYPE_DAY) {
                        beforeDay.setDisplayNongliDate("除夕");
                        beforeDay.setDefNongTextColor(context.getResources().getColor(R.color.ri_dhuang));
                        break;
                    }
                }
            }

            // 公历
            day.setDefTextColor(context.getResources().getColor(R.color.gren_171413));
            // 周末字体颜色
            if ((j + firstWeek) % 7 == 0 || (j + firstWeek - 1) % 7 == 0) {
                day.setDefTextColor(context.getResources().getColor(R.color.ri_dhong));
            }
            day.setDefTextSize(context.getResources().getDimension(R.dimen.size_12));
            if (CalendarDateUtil.getCurDate().equals(curDay)) {
                strDay = "今天";
                day.setCurDay(true);
                day.setDefTextColor(context.getResources().getColor(R.color.gray_FFB74B));
                day.setDefNongTextColor(context.getResources().getColor(R.color.gray_FFB74B));
                day.setCanBeChoose(true);
            } else if (CalendarDateUtil.compareDateDay(CalendarDateUtil.getCurDate(), curDay) > 0 || spanIndex >= MAX_SPAN) {
                //如果是今天以前
                day.setDefTextColor(context.getResources().getColor(R.color.ri_lhui));
                day.setDefNongTextColor(context.getResources().getColor(R.color.ri_lhui));
                day.setCanBeChoose(false);
            } else {
                spanIndex++;
            }

            if (curDay.equals(begDay)) {
                day.setBeginDay(true);
            }
            if (curDay.equals(endDay)) {
                day.setEndDay(true);
            }
            day.setDay(curDay);
            day.setDisplayDay(strDay);
            day.setBgColor(Color.WHITE);

            listDay.add(day);

        }

        //月尾空格
        int endWeek = 6 - cal.get(Calendar.DAY_OF_WEEK) - 1;// 获取当前月最后一天星期几
        addSpaceDay(endWeek, listDay);
    }

    /**
     * 添加空格日期
     *
     * @param daySize 空格日期数
     * @param listDay 日期列表
     */
    private void addSpaceDay(int daySize, List<DateInfo> listDay) {
        for (int i = 0; i < daySize; i++) {
            DateInfo daySpace = new DateInfo();
            daySpace.setDay("");
            daySpace.setDisplayDay("");
            daySpace.setNongliDate("");
            daySpace.setDisplayNongliDate("");
            daySpace.setTypeDay(DateInfo.VIEW_TYPE_SPACE);
            daySpace.setCanBeChoose(false);
            listDay.add(daySpace);
        }
    }


    @Override
    public void onShowResult(int requestType, BaseBean result) {

    }


    /**
     * 初始化时间数据
     */
    private void initTime() {
        for (int i = 8; i < 20; i++) {
            if (i > 8) {
                timeList.add(String.format("%02d", i) + ":00");
            }
            timeList.add(String.format("%02d", i) + ":30");
        }
    }
}
