package com.sheep.gamegroup.view.fragment;

import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.haibin.calendarviewproject.custom.CustomMonthView;
import com.haibin.calendarviewproject.custom.CustomWeekView;
import com.sheep.gamegroup.model.api.ApiService;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.FootprintCountRespons;
import com.sheep.gamegroup.model.entity.UserFootprint;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.TimeUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.util.share.ShareLinkConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

import org.afinal.simplecache.ApiKey;

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

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import rx.functions.Action1;

/**
 * Created by realicing on 2018/9/17.
 * realicing@sina.com
 * 小绵羊3.4.5新增--足迹
 */
public class FgtFootprint extends BaseListFragment4<UserFootprint> {
    @BindView(R.id.header_foot_print_date_tv)
    TextView header_foot_print_date_tv;
    @BindView(R.id.header_foot_print_last_iv)
    ImageView header_foot_print_last_iv;
    @BindView(R.id.header_foot_print_last_v)
    View header_foot_print_last_v;
    @BindView(R.id.header_foot_print_next_iv)
    ImageView header_foot_print_next_iv;
    @BindView(R.id.header_foot_print_next_v)
    View header_foot_print_next_v;

    @BindView(R.id.fgt_foot_print_cv)
    CalendarView mCalendarView;
    @BindView(R.id.fgt_foot_print_cl)
    CalendarLayout mCalendarLayout;
    @BindView(R.id.fgt_foot_print_grv)
    RecyclerView mRecyclerView;

    @Override
    public int getLayoutId() {
        return R.layout.fgt_foot_print;
    }

