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

import com.tax.file.constants.CommonConstants;
import com.tax.file.constants.FileConstants;
import com.tax.file.model.TkFile;
import com.tax.file.model.TkTaxUser;
import com.tax.file.service.api.FileClearLogService;
import com.tax.file.service.api.TkFileService;
import com.tax.file.service.api.TkTaxUserService;
import com.yxcheng.tax.fs.minio.service.MinioTemplate;
import com.yxcheng.token.utils.DateUtils;
import org.apache.commons.lang.StringUtils;
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.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

/**
 * @ProjectName: tax-sys-test
 * @Package: com.tax.file.service.async.clear
 * @ClassName: ClearPastDataService
 * @Author: ddx
 * @Description: ${description}
 * @Date: 2021-10-19 16:08
 * @Version: 1.0
 */
@Component
public class ClearPastDataService {

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

    @Autowired
    protected TkTaxUserService tkTaxUserService;
    @Autowired
    private MinioTemplate minioTemplate;
    @Autowired
    private TkFileService tkFileService;
    @Autowired
    private FileClearLogService fileClearLogService;

    @Async("resetExecutor")
    public Future<String> doClearData(String uuidFlag, CountDownLatch latch, TkTaxUser taxUser){
        Instant start = Instant.now();
        logger.info(uuidFlag + " taxno "+taxUser.getTaxno() + " clear file is start.");
        try {
            Date pastDate = DateUtils.getPastDate(FileConstants.pastDataDay);
            taxUser.setPastDate(pastDate);
            while(true) {
                if(taxUser.getUserStatus().equals("3")) {
                    List<TkFile> tkFiles = tkFileService.queryPastData(taxUser);
                    logger.info(uuidFlag + " taxno is " + taxUser.getTaxno() + " clearPastData pastDate is:" + DateUtils.date2Str(pastDate, DateUtils.date_sdf)
                            + ", file record number is:" + tkFiles.size() + ",userStatus is:" + taxUser.getUserStatus());
                    if (tkFiles != null && tkFiles.size() > 0) {
                        for (TkFile entity : tkFiles) {
                            if (StringUtils.isNotBlank(entity.getFileKey())) {
                                minioTemplate.removeObject(CommonConstants.BUCKET_NAME + FileConstants.systemName.toLowerCase(), entity.getFileKey());
                                fileClearLogService.saveLog(uuidFlag, entity, taxUser.getUserStatus());
                                tkFileService.deleteFileInfo(entity);
                            }
                        }
                    } else {
                        break;
                    }
                } else {
                    //超过6个月没有执行的，清理所有数据
                    if(null!=taxUser.getApplyDownDate() && DateUtils.getMonthSpace(taxUser.getApplyDownDate(), DateUtils.getDate())>6) {
                        List<TkFile> tkFiles = tkFileService.queryExitPastData(taxUser);
                        logger.info(uuidFlag + " taxno is " + taxUser.getTaxno() + " clearPastData pastDate is:" + DateUtils.date2Str(pastDate, DateUtils.date_sdf)
                                + ", file record number is:" + tkFiles.size() + ",userStatus is:" + taxUser.getUserStatus());
                        if (tkFiles != null && tkFiles.size() > 0) {
                            for (TkFile entity : tkFiles) {
                                if (StringUtils.isNotBlank(entity.getFileKey())) {
                                    minioTemplate.removeObject(CommonConstants.BUCKET_NAME  + FileConstants.systemName.toLowerCase(), entity.getFileKey());
                                }
                                fileClearLogService.saveLog(uuidFlag, entity, taxUser.getUserStatus());
                                tkFileService.deleteFileInfo(entity);
                            }
                        } else {
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(uuidFlag + " taxno is " + taxUser.getTaxno() + " clearPastData is error:" + e.getMessage());
        } finally {
            latch.countDown();
        }
        //统计耗时
        printEndLog(uuidFlag, taxUser.getTaxno(), start);
        return new AsyncResult<>("doClearData taxno="+taxUser.getTaxno()+" accomplished!");
    }

    public void printEndLog(String uuidFlag, String taxno, Instant start) {
        //统计耗时
        Instant end = Instant.now();
        long duration = end.toEpochMilli() - start.toEpochMilli();
        logger.info(uuidFlag + " taxno "+ taxno + " clear file is end.cost is {} ms!",duration);
    }
}
