//package com.ruoyi.utils.excel.easyexcel;
//
//import cn.stylefeng.guns.modular.business.custom.util.excel.easyexcel.annotations.ExplicitConstraint;
//import cn.stylefeng.guns.modular.business.custom.util.excel.easyexcel.handler.CommentWriteHandler;
//import cn.stylefeng.guns.modular.business.custom.util.excel.easyexcel.handler.CustomSheetWriteHandler;
//import cn.stylefeng.guns.modular.business.custom.util.excel.easyexcel.handler.TemplateCellWriteHandler;
//import cn.stylefeng.guns.modular.business.custom.util.excel.easyexcel.listener.ExcelListener;
//import cn.stylefeng.guns.modular.business.custom.util.excel.easyexcel.service.ExplicitInterface;
//import com.alibaba.excel.EasyExcel;
//import com.alibaba.excel.ExcelWriter;
//import com.alibaba.excel.write.metadata.WriteSheet;
//import com.alibaba.excel.write.metadata.WriteTable;
//import com.alibaba.excel.write.metadata.style.WriteCellStyle;
//import com.alibaba.excel.write.metadata.style.WriteFont;
//import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
//import com.alipay.service.schema.util.StringUtil;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.apache.poi.EncryptedDocumentException;
//import org.apache.poi.POIXMLDocumentPart;
//import org.apache.poi.hssf.usermodel.*;
//import org.apache.poi.ss.usermodel.HorizontalAlignment;
//import org.apache.poi.ss.usermodel.IndexedColors;
//import org.apache.poi.ss.usermodel.PictureData;
//import org.apache.poi.ss.usermodel.Workbook;
//import org.apache.poi.xssf.usermodel.*;
//import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.*;
//import java.lang.reflect.Field;
//import java.net.URLEncoder;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//@Slf4j
//public class ExcelUtil {
//    /**
//     * 导出数据为excel文件
//     *
//     * @param filename       文件名称
//     * @param dataResult     集合内的bean对象类型要与clazz参数一致
//     * @param clazz          集合内的bean对象类型要与clazz参数一致
//     * @param response       HttpServlet响应对象
//     */
//    public static void export(String filename, List<?> dataResult, Class<?> clazz, HttpServletResponse response) {
//        response.setStatus(200);
//        OutputStream outputStream = null;
//        ExcelWriter excelWriter = null;
//        try {
//            if (StringUtils.isBlank(filename)) {
//                throw new RuntimeException("'filename' 不能为空");
//            }
//            String fileName = filename.concat(".xlsx");
//            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
//            outputStream = response.getOutputStream();
//
//            // 根据不同的策略生成不同的ExcelWriter对象
//            if (dataResult == null){
//                excelWriter = getTemplateExcelWriter(outputStream,clazz);
//            } else {
//                excelWriter = getExportExcelWriter(outputStream);
//            }
//
//            WriteTable writeTable = EasyExcel.writerTable(0).head(clazz).needHead(true).build();
//            WriteSheet writeSheet = EasyExcel.writerSheet(fileName).build();
//            // 写出数据
//            excelWriter.write(dataResult, writeSheet, writeTable);
//
//        } catch (Exception e) {
//            log.error("导出excel数据异常：", e);
//            throw new RuntimeException(e);
//        } finally {
//            if (excelWriter != null) {
//                excelWriter.finish();
//            }
//            if (outputStream != null) {
//                try {
//                    outputStream.flush();
//                    outputStream.close();
//                } catch (IOException e) {
//                    log.error("导出数据关闭流异常", e);
//                }
//            }
//        }
//    }
//
//    /**
//     * 根据不同策略生成不同的ExcelWriter对象， 可根据实际情况修改
//     * @param outputStream  数据输出流
//     * @return  模板下载ExcelWriter对象
//     */
//    private static ExcelWriter getTemplateExcelWriter(OutputStream outputStream,Class<?> model){
//
////        //用来存储对应的列与值对象
////        Map<Integer, String[]> selectedMap = new HashMap<>();
////        selectedMap.put(1,new String[]{"1","2","3"});
//
//        //下拉列表集合
//        Map<Integer, String[]> selectedMap = resolveSelectedAnnotation(model);
//
//        return EasyExcel.write(outputStream)
//                .registerWriteHandler(new CommentWriteHandler())        //增加批注策略
//                .registerWriteHandler(new TemplateCellWriteHandler())   //样式
//                .registerWriteHandler(new CustomSheetWriteHandler(5000,selectedMap))    //增加下拉框策略
//                .build();
//    }
//
//    /**
//     * 根据不同策略生成不同的ExcelWriter对象， 可根据实际情况修改
//     * @param outputStream  数据输出流
//     * @return  数据导出ExcelWriter对象
//     */
//    private static ExcelWriter getExportExcelWriter(OutputStream outputStream){
//        return EasyExcel.write(outputStream)
//                .registerWriteHandler(new TemplateCellWriteHandler())   //字体居中策略
//                .build();
//    }
//    /**
//     * 解析表头类中的下拉注解
//     * @param head 表头类
//     * @param <T> 泛型
//     * @return Map<下拉框列索引, 下拉框内容> map
//     */
//    private static <T> Map<Integer, String[]> resolveSelectedAnnotation(Class<T> head) {
//        Map<Integer, String[]> selectedMap = new HashMap<>();
//
//        // getDeclaredFields(): 返回全部声明的属性；getFields(): 返回public类型的属性
//        Field[] fields = head.getDeclaredFields();
//        for (int i = 0; i < fields.length; i++) {
//            Field field = fields[i];
//            //解析注解信息
//            ExplicitConstraint explicitConstraint = field.getAnnotation(ExplicitConstraint.class);
//            resolveExplicitConstraint(selectedMap,explicitConstraint);
//
//        }
//
//        return selectedMap;
//    }
//
//    /**
//     * 解析注解内容 获取下列表信息
//     * @param explicitConstraint
//     * @return
//     */
//    public static Map<Integer, String[]> resolveExplicitConstraint(  Map<Integer, String[]> explicitListConstraintMap,ExplicitConstraint explicitConstraint){
//        if (explicitConstraint == null) {
//            return null;
//        }
//        //固定下拉信息
//        String[] source = explicitConstraint.source();
//        if (source.length > 0) {
//            explicitListConstraintMap.put(explicitConstraint.indexNum(), source);
//        }
//        //动态下拉信息
//        Class<? extends ExplicitInterface>[] classes = explicitConstraint.sourceClass();
//        if (classes.length>0){
//            ExplicitInterface explicitInterface = null;
//            try {
//
//                explicitInterface = classes[0].newInstance();
//                String[] source1 = explicitInterface.source(explicitConstraint.type());
//                if (source1.length>0){
//                    explicitListConstraintMap.put(explicitConstraint.indexNum(), source1);
//                }
//            } catch (InstantiationException e) {
//                e.printStackTrace();
//            } catch (IllegalAccessException e) {
//                e.printStackTrace();
//            }
//        }
//        return null;
//    }
//
//
//    /**
//     *  设置表格内容居中显示策略
//     * @return
//     */
//    private static HorizontalCellStyleStrategy getStyleStrategy(){
//        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//        //设置背景颜色
//        headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
//        //设置头字体
//        WriteFont headWriteFont = new WriteFont();
//        headWriteFont.setFontHeightInPoints((short)50);
//        headWriteFont.setBold(true);
//        headWriteCellStyle.setWriteFont(headWriteFont);
//        //设置头居中
//        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//
//        // 内容策略
//        WriteCellStyle writeCellStyle = new WriteCellStyle();
//        // 设置内容水平居中
//        writeCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//        return new HorizontalCellStyleStrategy(headWriteCellStyle, writeCellStyle);
//    }
//
//    /**
//     * 根据Excel模板，批量导入数据
//     * @param file  导入的Excel
//     * @param clazz 解析的类型
//     * @return  解析完成的数据
//     */
//    public static List<?> importExcel(MultipartFile file, Class<?> clazz){
//        if (file == null || file.isEmpty()){
//            throw new RuntimeException("没有文件或者文件内容为空！");
//        }
//        List<?> dataList = null;
//        BufferedInputStream ipt = null;
//        try {
//            InputStream is = file.getInputStream();
//            // 用缓冲流对数据流进行包装
//            ipt = new BufferedInputStream(is);
//            // 数据解析监听器
//            ExcelListener<?> listener = new ExcelListener<>();
//            // 读取数据
//            EasyExcel.read(ipt, clazz,listener).sheet().doRead();
//            // 获取去读完成之后的数据
//            dataList = listener.getDataList();
//        } catch (Exception e){
//            log.error(String.valueOf(e));
//            throw new RuntimeException("数据导入失败！" + e);
//        }
//        return dataList;
//    }
//
//
//
//    /**
//     * 获取excel表中的图片
//     *
//     * @return
//     * @throws IOException
//     * @throws EncryptedDocumentException
//     * @Param fis 文件输入流
//     * @Param sheetNum Excel表中的sheet编号
//     */
//    public static Map<String, PictureData> getPictureFromExcel(File file, int sheetNum) throws EncryptedDocumentException, IOException {
//
//        //获取图片PictureData集合
//        String fileName = file.getName();
//        Workbook workbook = null;
//        if (StringUtil.isEmpty(fileName)) {
//            return null;
//        }
//        FileInputStream fileInputStream = new FileInputStream(file);
//        if (fileName.endsWith("xls")) {
//            //2003
//            workbook = new HSSFWorkbook(fileInputStream);
//            HSSFSheet sheet = (HSSFSheet) workbook.getSheetAt(sheetNum - 1);
//            Map<String, PictureData> pictures = getPictures(sheet);
//            return pictures;
//        } else if (fileName.endsWith("xlsx")) {
//            //2007
//            workbook = new XSSFWorkbook(fileInputStream);
//            XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(sheetNum - 1);
//            Map<String, PictureData> pictures = getPictures(sheet);
//            return pictures;
//        }
//        return new HashMap();
//    }
//
//
//    /**
//     * 获取图片和位置 (xls版)
//     * @param sheet
//     * @return
//     * @throws IOException
//     */
//    public static Map<String, PictureData> getPictures (HSSFSheet sheet) throws IOException {
//        Map<String, PictureData> map = new HashMap<String, PictureData>();
//        List<HSSFShape> list = sheet.getDrawingPatriarch().getChildren();
//        for (HSSFShape shape : list) {
//            if (shape instanceof HSSFPicture) {
//                HSSFPicture picture = (HSSFPicture) shape;
//                HSSFClientAnchor cAnchor = picture.getClientAnchor();
//                PictureData pdata = picture.getPictureData();
//                String key = cAnchor.getRow1() + "-" + cAnchor.getCol1(); // 行号-列号
//                map.put(key, pdata);
//            }
//        }
//        return map;
//    }
//
//    /**
//     * 获取图片和位置 (xlsx版)
//     * @param sheet
//     * @return
//     * @throws IOException
//     */
//    public static Map<String, PictureData> getPictures (XSSFSheet sheet) throws IOException {
//        Map<String, PictureData> map = new HashMap<String, PictureData>();
//        List<POIXMLDocumentPart> list = sheet.getRelations();
//        for (POIXMLDocumentPart part : list) {
//            if (part instanceof XSSFDrawing) {
//                XSSFDrawing drawing = (XSSFDrawing) part;
//                List<XSSFShape> shapes = drawing.getShapes();
//                for (XSSFShape shape : shapes) {
//                    XSSFPicture picture = (XSSFPicture) shape;
//                    XSSFClientAnchor anchor = picture.getPreferredSize();
//                    CTMarker marker = anchor.getFrom();
//                    String key = marker.getRow() + "-" + marker.getCol();
//                    map.put(key, picture.getPictureData());
//                }
//            }
//        }
//        return map;
//    }
//
//    public static void main(String [] args) throws IOException {
//        File file = new File("C:\\Users\\a\\Downloads\\数据导出1687160619220.xlsx");
//        //获取图片数据
//        Map<String, PictureData> map = getPictureFromExcel(file, 1);
//
//        //根据图片行列位置获取图片
//        PictureData picData = (PictureData)map.get(10000+"-"+"8");
//        if (picData != null) {
//            //后缀名
//            String extension = picData.suggestFileExtension();
//            byte[] data = picData.getData();
//            FileOutputStream out = new FileOutputStream("C:\\Users\\a\\Pictures\\a\\" + "picture." + extension);
//            out.write(data);
//            out.close();
//        }
//    }
//
//
//}