    @Override
    public void initView() {
        per_page = 1;
        CustomMonthView.class.getSimpleName();
        CustomWeekView.class.getSimpleName();
        TitleBarUtils
                .getInstance()
                .setShowOrHide(getActivity(), true)
                .setTitleFinish(activity)
                .setTitle(activity, "足迹")
                .setRightImgBotton(activity, R.mipmap.share, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new ShareLinkConfig().toShare(activity);
                    }
                });

        view_list = mRecyclerView;
        initAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        mRecyclerView.setAdapter(adapter);

        int maxYear = mCalendarView.getCurYear();
        int maxYearMonth = mCalendarView.getCurMonth();
        int maxYearDay = mCalendarView.getCurDay();
        mCalendarView.setRange(2018, 10, 23,
                maxYear, maxYearMonth, maxYearDay);
        header_foot_print_last_v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //翻到上一个月
                mCalendarView.scrollToPre(true);
            }
        });
        header_foot_print_next_v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //翻到下一个月
                mCalendarView.scrollToNext(true);
            }
        });
    }

    protected void initAdapter() {
        adapter = new BaseQuickAdapter<UserFootprint, BaseViewHolder>(R.layout.item_my_focus, list) {
            @Override
            protected void convert(BaseViewHolder holder, UserFootprint item) {
                ImageView item_my_focus_iv = holder.itemView.findViewById(R.id.item_my_focus_iv);
                TextView item_my_focus_info_tv = holder.itemView.findViewById(R.id.item_my_focus_info_tv);
                TextView item_my_focus_tv = holder.itemView.findViewById(R.id.item_my_focus_tv);
                ViewUtil.setVisibility(item_my_focus_tv, false);

                ViewUtil.setAvatar(item_my_focus_iv, item.getPic());
                ViewUtil.setText(item_my_focus_info_tv, item.getInfo());
            }
        };
        View headerView = LayoutInflater.from(SheepApp.getInstance()).inflate(R.layout.header_foot_print, null);
        adapter.addHeaderView(headerView);
    }

    private void checkHeaderView(int year, int month) {
        ViewUtil.setText(header_foot_print_date_tv, String.format(Locale.CHINA, "%d年%d月", year, month));
        Calendar firstCalendar = new Calendar();
        firstCalendar.setYear(year);
        firstCalendar.setMonth(month);
        firstCalendar.setDay(1);
        Calendar lastCalendar = new Calendar();
        lastCalendar.setYear(year);
        lastCalendar.setMonth(month);
        lastCalendar.setDay(TimeUtil.getTotalDay(month));
        checkHeaderView(firstCalendar, lastCalendar);
    }

    private void checkHeaderView(Calendar firstCalendar, Calendar lastCalendar) {
        Calendar minCalendar = mCalendarView.getMinRangeCalendar();
        Calendar maxCalendar = mCalendarView.getMaxRangeCalendar();
        boolean canScrollToPre = minCalendar.compareTo(firstCalendar) < 0;
        ViewUtil.setEnabled(header_foot_print_last_iv, canScrollToPre);
        ViewUtil.setEnabled(header_foot_print_last_v, canScrollToPre);
        boolean canScrollToNext = maxCalendar.compareTo(lastCalendar) > 0;
        ViewUtil.setEnabled(header_foot_print_next_iv, canScrollToNext);
        ViewUtil.setEnabled(header_foot_print_next_v, canScrollToNext);
    }

    private void checkHeaderView(List<Calendar> weekCalendars) {
        Calendar firstCalendar = ListUtil.getItem(weekCalendars, 0);
        Calendar lastCalendar = ListUtil.getLast(weekCalendars);
        if (firstCalendar != null && lastCalendar != null) {
            int year = firstCalendar.getYear();
            int month = firstCalendar.getMonth();
            ViewUtil.setText(header_foot_print_date_tv, String.format(Locale.CHINA, "%d年%d月", year, month));
            checkHeaderView(firstCalendar, lastCalendar);
        }
    }


    @Override
    public void initListener() {
        mCalendarView.setOnMonthChangeListener(new CalendarView.OnMonthChangeListener() {
            @Override
            public void onMonthChange(int year, int month) {
                checkHeaderView(year, month);
                initFootprintCountRespons(year, month);
            }
        });
        mCalendarView.setOnWeekChangeListener(new CalendarView.OnWeekChangeListener() {
            @Override
            public void onWeekChange(List<Calendar> weekCalendars) {
                checkHeaderView(weekCalendars);
            }
        });
        mCalendarView.setOnViewChangeListener(new CalendarView.OnViewChangeListener() {
            @Override
            public void onViewChange(boolean isMonthView) {
                if (isMonthView) {
                    checkHeaderView(mCalendarView.getCurYear(), mCalendarView.getCurMonth());
                } else {
                    checkHeaderView(mCalendarView.getCurrentWeekCalendars());
                }
            }
        });
        mCalendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {

            }

            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                date = String.format(Locale.CHINA, "%d-%d-%d", calendar.getYear(), calendar.getMonth(), calendar.getDay());
                refreshData();
            }
        });
    }

    //初始化足迹数量
    private void initFootprintCountRespons(final int year, final int month) {
        String start_date = String.format(Locale.CHINA, "%d-%02d-%02d", year, month, 1);
        String end_date = String.format(Locale.CHINA, "%d-%02d-%02d", year, month, TimeUtil.getTotalDay(month));
        SheepApp.getInstance().getNetComponent().getApiService().getUserFootPrintDateCount(start_date, end_date)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                            @Override
                            public void onNext(BaseMessage baseMessage) {
                                List<FootprintCountRespons> newList = baseMessage.getDataList(FootprintCountRespons.class);
                                if(!ListUtil.isEmpty(newList)){
                                    loadFootprintCountList(year, month, newList);
                                }
                            }

                            @Override
                            public void onError(BaseMessage baseMessage) {
                                if(TestUtil.isDev())
                                    G.showToast(baseMessage);
                            }
                        });
    }

    private void loadFootprintCountList(final int year, final int month, List<FootprintCountRespons> newList) {
        final Map<String, Calendar> map = new HashMap<>();
        ListUtil.forEach(newList, new Action1<FootprintCountRespons>() {
                    @Override
                    public void call(FootprintCountRespons item) {
                        if(item != null && item.getCount() > 0) {
                            Calendar calendar = getSchemeCalendar(year, month, item.getDay(), String.valueOf(item.getCount()));
                            map.put(calendar.toString(), calendar);
                        }
                    }
                });
        //此方法在巨大的数据量上不影响遍历性能，推荐使用
        mCalendarView.setSchemeDate(map);

    }

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


    private String date;

    @Override
    protected String getKey(int page, int per_page) {
        return String.format(Locale.CHINA, "%s?page=%d&per_page=%d&date=%s", ApiKey.getUserFootPrintList, page, per_page, date);
    }

    @Override
    protected Observable<BaseMessage> getApi(ApiService apiService) {
        return apiService.getUserFootPrintList(page, per_page, date);
    }

    @Override
    protected Class<UserFootprint> getTClass() {
        return UserFootprint.class;
    }

}
