package com.yeejoin.amos.boot.module.tcm.biz.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ss.extractor.EmbeddedData;
import org.apache.poi.ss.extractor.EmbeddedExtractor;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Shape;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping(value = "/file")
@Slf4j
public class FileController {

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/upload")
    public ResponseModel<Boolean> importData07(@RequestBody MultipartFile file, boolean updateSupport) throws Exception {
        // 获取文件流
        InputStream inputStream = file.getInputStream();
        // 创建一个工作薄对象
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        // 获取第一个工作表对象
        String sheetName = workbook.getSheetName(0);
        XSSFSheet sheet = workbook.getSheet(sheetName);
        getPicturesXSS1(sheet);
        getPicturesXSS2(sheet);
        workbook.close();
        return ResponseHelper.buildResponse(Boolean.TRUE);
    }

    private void getPicturesXSS1(XSSFSheet sheet) {
        XSSFDrawing patriarch = sheet.createDrawingPatriarch();
        // 获取excel所有的图片对象
        List<XSSFShape> shapes = patriarch.getShapes();
        for (Shape shape : shapes) {
            if (shape instanceof XSSFPicture) {
                XSSFPicture picture = (XSSFPicture) shape;
                ClientAnchor anchor2 = picture.getClientAnchor();
                int row1 = anchor2.getRow1();
                short col1 = anchor2.getCol1();
                // 获取图片单元格坐标。例R3、A4等
//                String cellRef = new CellReference(row1, col1).formatAsString();
                // 根据图片位置获取对应的第一行标题单元格
//                Row row = sheet.getRow(row1 - row1);
//                Cell cell3 = row.getCell(col1);
                // 获取标题单元格文本内容
//                String stringCellValue = cell3.getStringCellValue();
//                System.out.println("图片所在的单元格标题: " + stringCellValue);
                // 获取图片数据
                XSSFPictureData pictureData = picture.getPictureData();
                byte[] bytes = pictureData.getData();
                // 图片保存至本地
                FileOutputStream out = null;
                try (FileOutputStream fos = new FileOutputStream("D:\\temp\\" + UUID.randomUUID() + "." + pictureData.suggestFileExtension())) {
                    // 图片保存至本地
                    fos.write(bytes);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }

    private Map<String, PictureData> getPicturesXSS2(XSSFSheet sheet) {
        Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
        for (POIXMLDocumentPart dr : sheet.getRelations()) {
            if (dr instanceof XSSFDrawing) {
                XSSFDrawing drawing = (XSSFDrawing)dr;
                for(XSSFShape shape :drawing.getShapes()) {
                    if(shape instanceof XSSFPicture) {
                        XSSFPicture picture = (XSSFPicture)shape;
                        XSSFPictureData pictureData = picture.getPictureData();
                        byte[] bytes = pictureData.getData();
                        try (FileOutputStream fos = new FileOutputStream("D:\\temp\\" + UUID.randomUUID() + "." + pictureData.suggestFileExtension())) {
                            // 图片保存至本地
                            fos.write(bytes);
                        } catch (IOException e) {
                            log.error(e.getMessage());
                        }
                    }
                }
            }
        }
        return sheetIndexPicMap;
    }


    /**
     * 镶入的附件解析
     *
     * @param file
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/extractor")
    public ResponseModel<Boolean> importData3(@RequestBody MultipartFile file) throws Exception {
        // 获取文件流
        InputStream inputStream = file.getInputStream();
        // 创建一个工作薄对象
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        // 获取第一个工作表对象
        XSSFSheet sheet = workbook.getSheetAt(0);
        EmbeddedExtractor extractor = new EmbeddedExtractor();
        for (EmbeddedData embeddedData : extractor.extractAll(sheet)) {
            Shape shape = embeddedData.getShape();
            System.out.println(shape);
            String filename = embeddedData.getFilename();
            System.out.println(filename);
            byte[] data = embeddedData.getEmbeddedData(); //data now contains the embedded data
            try (FileOutputStream dataOut = new FileOutputStream("D:\\temp\\" + UUID.randomUUID() + filename)) {
                dataOut.write(data);
            }
        }
        workbook.close();
        return ResponseHelper.buildResponse(Boolean.TRUE);
    }


    //xlsx版本表格的图片信息
    public static PictureData getSheetPictrues07(int sheetNum,
                                                 XSSFSheet sheet) {
        Map<Integer, PictureData> sheetIndexPicMap = new HashMap<Integer, PictureData>();
        for (POIXMLDocumentPart dr : sheet.getRelations()) {
            if (dr instanceof XSSFDrawing) {
                XSSFDrawing drawing = (XSSFDrawing) dr;
                List<XSSFShape> shapes = drawing.getShapes();
                for (XSSFShape shape : shapes) {
                    XSSFPicture pic = (XSSFPicture) shape;
                    XSSFClientAnchor anchor = pic.getPreferredSize();
                    CTMarker ctMarker = anchor.getFrom();
                    Integer picIndex = ctMarker.getRow();
                    sheetIndexPicMap.put(picIndex, pic.getPictureData());
                }
            }
        }
        return sheetIndexPicMap.get(sheetNum);
    }


}
