package com.xxfc.platform.order.jobhandler;

import com.github.wxiaoqi.security.common.exception.BaseException;
import com.google.common.collect.Lists;
import com.xxfc.platform.order.biz.DailyOrderStatisticsBiz;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 每天2点定时统计前一天的数据
 *
 * @author Administrator
 */
@JobHandler(value = "baseOrderStatisticsHandler")
@Component
@Slf4j
public class BaseOrderStatisticsJobHandler extends IJobHandler {
    @Autowired
    private DailyOrderStatisticsBiz statisticsBiz;

    @Value("${order.day:1}")
    private Integer day;

    /**
     * 每日定时执行订单统计
     *
     * @param date 重新统计起止日期.可以为:起止时间(yyyy-MM-dd),开始时间/结束时间(yyyy-MM-dd/yyyy-MM-dd)
     * @return
     */
    @Override
    public ReturnT<String> execute(String date) {

        try {
            log.info("-----定时器进入---baseOrderStatisticsHandler---" + date);
            XxlJobLogger.log("-----定时器进入---baseOrderStatisticsHandler---" + date);
            ArrayList<Integer> arrayList = Lists.newArrayList();
            if (StringUtils.isBlank(date)) {
                arrayList.add(day);
            } else {
                arrayList = dateDifferenceSet(date);
            }
            log.info("获取到当前需要执行的日期,距离当前时间的天数集合" + arrayList);
            XxlJobLogger.log("获取到当前需要执行的日期,距离当前时间的天数集合" + arrayList);
            DateTime now = DateTime.now();

            for (Integer day : arrayList) {
                boolean flag = statisticsBiz.statisticalOrder(day);
                DateTime dateTime = now.plusDays(-day);
                log.info("执行状态:" + dateTime.toString("yyyy-MM-dd")+"="+flag);
                XxlJobLogger.log("执行状态:" + dateTime.toString("yyyy-MM-dd")+"="+flag);
            }
            return new ReturnT<>(ReturnT.SUCCESS_CODE,"执行成功");
        } catch (Exception e) {
            XxlJobLogger.log(e);
            log.error(e.getMessage());
            return new ReturnT<>(ReturnT.FAIL_CODE,"执行失败");
        }
    }

    private ArrayList<Integer> dateDifferenceSet(String date) throws ParseException {

        Long maxDate;
        Long minDate;
        Long currentTime= System.currentTimeMillis();
        if (date.contains("/")) {
            String[] dates = date.split("/");
            Long date1 = getDateByString(dates[0]);
            Long date2 = getDateByString(dates[1]);
            if (date1<date2) {
                maxDate=date2;
                minDate=date1;
            }else{
                maxDate=date1;
                minDate=date2;
            }
            if (minDate<currentTime&&maxDate>currentTime){
                maxDate=currentTime;
            }else if (minDate>currentTime){
                throw  new BaseException("设置的日期,大于当前日期!");
            }

        }else {
            Long dt = getDateByString(date);
            if (dt>currentTime) {
                throw  new BaseException("设置的日期,大于当前日期!");
            }
            minDate=dt;
            maxDate=currentTime;
        }


        //距离今天的最大天数差
        int maxDay = (int) ((currentTime-minDate)/(24*60*60*1000));
        //距离今天的最小天数差
        int minDay = (int) ((currentTime-maxDate)/(24*60*60*1000));


        return getListByMinDayAndMaxDay(minDay,maxDay);
    }

    private Long getDateByString(String date) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.parse(date).getTime();

    }



    private ArrayList<Integer> getListByMinDayAndMaxDay(int minDay,int maxDay){
        ArrayList<Integer> arrayList = Lists.newArrayList();
        for (int day=maxDay;day>=minDay;day--){
            arrayList.add(day);
        }
        return arrayList;
    }

}
