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();
        String threadName = Thread.currentThread().getName();
        logger.info(uuidFlag + " taxno "+taxUser.getTaxno() + " clear file is start." + " 线程名称： " + threadName);
        try {
            Date pastDate = DateUtils.getPastDate(FileConstants.pastDataDay);
            taxUser.setPastDate(pastDate);

            if(taxUser.getUserStatus().equals("3")) {
                while(true) {
                    List<TkFile> tkFiles = tkFileService.queryPastData(taxUser);
                    logger.info(uuidFlag + " taxno is " + taxUser.getTaxno() + " clearPastData part 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())) {
                                //兼容b的桶前缀
                                String bucketName = CommonConstants.BUCKET_NAME;
                                if("nb".equalsIgnoreCase(FileConstants.systemName)) {
                                    bucketName = "invoice";
                                }
                                minioTemplate.removeObject(bucketName + FileConstants.systemName.toLowerCase(), entity.getFileKey());
                                logger.info(uuidFlag + " taxno is " + taxUser.getTaxno() + " clearPastData file " + entity.getInvoiceInfo() + "," + entity.getFileKey() + " delete success!");
                            }
                            fileClearLogService.saveLog(uuidFlag, entity, taxUser.getUserStatus());
                            tkFileService.deleteFileInfo(entity);
                        }
                    } else {
                        break;
                    }
                }
            } else {
                //超过3个月没有执行的，清理所有数据
                if(null!=taxUser.getApplyDownDate() && DateUtils.getMonthSpace(taxUser.getApplyDownDate(), DateUtils.getDate())>=3) {
                    while(true) {
                        List<TkFile> tkFiles = tkFileService.queryExitPastData(taxUser);
                        logger.info(uuidFlag + " taxno is " + taxUser.getTaxno() + " clearPastData all 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())) {
                                    //兼容b的桶前缀
                                    String bucketName = CommonConstants.BUCKET_NAME;
                                    if("nb".equalsIgnoreCase(FileConstants.systemName)) {
                                        bucketName = "invoice";
                                    }
                                    minioTemplate.removeObject(bucketName + FileConstants.systemName.toLowerCase(), entity.getFileKey());
                                    logger.info(uuidFlag + " taxno is " + taxUser.getTaxno() + " clearPastData file " + entity.getInvoiceInfo() + "," + entity.getFileKey() + " delete success!");
                                }
                                fileClearLogService.saveLog(uuidFlag, entity, taxUser.getUserStatus());
                                tkFileService.deleteFileInfo(entity);
                            }
                        } else {
                            //数据清理完后，清理税号上的标记，下次重置时按新税号初始化
                            tkTaxUserService.updateClearTaxUser(taxUser);
                            logger.info(uuidFlag + " taxno is " + taxUser.getTaxno() + " clearPastData user is clear success!");
                            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);
    }
}
