package shop.alien.storeplatform.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LifeGroupBuyThali;
import shop.alien.entity.store.LifeLikeRecord;
import shop.alien.entity.store.StoreImg;
import shop.alien.entity.store.StoreMenu;
import shop.alien.entity.store.excelVo.util.ExcelImage;
import shop.alien.entity.store.vo.StoreMenuImportVo;
import shop.alien.entity.store.vo.StoreMenuVo;
import shop.alien.mapper.LifeGroupBuyThaliMapper;
import shop.alien.mapper.LifeLikeRecordMapper;
import shop.alien.mapper.StoreImgMapper;
import shop.alien.mapper.StoreMenuMapper;
import shop.alien.storeplatform.feign.AlienStoreFeign;
import shop.alien.storeplatform.service.StoreMenuPlatformService;
import shop.alien.storeplatform.util.PlatformLikeRecordIdentityHelper;
import shop.alien.storeplatform.util.PlatformLikeRecordIdentityHelper.PlatformLikerScope;
import shop.alien.util.ali.AliOSSUtil;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 二期-门店推荐 服务实现类
 *
 * @author ssk
 * @since 2024-12-05
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StoreMenuPlatformServiceImpl extends ServiceImpl<StoreMenuMapper, StoreMenu> implements StoreMenuPlatformService {

    private final StoreMenuMapper storeMenuMapper;

    private final LifeLikeRecordMapper lifeLikeRecordMapper;

    private final PlatformLikeRecordIdentityHelper lifeLikeIdentityHelper;

    private final StoreImgMapper storeImgMapper;

    private final LifeGroupBuyThaliMapper lifeGroupBuyThaliMapper;

    private final AliOSSUtil aliOSSUtil;

    private final AlienStoreFeign alienStoreFeign;

    /**
     * 获取门店菜单
     *
     * @param storeId  门店id
     * @param dishType 菜品类型, 0:菜单, 1:推荐
     * @param phoneId  消息标识
     * @return list
     */
    @Override
    public List<StoreMenuVo> getStoreMenu(Integer storeId, Integer dishType, String phoneId) {

        if (dishType == 0) {
            List<StoreMenuVo> collect = storeMenuMapper.getStoreMenuList(storeId, null);
            return collect.stream().sorted(Comparator.comparing(StoreMenuVo::getSort)).collect(Collectors.toList());
        } else {
            List<StoreMenuVo> collect = storeMenuMapper.getStoreMenuList(storeId, dishType);
            collect.forEach(item -> {
                if (StringUtils.isNotEmpty(phoneId)) {
                    PlatformLikerScope likerScope = lifeLikeIdentityHelper.resolveFromDianzanId(phoneId);
                    LambdaQueryWrapper<LifeLikeRecord> query = new LambdaQueryWrapper<>();
                    query.eq(LifeLikeRecord::getHuifuId, item.getId());
                    lifeLikeIdentityHelper.applyLikerFilter(query, likerScope);
                    Integer i = lifeLikeRecordMapper.selectCount(query);
                    if (i > 0) {
                        item.setIsLike(1);
                    } else {
                        item.setIsLike(0);
                    }
                }
            });
            return collect.stream().sorted(Comparator.comparing(StoreMenuVo::getSort)).collect(Collectors.toList());
        }
    }

    /**
     * 获取菜品详情
     *
     * @param id 菜品id
     * @return StoreMenuVo
     */
    @Override
    public StoreMenuVo getMenuInfo(Integer id) {
        return storeMenuMapper.getMenuInfo(id);
    }

    /**
     * 新增或修改门店菜品
     *
     * @param storeMenu 菜品信息
     * @return 处理结果
     */
    @Override
    public R<String> saveOrUpdateMenu(StoreMenu storeMenu) {
        boolean flag = false;
        LambdaQueryWrapper<StoreMenu> storeMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //修改菜品
        if (storeMenu.getId() != null) {
            flag = this.updateById(storeMenu);
            if (!flag) {
                log.error("菜单修改失败");
                return R.fail("菜单修改失败");
            }
            return R.success("菜单修改成功");
        } else {//新增菜品
            if (StringUtils.isEmpty(storeMenu.getDishName())) {
                return R.fail("请输入菜品名称");
            }
            storeMenuLambdaQueryWrapper.eq(StoreMenu::getStoreId, storeMenu.getStoreId());
            List<StoreMenu> menuList = this.list(storeMenuLambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(menuList)) {
                int maxSort = menuList.stream().map(StoreMenu::getSort).reduce(Integer::max).get();
                storeMenu.setSort(maxSort + 1);
            } else {
                storeMenu.setSort(1);
            }
            //保存菜品
            flag = this.save(storeMenu);
            if (!flag) {
                return R.fail("菜品新增失败");
            }
        }
        return R.success("新增菜品成功");
    }

    /**
     * 新增或修改门店菜品new
     *
     * @param storeMenuVo 菜品信息
     * @return 处理结果
     */
    @Override
    public R<String> saveOrUpdateMenus(StoreMenuVo storeMenuVo) {
        boolean flag = false;
        LambdaQueryWrapper<StoreMenu> storeMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        int imgId = 0;
        if (storeMenuVo.getImgId() == null || storeMenuVo.getImgId() == 0) {
            StoreImg storeImg = new StoreImg();
            storeImg.setStoreId(storeMenuVo.getStoreId());
            storeImg.setImgType(7);
            storeImg.setImgUrl(storeMenuVo.getImgUrl());
            storeImg.setImgDescription(storeMenuVo.getDishName());
            storeImgMapper.insert(storeImg);
            imgId = storeImg.getId();
        } else {
            imgId = storeMenuVo.getImgId();
        }

        // 封装storeMenu参数
        StoreMenu storeMenu = new StoreMenu();
        BeanUtils.copyProperties(storeMenuVo, storeMenu);
        storeMenu.setImgId(imgId);

        //修改菜品
        if (storeMenu.getId() != null) {
            flag = this.updateById(storeMenu);
            if (!flag) {
                log.error("菜单修改失败");
                return R.fail("菜单修改失败");
            }
            return R.success("菜单修改成功");
        } else {
            //新增菜品
            // 校验菜品参数
            if (StringUtils.isEmpty(storeMenu.getDishName())) {
                return R.fail("请输入菜品名称");
            }

            storeMenuLambdaQueryWrapper.eq(StoreMenu::getStoreId, storeMenu.getStoreId());
            List<StoreMenu> menuList = this.list(storeMenuLambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(menuList)) {
                int maxSort = menuList.stream().map(StoreMenu::getSort).reduce(Integer::max).get();
                storeMenu.setSort(maxSort + 1);
            } else {
                storeMenu.setSort(1);
            }
            //保存菜品
            flag = this.save(storeMenu);
            if (!flag) {
                return R.fail("菜品新增失败");
            }
        }
        return R.success("新增菜品成功");
    }

    /**
     * 菜品排序信息
     *
     * @param storeMenuVo 排序信息
     * @return 处理结果
     */
    @Override
    public Boolean getSortMenuInfo(StoreMenuVo storeMenuVo) {
        boolean flag = false;
        if (CollectionUtil.isNotEmpty(storeMenuVo.getSortList())) {
            for (int i = 0; i < storeMenuVo.getSortList().size(); i++) {
                LambdaQueryWrapper<StoreMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(StoreMenu::getId, storeMenuVo.getSortList().get(i).getId());
                StoreMenu storeMenu = this.getOne(lambdaQueryWrapper);
                storeMenu.setSort(i + 1);
                flag = this.updateById(storeMenu);
            }
        }
        return flag;
    }

    @Override
    public Boolean saveMenuSort(List<StoreMenu> storeMenuList) {
        return this.updateBatchById(storeMenuList);
    }

    /**
     * 删除菜品或推荐菜 根据类型区分
     *
     * @param ids      菜品ID合集
     * @param dishType 0:菜品 1:推荐菜
     * @return 处理结果
     */
    @Override
    public R deleteMenu(List<Integer> ids, int dishType) {
        QueryWrapper<StoreMenu> queryWrapperMenu = new QueryWrapper<>();
        boolean flag = false;
        if (dishType == 0) {
            List<LifeGroupBuyThali> lifeGroupBuyThaliList = lifeGroupBuyThaliMapper.selectList(new LambdaQueryWrapper<LifeGroupBuyThali>().in(LifeGroupBuyThali::getDetailId, ids));
            if (CollectionUtil.isNotEmpty(lifeGroupBuyThaliList)) {
                return R.fail("该菜品已被团购套餐引用，不能删除");
            }
            flag = this.removeByIds(ids);
        } else {
            queryWrapperMenu.in("id", ids);
            List<StoreMenu> storeMenuList = baseMapper.selectList(queryWrapperMenu);
            storeMenuList.forEach(item -> {
                item.setDishType(0);
                this.updateById(item);
            });
            flag = true;
        }
        if (!flag) {
            return R.fail("删除失败");
        }
        return R.success("删除成功");
    }

    @Override
    public StoreMenuVo getMenuCountByStoreId(int storeId) {
        StoreMenuVo storeMenuVo = new StoreMenuVo();
        LambdaUpdateWrapper<StoreMenu> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(StoreMenu::getStoreId, storeId);
        updateWrapper.eq(StoreMenu::getDeleteFlag, 0);
        List<StoreMenu> storeMenuList = storeMenuMapper.selectList(updateWrapper);
        if (CollectionUtils.isNotEmpty(storeMenuList)) {
            storeMenuVo.setMenuCount(storeMenuList.size());
            Map<Integer, List<StoreMenu>> groupByDishType = storeMenuList.stream()
                    .collect(Collectors.groupingBy(StoreMenu::getDishType));
            List<StoreMenu> suggestList = groupByDishType.get(1);
            if (CollectionUtils.isNotEmpty(suggestList)) {
                storeMenuVo.setSuggestCount(suggestList.size());
            } else {
                storeMenuVo.setSuggestCount(0);
            }
        } else {
            storeMenuVo.setMenuCount(0);
            storeMenuVo.setSuggestCount(0);
        }
        return storeMenuVo;
    }

    /**
     * 获取用户对该菜品是否点赞
     *
     * @param userId 用户id
     * @param menuId 菜品id
     * @return boolean
     */
    @Override
    public boolean getMenuLikeStatus(String userId, Integer menuId) {
        PlatformLikerScope likerScope = lifeLikeIdentityHelper.resolveFromDianzanId(userId);
        LambdaQueryWrapper<LifeLikeRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifeLikeRecord::getHuifuId, menuId).eq(LifeLikeRecord::getDeleteFlag, 0);
        lifeLikeIdentityHelper.applyLikerFilter(wrapper, likerScope);
        return lifeLikeRecordMapper.selectCount(wrapper) > 0;
    }
    /**
     * Excel导入门店菜单
     *
     * @param file     Excel文件
     * @param storeId  门店id
     * @return 导入结果
     */
    @Override
    public R<String> importMenuFromExcel(MultipartFile file, Integer storeId) {
        log.info("StoreMenuPlatformServiceImpl.importMenuFromExcel storeId={}", storeId);

        if (file == null || file.isEmpty()) {
            return R.fail("上传文件为空");
        }

        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
            return R.fail("文件格式不正确，请上传Excel文件");
        }

        if (storeId == null) {
            return R.fail("门店ID不能为空");
        }

        List<String> errorMessages = new ArrayList<>();
        int successCount = 0;
        int totalCount = 0;

        try (InputStream inputStream = file.getInputStream();
             XSSFWorkbook workbook = new XSSFWorkbook(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0);

            // 获取表头
            Row headerRow = sheet.getRow(5);
            if (headerRow == null) {
                return R.fail("Excel文件格式不正确，缺少表头");
            }

            // 构建字段映射（表头名称 -> 列索引）
            Map<String, Integer> headerMap = new HashMap<>();
            Field[] fields = StoreMenuImportVo.class.getDeclaredFields();
            for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                Cell cell = headerRow.getCell(i);
                if (cell != null) {
                    String headerName = getCellValueAsString(cell);
                    if (StringUtils.isNotEmpty(headerName)) {
                        headerMap.put(headerName.trim(), i);
                    }
                }
            }

            // 获取图片映射（行索引 -> 图片字节数组）
            Map<Integer, byte[]> imageMap = extractImagesFromSheet(sheet);

            // 读取数据行
            for (int rowIndex = 6; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row == null) {
                    continue;
                }

                // 检查是否为空行
                boolean isEmptyRow = true;
                for (int i = 0; i < row.getLastCellNum(); i++) {
                    Cell cell = row.getCell(i);
                    if (cell != null && cell.getCellType() != CellType.BLANK) {
                        String cellValue = getCellValueAsString(cell);
                        if (StringUtils.isNotEmpty(cellValue)) {
                            isEmptyRow = false;
                            break;
                        }
                    }
                }
                if (isEmptyRow) {
                    continue;
                }

                totalCount++;
                StoreMenuImportVo excelVo = new StoreMenuImportVo();

                // 读取每个字段
                for (Field field : fields) {
                    field.setAccessible(true);
                    String fieldName = field.getName();
                    Integer colIndex = null;

                    // 根据字段名查找对应的表头
                    for (Map.Entry<String, Integer> entry : headerMap.entrySet()) {
                        String headerName = entry.getKey();
                        if (isFieldMatch(fieldName, headerName)) {
                            colIndex = entry.getValue();
                            break;
                        }
                    }

                    if (colIndex == null) {
                        continue;
                    }

                    Cell cell = row.getCell(colIndex);
                    if (cell == null && !field.isAnnotationPresent(ExcelImage.class)) {
                        continue;
                    }

                    try {
                        if (field.isAnnotationPresent(ExcelImage.class)) {
                            // 处理图片字段
                            byte[] imageBytes = imageMap.get(rowIndex);
                            if (imageBytes != null && imageBytes.length > 0) {
                                String imageName = "menu_" + storeId + "_" + System.currentTimeMillis() + "_" + rowIndex + ".jpg";
                                MultipartFile multipartFile = new ByteArrayMultipartFile(imageBytes, imageName);
                                JSONObject jsonObject = alienStoreFeign.uploadFile(multipartFile);
                                if (200 == jsonObject.getIntValue("code")) {
                                    field.set(excelVo, jsonObject.getJSONArray("data").get(0));
                                } else {
                                    field.set(excelVo, "");
                                }
//                                String imageUrl = uploadImageToOSS(imageBytes, storeId, rowIndex);
                            }
                        } else {
                            // 处理普通字段
                            String cellValue = getCellValueAsString(cell);
                            if (StringUtils.isNotEmpty(cellValue)) {
                                setFieldValue(excelVo, field, cellValue.trim());
                            }
                        }
                    } catch (Exception e) {
                        log.warn("读取字段{}失败：{}", fieldName, e.getMessage());
                    }
                }

                // 处理导入数据
                try {
                    validateAndSaveMenu(excelVo, storeId, rowIndex + 1);
                    successCount++;
                } catch (Exception e) {
                    errorMessages.add(String.format("第%d行：%s", rowIndex + 1, e.getMessage()));
                    log.error("导入第{}行数据失败", rowIndex + 1, e);
                }
            }
        } catch (Exception e) {
            log.error("导入Excel失败", e);
            return R.fail("导入失败：" + e.getMessage());
        }

        // 构建返回消息
        StringBuilder message = new StringBuilder();
        message.append(String.format("导入完成：成功%d条，失败%d条", successCount, totalCount - successCount));
        if (!errorMessages.isEmpty()) {
            message.append("\n失败详情：\n");
            for (int i = 0; i < Math.min(errorMessages.size(), 10); i++) {
                message.append(errorMessages.get(i)).append("\n");
            }
            if (errorMessages.size() > 10) {
                message.append("...还有").append(errorMessages.size() - 10).append("条错误信息");
            }
        }

        return R.success(message.toString());
    }

    /**
     * 从Sheet中提取图片
     */
    private Map<Integer, byte[]> extractImagesFromSheet(Sheet sheet) {
        Map<Integer, byte[]> imageMap = new HashMap<>();
        if (sheet instanceof XSSFSheet) {
            XSSFSheet xssfSheet = (XSSFSheet) sheet;
            XSSFDrawing drawing = xssfSheet.getDrawingPatriarch();
            if (drawing != null) {
                List<XSSFShape> shapes = drawing.getShapes();
                for (XSSFShape shape : shapes) {
                    if (shape instanceof XSSFPicture) {
                        XSSFPicture picture = (XSSFPicture) shape;
                        XSSFClientAnchor anchor = (XSSFClientAnchor) picture.getAnchor();
                        int rowIndex = anchor.getRow1();
                        try {
                            // 直接使用 getData() 方法获取图片字节数组
                            byte[] imageBytes = picture.getPictureData().getData();
                            imageMap.put(rowIndex, imageBytes);
                        } catch (Exception e) {
                            log.warn("提取第{}行图片失败：{}", rowIndex, e.getMessage());
                        }
                    }
                }
            }
        }
        return imageMap;
    }

    /**
     * 上传图片到OSS
     */
    private String uploadImageToOSS(byte[] imageBytes, Integer storeId, int rowIndex) {
        try {
            // 生成文件名
            String fileName = "menu_" + storeId + "_" + System.currentTimeMillis() + "_" + rowIndex + ".jpg";
            String prefix = "image/";

            // 创建临时MultipartFile
            MultipartFile multipartFile = new ByteArrayMultipartFile(imageBytes, fileName);

            // 上传到OSS
            return aliOSSUtil.uploadFile(multipartFile, prefix + fileName);
        } catch (Exception e) {
            log.error("上传图片失败", e);
            throw new RuntimeException("上传图片失败：" + e.getMessage());
        }
    }

    /**
     * 校验并保存菜单
     */
    private void validateAndSaveMenu(StoreMenuImportVo excelVo, Integer storeId, int rowNum) {
        // 校验必填字段
        if (StringUtils.isEmpty(excelVo.getDishName())) {
            throw new RuntimeException("菜品名称不能为空");
        }

        if (excelVo.getDishPrice() == null || excelVo.getDishPrice().compareTo(BigDecimal.ZERO) <= 0) {
            throw new RuntimeException("菜品价格必须大于0");
        }

        // 创建StoreMenu对象
        StoreMenu storeMenu = new StoreMenu();
        storeMenu.setStoreId(storeId);
        storeMenu.setDishName(excelVo.getDishName());
        storeMenu.setDishPrice(excelVo.getDishPrice());
        storeMenu.setCostPrice(excelVo.getCostPrice());
//        storeMenu.setDishesUnit(excelVo.getDishesUnit());
        storeMenu.setDescription(excelVo.getDescription());
        storeMenu.setDishType(excelVo.getDishType());

        // 处理图片
        if (StringUtils.isNotEmpty(excelVo.getImg())) {
            StoreImg storeImg = new StoreImg();
            storeImg.setStoreId(storeId);
            storeImg.setImgType(7);
            storeImg.setImgUrl(excelVo.getImg());
            storeImg.setImgDescription(excelVo.getDishName());
            storeImgMapper.insert(storeImg);
            storeMenu.setImgId(storeImg.getId());
        }

        // 设置排序
        LambdaQueryWrapper<StoreMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StoreMenu::getStoreId, storeId);
        List<StoreMenu> menuList = this.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(menuList)) {
            int maxSort = menuList.stream().map(StoreMenu::getSort).max(Integer::compareTo).orElse(0);
            storeMenu.setSort(maxSort + 1);
        } else {
            storeMenu.setSort(1);
        }

        // 保存菜单
        boolean flag = this.save(storeMenu);
        if (!flag) {
            throw new RuntimeException("保存菜单失败");
        }
    }

    /**
     * 判断字段名是否匹配表头
     */
    private boolean isFieldMatch(String fieldName, String headerName) {
        // 简单的匹配逻辑，可以根据实际需求调整
        Map<String, String> fieldMapping = new HashMap<>();
        fieldMapping.put("dishName", "菜品名称");
        fieldMapping.put("dishPrice", "价格（￥）");
        fieldMapping.put("costPrice", "成本价（￥）");
//        fieldMapping.put("dishesUnit", "单位");
        fieldMapping.put("img", "图片");
        fieldMapping.put("description", "描述");
        fieldMapping.put("dishType", "是否设为推荐（是/否）");

        String expectedHeader = fieldMapping.get(fieldName);
        return expectedHeader != null && expectedHeader.equals(headerName);
    }

    /**
     * 设置字段值
     */
    private void setFieldValue(StoreMenuImportVo excelVo, Field field, String cellValue) throws Exception {
        Class<?> fieldType = field.getType();
        String fieldName = field.getName();
        if (fieldType == BigDecimal.class) {
            try {
                if (new BigDecimal(cellValue).scale() > 2) {
                    throw new RuntimeException("价格或者成本价格式错误, 请输入数字, 小数点保留两位以内");
                } else {
                    field.set(excelVo, new BigDecimal(cellValue));
                }
            } catch (NumberFormatException e) {
                throw new RuntimeException("价格或者成本价格式错误, 请输入数字, 小数点保留两位以内");
            }
        } else {
            if ("dishType".equals(fieldName)) {
                String trimmedValue = cellValue.trim();
                if ("是".equals(trimmedValue)) {
                    field.set(excelVo, 1);
                } else if ("否".equals(trimmedValue)) {
                    field.set(excelVo, 0);
                } else {
                    throw new RuntimeException("是否推荐字段格式错误，请输入'是'或'否'");
                }
            } else {
                field.set(excelVo, cellValue);
            }
        }
    }

    /**
     * 获取单元格值（字符串格式）
     */
    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return null;
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    // 处理数字，避免科学计数法
                    double numericValue = cell.getNumericCellValue();
                    if (numericValue == (long) numericValue) {
                        return String.valueOf((long) numericValue);
                    } else {
                        return String.valueOf(numericValue);
                    }
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return null;
        }
    }

    /**
     * 临时MultipartFile实现类，用于上传字节数组
     */
    private static class ByteArrayMultipartFile implements MultipartFile {
        private final byte[] content;
        private final String fileName;

        public ByteArrayMultipartFile(byte[] content, String fileName) {
            this.content = content;
            this.fileName = fileName;
        }

        @Override
        public String getName() {
            return "file";
        }

        @Override
        public String getOriginalFilename() {
            return fileName;
        }

        @Override
        public String getContentType() {
            return "image/jpeg";
        }

        @Override
        public boolean isEmpty() {
            return content == null || content.length == 0;
        }

        @Override
        public long getSize() {
            return content.length;
        }

        @Override
        public byte[] getBytes() throws IOException {
            return content;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(content);
        }

        @Override
        public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
            java.nio.file.Files.write(dest.toPath(), content);
        }
    }
}


