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

import com.tax.file.constants.FileConstants;
import com.tax.file.model.TkTaxUser;
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.stereotype.Component;

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

@Component
public class FileDayReportTask {

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

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

    @Autowired
    private TkTaxUserService tkTaxUserService;
    @Autowired
    private FileDayReportService fileDayReportService;

    public void createDayReport(String uuidFlag){
        //从指定日期执行统计任务
        String preDay = DateUtils.date2Str(DateUtils.addDate(DateUtils.getDate(), -1), DateUtils.date_sdf);
        String startDate = preDay, endDate = preDay;
        if(REPORT_INIT_FLAG.equals("1")) {
            startDate = REPORT_START_DATE;
            endDate = preDay;
        }
        List<TkTaxUser> taxUserList = tkTaxUserService.queryDayReportTaxnoList(startDate, endDate);
        logger.info(uuidFlag + " createDayReport taxno number:" + taxUserList.size());
        try {
            if(taxUserList!=null && taxUserList.size()>0){
                CountDownLatch latch = new CountDownLatch(taxUserList.size());
                for(TkTaxUser taxUser: taxUserList){
                    taxUser.setStartDate(startDate);
                    taxUser.setEndDate(endDate);
                    fileDayReportService.saveFileDayReport(uuidFlag, latch, taxUser);
                }
                latch.await();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(uuidFlag + " createDayReport is error:" + e.getMessage());
        }
    }

}
