package org.eco.common.excel.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.eco.common.core.core.domain.UploadRes;
import org.eco.common.core.service.OssService;
import org.eco.common.excel.core.ExcelListener;
import org.eco.common.excel.entity.ExcelResultRes;
import org.eco.common.excel.service.IExcelService;
import org.eco.common.excel.utils.ExcelUtil;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;

/**
 * @Description: ExcelService 实现类
 * @Author: GaoKun Wang
 * @Date: 2024/6/26
 */
@Service
@Slf4j
public class ExcelService implements IExcelService {

    @Resource
    private OssService ossService;

    @Override
    public <T> ExcelResultRes importExcel(InputStream inputStream, String name, Class<T> clazz, ExcelListener<T> listener) {
        log.info("开始异步导入");
        byte[] bytes = IoUtil.readBytes(inputStream);
        InputStream copyInputStream = new ByteArrayInputStream(bytes);
        EasyExcel.read(copyInputStream, clazz, listener).sheet().doReadSync();
        UploadRes uploadRes = ossService.upload(bytes, name);
        ExcelResultRes res = listener.getExcelResult().getAnalysis();
        res.setName(uploadRes.getName());
        res.setUrl(uploadRes.getUrl());
        res.setOssId(uploadRes.getOssId());
        log.info("错误信息：{}", res.getLogInfo());
        log.info("状态：{}", res.getStatus());
        log.info("异步导入结束");
        return res;
    }

    @Override
    public <T> ExcelResultRes exportExcel(List<T> list, String sheetName, Class<T> clazz) {
        log.info("开始异步导出");
        try {
            String fileName = sheetName + "_" + IdUtil.fastSimpleUUID() + ".xlsx";
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes = ExcelUtil.exportExcel(list, sheetName, clazz, false, byteArrayOutputStream, null);
            UploadRes uploadRes = ossService.upload(bytes, fileName);
            log.info("异步导出结束");
            return ExcelResultRes.builder().name(uploadRes.getName()).url(uploadRes.getUrl()).status("1").ossId(uploadRes.getOssId()).logInfo("导出成功").build();
        } catch (Exception e) {
            log.error("异步导出失败：{}", e.getMessage());
            return ExcelResultRes.builder().status("0").logInfo("导出失败").build();
        }
    }
}
