package com.tax.file.service.async.apply;

import com.google.common.collect.Maps;
import com.tax.file.constants.FileConstants;
import com.tax.file.model.TkTaxUser;
import com.tax.file.service.api.TkFileService;
import com.yxcheng.token.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Order(1)
@Component
public class FirstApplyFileService extends AbstractApplyService implements ApplyService {

    private static final Logger logger = LoggerFactory.getLogger(FirstApplyFileService.class);

    @Autowired
    protected TkFileService tkFileService;

    @Override
    public boolean apply(String uuidFlag, TkTaxUser taxUser, Map<String, String> context) {
        boolean applyFlag = true;
        logger.info(uuidFlag + " taxno is " + taxUser.getTaxno() + " initApplyFileService is start!");

        boolean flag = true;
        Date lastInvDate = taxUser.getLastInvDate();
        if(null != lastInvDate) {
            lastInvDate = DateUtils.addDate(lastInvDate, 1);
            //最后发票时间在当前周期，说明已经加载过申请记录，不再执行
            if(DateUtils.isCommonDayCycle(FileConstants.applyCycle, lastInvDate)) {
                flag = false;
                //如果在当前周期，把初始化标记设置为已初始化
                if(taxUser.getInit().equals("0")) {
                    taxUser.setInit("1");
                    taxUser.setApplyDownDate(DateUtils.getDate());
                    taxUser.setUpdateDate(DateUtils.getDate());
                    tkTaxUserService.updateByPrimaryKeySelective(taxUser);
                }
            }
        }

        if(taxUser.getIsOnce().equals("1") && taxUser.getInit().equals("1")) {
            //一次性的，已执行过的，不再加入申请列表
        } else {
            if(flag) {
                applyFlag = doFirstApply(uuidFlag, taxUser);
            }
        }
        logger.info(uuidFlag + " taxno is " + taxUser.getTaxno() + " initApplyFileService is end!The applyFlag is " + applyFlag + ",init flag is " + taxUser.getInit());
        return applyFlag;
    }


    private boolean doFirstApply(String uuidFlag, TkTaxUser taxUser) {
        boolean flag = true;
        try {
            Integer preMonth = taxUser.getInitMonth();
            String curMonth = DateUtils.getDataString(new SimpleDateFormat("yyyyMM"));
            String curPreMonth = DateUtils.getPastMonth(curMonth, -1);
            String[] resetDayArr = taxUser.getResetDay().split(",");

            Date lastInvDate = taxUser.getLastInvDate();
            if(null != lastInvDate) {
                lastInvDate = DateUtils.addDate(lastInvDate, 1);
            }

            Date curDate = DateUtils.getDate();
            //如果没有执行完毕，则在断点处开始
            if(null != lastInvDate) {
                preMonth = DateUtils.monthCompare(lastInvDate, curDate);
                //如果日期太旧，保证最大下载量
                Integer maxMonth = Integer.valueOf(FileConstants.downLoadMaxMonth);
                if(preMonth > maxMonth) {
                    preMonth = maxMonth;
                }
            }

            Map<String, Date> applyDateMap = Maps.newConcurrentMap();
            int minValue = DateUtils.getMinValue(curDate, FileConstants.applyCycle);
            for(int i=preMonth; i>=minValue;i--){
                //获取当月第一天日期
                Date dateStart = DateUtils.getPreFirstDay(curDate,i);
                //获取当月最后一天日期
                Date dateEnd = DateUtils.getPreLastDay(curDate,i);

                boolean addDateFlag = false;
                String beMonth = DateUtils.getMonth(dateStart);
                //比较当月和配置第一天，如果小于配置第一天的，不处理上月和当月数据
                if(DateUtils.companyCurDay(resetDayArr[0]) && curPreMonth.equals(beMonth)) {
                    break;
                }
                //如果配置是一个月一次的，当月不再处理
                if(resetDayArr.length==1 && curMonth.equals(beMonth)) {
                    break;
                }
                if(beMonth.equals(curMonth)) {
                    dateEnd = DateUtils.getPreDateCurMonth(curDate, FileConstants.applyCycle);
                    Date dateNextEnd = DateUtils.getPreDateCurMonth(DateUtils.addDate(curDate, 1), FileConstants.applyCycle);
                    //排除当月周期前一天采集
                    if(DateUtils.dateCompare(dateEnd, dateNextEnd) == 0) {
                        addDateFlag = true;
                    } else {
                        logger.info(uuidFlag  + " taxno is " + taxUser.getTaxno() +  " apply file dateNextEnd is "
                                + DateUtils.date2Str(dateNextEnd, new SimpleDateFormat("yyyy-MM-dd")));
                    }
                } else {
                    addDateFlag = true;
                }
                if(addDateFlag) {
                    applyDateMap.put(DateUtils.date2Str(dateStart, new SimpleDateFormat("yyyy-MM-dd")), dateEnd);
                    //正常执行完，记录最后发票日期
                    taxUser.setLastInvDate(dateEnd);
                }
            }
            tkFileService.saveApplyFileList(uuidFlag, taxUser, applyDateMap);
            taxUser.setInit("1");
            taxUser.setApplyDownDate(curDate);
            taxUser.setUpdateDate(DateUtils.getDate());
            tkTaxUserService.updateByPrimaryKeySelective(taxUser);

        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            logger.error(uuidFlag  + " taxno is " + taxUser.getTaxno() +  " apply file doFirstApply error is " + e.getMessage());
        }
        return flag;
    }

    public static void main(String[] args) {
        Date curDate = DateUtils.str2Date("2022-06-23", new SimpleDateFormat("yyyy-MM-dd"));
        String curMonth = DateUtils.getDataString(new SimpleDateFormat("yyyyMM"));
        Date dateStart = DateUtils.getPreFirstDay(curDate,0);
        //获取当月最后一天日期
        Date dateEnd = DateUtils.getPreLastDay(curDate,0);
        System.out.println("02,04".split(",")[0]);
        String beMonth = DateUtils.getMonth(dateStart);

        String[] resetDayArr = "02,04".split(",");
        String curPreMonth = DateUtils.getPastMonth(curMonth, -1);
        //比较当月和配置第一天，如果小于配置第一天的，不处理上月和当月数据
        if(DateUtils.companyCurDay("27") && curPreMonth.equals(beMonth)) {
            System.out.println("cfgDay break" + curPreMonth);
        }
        //如果配置是一个月一次的，当月不再处理
        if(resetDayArr.length==1 && curMonth.equals(beMonth)) {
            System.out.println("resetDayArr break");
        }

        if(beMonth.equals(curMonth)) {
            dateEnd = DateUtils.getPreDateCurMonth(curDate, FileConstants.applyCycle);
            System.out.println(DateUtils.date2Str(dateEnd, new SimpleDateFormat("yyyy-MM-dd")));

            Date dateNextEnd = DateUtils.getPreDateCurMonth(DateUtils.addDate(curDate, 1), FileConstants.applyCycle);
            System.out.println(DateUtils.date2Str(dateNextEnd, new SimpleDateFormat("yyyy-MM-dd")));
            System.out.println(DateUtils.dateCompare(dateEnd, dateNextEnd));
        }

    }
}
