package com.gree.mall.manager.helper;

import com.aliyuncs.utils.StringUtils;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.utils.oss.OSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Sheet;
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 java.io.IOException;
import java.util.*;

/**
 *  lijh
 * 2021-06-08
 */
@Slf4j
public class ExcelImgHelper {

    //导入商品
    public static  HashMap<String, String> importExcel(MultipartFile file, String uploadFileSuffix,int counts) throws IOException, RemoteServiceException {
        Workbook workbook = null;
        try {
            if (uploadFileSuffix.equals("xls")) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else if (uploadFileSuffix.equals("xlsx")) {
                workbook = new XSSFWorkbook(file.getInputStream());
            }
            if (workbook != null) {
                int sheetCount = workbook.getNumberOfSheets();
                if (sheetCount > 0) {
                    Map<Integer,List<PictureData>> imgsMap = getImgs(file);
                    HashMap<String, String> imgUrlByXLS = getImgUrlByXLS(imgsMap, counts);
                    return imgUrlByXLS;
                }
            }
        } finally {
                if (workbook != null) {
                    workbook.close();
                }
        }
        return null;
    }


    //部分代码需要根据导入模板调整
    public static HashMap<String,String> getImgUrlByXLS(Map<Integer,List<PictureData>> pictures,int counts) throws IOException, RemoteServiceException {

        //图片集
        HashMap<String,String> imgMap = new HashMap<>();

        log.error("导入图片数量:{}",pictures.size());
        for (int i = 1; i <= counts; i++) {
            //图片(是根据行号的)
            List<PictureData> picture =  pictures.get(i);
            if(picture == null){
                imgMap.put(i+"",null);
                continue;
            }
            log.error("序号:{}的导入图片数量:{}",i,picture.size());
            String ossUrl = "";
            for(PictureData pictureData :picture) {
                byte[] data = pictureData.getData();
                String uploadFileSuffix = pictureData.suggestFileExtension();

                //保存路径
                long currentTime = System.currentTimeMillis();
                String filePath = OSSUtil.OSS_TYPE_PIC + currentTime + UUID.randomUUID().toString() + "." + uploadFileSuffix;
                //保存图片到oss
                if (!OSSUtil.uploadFile(filePath, data)) {
                    throw new RemoteServiceException("文件同步oss失败");
                }
                ossUrl += OSSUtil.accessUrl + filePath + ",";
            }
            if(StringUtils.isNotEmpty(ossUrl)){
                ossUrl = ossUrl.substring(0,ossUrl.length()-1);
            }
            imgMap.put(i+"",ossUrl);
        }
        return imgMap;
    }


    //获取excel的图片
    public static Map<Integer,List<PictureData>> getImgs(MultipartFile file) throws IOException {

        XSSFWorkbook workBook = new XSSFWorkbook(file.getInputStream());
        Sheet sheet = workBook.getSheetAt(0);

        Map<Integer,List<PictureData>> imgMap = new HashMap<>();
        List<PictureData> list = null;
        //读取sheet的图片放入Map
        for (POIXMLDocumentPart dr : ((XSSFSheet) sheet).getRelations()) {
            if (dr instanceof XSSFDrawing) {
                XSSFDrawing drawing = (XSSFDrawing) dr;
                List<XSSFShape> shapes = drawing.getShapes();
                for (XSSFShape shape : shapes) {
                    if(shape instanceof  XSSFPicture) {
                        XSSFPicture pic = (XSSFPicture) shape;
                        XSSFClientAnchor anchor = pic.getPreferredSize();
                        CTMarker ctMarker = anchor.getFrom();
                        int rowIndex = ctMarker.getRow() - 1;
                        if (imgMap.get(rowIndex) == null) {
                            list = new ArrayList<>();
                            list.add(pic.getPictureData());
                            imgMap.put(rowIndex, list);
                        } else {
                            imgMap.get(rowIndex).add(pic.getPictureData());
                        }
                    }
                }
            }
        }
        return imgMap;
    }
}
