package com.rongwei.safecommon.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.rongwei.rwcommon.base.R;
import com.rongwei.safecommon.config.CustomCellWriteWidthConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

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

import static com.rongwei.safecommon.utils.SaveConstans.NotifyTitle.WEEK_HIDDEN_DANGER_TASK;

/**
 * ExportExceByEasyExcel class
 *
 * @author XH
 * @date 2024/02/02
 */
@Component
public class ExportExcelByEasyExcel {

    private static final Logger log = LoggerFactory.getLogger(ExportExcelByEasyExcel.class.getName());

    public static <T> String generateExcel(String file, String originalFilename, String notifyId, List<T> data, Class<T> className) {
        String returnStr = "";
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();) {
            ExcelWriter excelWriter = EasyExcel.write(byteArrayOutputStream).build();
            WriteSheet maintainSheet = EasyExcel.writerSheet(0, WEEK_HIDDEN_DANGER_TASK)
                    .head(className)
                    .registerWriteHandler(new CustomCellWriteWidthConfig())
                    .build();
            excelWriter.write(data, maintainSheet);
            excelWriter.finish();

            byte[] byteArray = byteArrayOutputStream.toByteArray();
            MultipartFile multipartFile = new MockMultipartFile(file,
                    originalFilename,
                    SaveConstans.ContentType.XLSX, byteArray);
            R upload = JSCommonUtils.upload(multipartFile, notifyId);

            if ("200".equals(upload.getCode())) {
                JSONObject jsonObject = JSONUtil.parseObj(upload.getData());
                returnStr = jsonObject.get("filename").toString() + "-;-" + jsonObject.get("id").toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件生成异常");
        }
        return returnStr;
    }
}
