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

import com.tax.file.constants.FileConstants;
import com.tax.file.model.FileReport;
import com.tax.file.model.TkTaxUser;
import com.tax.file.service.api.FileReportService;
import com.tax.file.service.api.TkFileService;
import com.tax.file.service.api.TkTaxUserService;
import com.yxcheng.token.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

@Component
public class FileDayReportService {

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

    @Autowired
    protected TkTaxUserService tkTaxUserService;
    @Autowired
    protected TkFileService tkFileService;
    @Autowired
    protected FileReportService fileReportService;

    public static String REPORT_INIT_FLAG = FileConstants.reportInitFlag;
    public static String REPORT_START_DATE = FileConstants.reportStartDate;

    @Async("resetExecutor")
    public Future<String> saveFileDayReport(String uuidFlag, CountDownLatch latch, TkTaxUser taxUser) {
        String taxno = taxUser.getTaxno();
        try {
            //从指定日期执行统计任务
            String preDay = DateUtils.date2Str(DateUtils.addDate(DateUtils.getDate(), -1), DateUtils.date_sdf);
            if(REPORT_INIT_FLAG.equals("1")) {
                taxUser.setStartDate(REPORT_START_DATE);
                taxUser.setEndDate(preDay);
            } else {
                taxUser.setStartDate(preDay);
                taxUser.setEndDate(preDay);
            }
            List<FileReport> fileDayReportList = fileReportService.queryInitFileDayReport(taxUser);
            for(FileReport dayReport:fileDayReportList) {
                fileReportService.saveDayReport(uuidFlag, dayReport, taxUser);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info(uuidFlag + " saveDayReport " + taxno + " error is " + e.getMessage());
        }finally {
            latch.countDown();
        }
        return new AsyncResult<>("saveDayReport taxno="+taxno+" accomplished!");
    }



}
