package com.reyun.task;

import com.reyun.dic.DownloadStatusEnumType;
import com.reyun.model.ExportReportInfo;
import com.reyun.service.ExportReportInfoService;
import com.reyun.taskexecute.ExportReportThread;
import com.reyun.util.AwsS3Util;
import com.reyun.util.Constant;
import com.reyun.util.RedisUtilNew;
import org.apache.commons.lang.time.DateUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by zxy on 17/4/27.
 * description:报表导出
 */
@Service
public class ExportReportTask {

    private static Logger logger = LoggerFactory.getLogger(ExportReportTask.class);
    private static int EXPIRE_PERIOD = (int) DateUtils.MILLIS_PER_MINUTE * 1 / 1000;

    private static final String S3_DOWNLOAD_BUCKET = Constant.bucket;

    private static final String DOWNLOAD_PATH = "trackingio/reportdownload/";


    @Autowired
    private ExportReportInfoService exportService;

    public void run(){

        logger.info("导出报表结果数据................//Begin, 执行时间: {}", DateTime.now());

        System.out.println(Constant.reportExportTask);

        if (RedisUtilNew.getInstance().tryLock(Constant.reportExportTask, EXPIRE_PERIOD) != null) {

            //生成数据
            List<ExportReportInfo> exportList = exportService.findExport2Deal();

            for (ExportReportInfo export : exportList) {

            	logger.info(export.getFileName());

                Thread exportReportThread = new ExportReportThread(export);
                exportReportThread.start();

            }

            //删除已过期文件
            List<ExportReportInfo> invalidExportInfoList = exportService.findInvalidExportList();
            for (ExportReportInfo invalidExport : invalidExportInfoList) {

                final String s3key = DOWNLOAD_PATH + invalidExport.getFileName();
                //删除文件
                if(AwsS3Util.getInstance().getAmazonS3().doesObjectExist(S3_DOWNLOAD_BUCKET, s3key)) {
                    AwsS3Util.getInstance().deleteS3Object(S3_DOWNLOAD_BUCKET, s3key);
                }

                //跟新文件为失效状态
                exportService.updateStatus(invalidExport.getId(), DownloadStatusEnumType.INVALID.getCode());
            }

        } else {
            logger.info("ExportReportTask正在执行中......");
        }

        logger.info("导出报表结果数据................//End");
    }
}
