package com.rongwei.bscommon.sys.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.rongwei.rwcommon.base.R;
import com.rongwei.safecommon.utils.CXCommonUtils;
import com.rongwei.safecommon.utils.SaveConstans;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.Map;

/**
 * @author zhou
 */
public class ExcelUtils {

    /**
     * 校验excel行是否为空
     * @param row
     * @return
     */
    public static boolean isRowEmpty(Row row) {
        if (row == null){
            return true;
        }else {
            for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
                Cell cell = row.getCell(c);
                if (cell != null && cell.getCellType() != CellType.BLANK){
                    return false;
                }
            }
        }
        return true;
    }


    /**
     * 生成附件返回附件信息
     *
     * @param workbook
     * @param noticeId
     * @param originalFilename
     * @return
     */
    public static String feginCommonUpload(HSSFWorkbook workbook, String noticeId, String originalFilename){

        String returnStr =null;
        try {
            // 1. 将workbook保存为临时文件
            File tempFile = File.createTempFile("workbook", ".xlsx");
            try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                workbook.write(fos);
            }
            // 2. 读取临时文件的内容并将其转换为byte[] byteArray
            byte[] byteArray = Files.readAllBytes(tempFile.toPath());
            tempFile.deleteOnExit();

            MultipartFile multipartFile = new MockMultipartFile("file",
                    originalFilename,
                    SaveConstans.ContentType.XLSX, byteArray);
            //文件上传只需将参数中的键指定（默认file），值设为文件对象即可，对于使用者来说，文件上传与普通表单提交并无区别
            R upload = CXCommonUtils.upload(multipartFile,noticeId);
            if (upload.getCode().equals("200")){
                JSONObject jsonObject = JSONUtil.parseObj(upload.getData());
                returnStr = jsonObject.get("filename").toString() + "-;-" + jsonObject.get("id").toString();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return  returnStr;
    }

    /**
     * 调用接口生成文件
     * @param workbook
     * @param fileName
     * @return
     */
    public static  String workBookCommonUpload(Workbook workbook, String fileName, String suffix){
        String id="";
        try {
            // 创建临时文件
            File tempFile = File.createTempFile(fileName, suffix);
            tempFile.deleteOnExit();
            //数据写入临时文件中
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            workbook.write(outputStream);
            outputStream.close();
            // 获取临时文件的InputStream
            InputStream inputStream = new FileInputStream(tempFile);
            // 使用临时文件创建一个 MultipartFile 实例
            MultipartFile multipartFile = new MockMultipartFile("file", tempFile.getName() , "application/vnd.ms-excel", inputStream);
            //文件上传只需将参数中的键指定（默认file），值设为文件对象即可，对于使用者来说，文件上传与普通表单提交并无区别
            R upload = CXCommonUtils.upload(multipartFile,"");
            if (upload.getCode().equals("200")){
                Map<String,String> map = (Map<String, String>) JSON.parse(upload.getData().toString());
                id =map.get("id");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return id;
    }





}
