package org.springblade.file.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.file.exception.UnzipFailException;
import org.springblade.file.listener.UnzipCompletedEvent;
import org.springblade.file.listener.UnzipFailEvent;
import org.springblade.file.mapper.BusinessUnzipDetailMapper;
import org.springblade.file.pojo.entity.Attachment;
import org.springblade.file.pojo.entity.BusinessUnzipDetail;
import org.springblade.file.pojo.vo.FileVO;
import org.springblade.file.service.IAttachmentService;
import org.springblade.file.service.IBusinessUnzipDetailService;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author bfhuange
 * @date 2024/10/30
 */
@AllArgsConstructor
@Slf4j
@Service
public class BusinessUnzipDetailServiceImpl extends ServiceImpl<BusinessUnzipDetailMapper, BusinessUnzipDetail> implements IBusinessUnzipDetailService {

    private final IAttachmentService attachmentService;
    private final ApplicationContext applicationContext;

    @Async
    @Override
    public void unzipAndSaveAsync(Long unzipTaskId, FileVO file) {
        log.info("解压文件并上传开始 unzipTaskId: {} file: {}", unzipTaskId, JSON.toJSONString(file));
        long start = System.currentTimeMillis();
        try {
            // 1. 上传文件并解压
            List<Attachment> attachments = attachmentService.unzipAndUpload(file);
            if (CollectionUtil.isEmpty(attachments)) {
                log.warn("上传解压文件为空 unzipTaskId:{} objectKey:{}", unzipTaskId, file.getObjectKey());
                return;
            }
            // 2. 保存压缩文件和解压文件关系
            List<BusinessUnzipDetail> addParams = attachments.stream()
                    .map(attachment -> {
                        BusinessUnzipDetail addParam = new BusinessUnzipDetail();
                        addParam.setBusinessUnzipTaskId(unzipTaskId);
                        addParam.setAttachmentId(attachment.getId());
                        return addParam;
                    }).toList();
            if (CollectionUtil.isNotEmpty(addParams)) {
                this.saveBatch(addParams);
            }
            // 3. 发布解压完成事件
            applicationContext.publishEvent(new UnzipCompletedEvent(unzipTaskId));
        } catch (UnzipFailException e) {
            log.error("解压文件异常", e);
            // 发布解压失败事件
            applicationContext.publishEvent(new UnzipFailEvent(unzipTaskId));
        } catch (Exception e) {
            log.error("解压文件并上传异常", e);
        } finally {
            long end = System.currentTimeMillis();
            log.info("解压文件并上传 完成 unzipTaskId: {} objectKey: {} 耗时：{}", unzipTaskId, file.getObjectKey(), end - start);
        }
    }
}
