package ink.wgink.module.file.excel.error;

import com.alibaba.excel.EasyExcel;
import ink.wgink.module.file.service.IFileService;
import ink.wgink.util.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: AbstractErrorExcelHandler
 * @Description: Excel错误处理器
 * @Author: WangGeng
 * @Date: 2020/4/23 9:56 下午
 * @Version: 1.0
 **/
public abstract class AbstractErrorExcelHandler<T> {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractErrorExcelHandler.class);
    private IFileService fileService;

    public AbstractErrorExcelHandler(IFileService fileService) {
        this.fileService = fileService;
    }

    public String saveErrorExcel(List<T> excelErrors) {
        LOG.debug("生成错误信息Excel");
        // 文件路径
        String errorExcelPath = fileService.getUploadExcelErrorPath();
        File errorExcelPathFileFolder = new File(errorExcelPath);
        if (!errorExcelPathFileFolder.exists()) {
            errorExcelPathFileFolder.mkdirs();
        }
        // 文件名
        String fileName = String.format("%s.xlsx", UUIDUtil.get32UUID());
        // 表格头
        File file = new File(String.format("%s/%s", errorExcelPath, fileName));
        EasyExcel.write(file).sheet("错误清单").head(excelHeaderNames()).doWrite(excelErrors);
        Map<String, Object> params = new HashMap<>(8);
        fileService.uploadErrorExcelFileInfo(fileName, errorExcelPath, file.length(), params);
        return params.get("fileId").toString();
    }

    /**
     * 错误表头
     *
     * @return
     */
    public abstract List<List<String>> excelHeaderNames();

}
