package com.bonus.canteen.core.common.export.task;

import com.bonus.canteen.core.common.export.model.ExportRecord;
import com.bonus.canteen.core.common.export.service.ExportRecordService;
import com.bonus.canteen.core.common.export.service.ExportUploadManager;
import com.bonus.canteen.core.common.redis.RedisUtil;
import com.bonus.canteen.core.common.utils.JacksonUtil;
import com.bonus.canteen.core.common.utils.LogUtil;
import com.bonus.canteen.core.data.dataset.Executors;
import com.bonus.canteen.core.dataset.tenant.TenantLoader;
import com.bonus.common.houqin.oss.OssProperties;
import com.bonus.common.houqin.oss.service.OssTemplate;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

@Component
public class ExportCleanUpTask {
   private static final Logger log = LoggerFactory.getLogger(ExportCleanUpTask.class);
   private static final String LOCK_KEY_CLEAN = "export:clean-expired";
   @Resource
   @Lazy
   private ExportRecordService exportRecordService;
   @Resource
   @Lazy
   private ExportUploadManager exportUploadManager;
   @Resource
   @Lazy
   private OssProperties ossProperties;
   @Resource
   @Lazy
   private OssTemplate ossTemplate;
   @Resource
   @Lazy
   private TenantLoader tenantLoader;

   @XxlJob("exportFileCleanHandler")
   public void exportFileCleanHandler() {
      LogUtil.generateNewLogTraceId();
      log.info("[导出定时任务]清理过期导出 开始");
      RLock lock = RedisUtil.getLock("export:clean-expired");
      if (!lock.tryLock()) {
         log.warn("[导出定时任务]上一个任务进行中（清理过期导出）");
      } else {
         try {
            String jobParam = XxlJobHelper.getJobParam();
            TaskParam param = (TaskParam) JacksonUtil.readValue(jobParam, TaskParam.class);
            Iterator var4 = this.tenantLoader.listTenant().iterator();

            label141:
            while(true) {
               while(true) {
                  if (!var4.hasNext()) {
                     break label141;
                  }

                  Long tenantId = (Long)var4.next();
                  if (param != null && param.ifStopMode()) {
                     Executors.doInAllTenant((s) -> {
                        this.exportRecordService.cancelAllWaitingAndCreating();
                     });
                  } else {
                     List<ExportRecord> exportRecords = (List)Executors.readInTenant(tenantId, () -> {
                        return this.exportRecordService.listExpired();
                     });
                     if (exportRecords != null && !exportRecords.isEmpty()) {
                        Iterator var7 = exportRecords.iterator();

                        while(var7.hasNext()) {
                           ExportRecord exportRecord = (ExportRecord)var7.next();

                           try {
                              this.exportUploadManager.remove(exportRecord.getFileUrl());
                              Executors.doInTenant(tenantId, (s) -> {
                                 this.exportRecordService.didExpired(exportRecord.getExportId());
                              });
                           } catch (Exception var19) {
                              log.error("[导出定时任务]删除文件失败", var19);
                           }
                        }
                     }
                  }
               }
            }
         } catch (Exception var20) {
            log.error("[导出定时任务]处理失败", var20);
         } finally {
            try {
               if (lock.isHeldByCurrentThread() && lock.isLocked()) {
                  lock.unlock();
               }
            } catch (Exception var18) {
               log.error("解锁异常", var18);
            }

         }

         log.info("[导出定时任务]清理过期导出 结束");
      }
   }

   private static class TaskParam {
      private String mode = "CLEAN";

      public boolean ifStopMode() {
         return "STOP".equals(this.mode);
      }

      public TaskParam() {
      }

      public String getMode() {
         return this.mode;
      }

      public void setMode(final String mode) {
         this.mode = mode;
      }
   }
}
