package com.fs.his.service.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.List;
import java.util.Map;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fs.common.core.domain.CustomMultipartFile;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.his.dto.FsPackagePruductDTO;
import com.fs.his.param.FsPackageListUParam;
import com.fs.his.param.FsPackageParam;
import com.fs.his.vo.*;
import com.fs.system.domain.SysConfig;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.fs.system.service.ISysConfigService;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.his.mapper.FsPackageMapper;
import com.fs.his.domain.FsPackage;
import com.fs.his.service.IFsPackageService;

import javax.imageio.ImageIO;

/**
 * 套餐包Service业务层处理
 *
 * @author fs
 * @date 2023-08-25
 */
@Service
public class FsPackageServiceImpl implements IFsPackageService {
    @Autowired
    private FsPackageMapper fsPackageMapper;
    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 查询套餐包
     *
     * @param packageId 套餐包主键
     * @return 套餐包
     */
    @Override
    public FsPackage selectFsPackageByPackageId(Long packageId) {
        return fsPackageMapper.selectFsPackageByPackageId(packageId);
    }

    /**
     * 查询套餐包列表
     *
     * @param fsPackage 套餐包
     * @return 套餐包
     */
    @Override
    public List<FsPackage> selectFsPackageList(FsPackage fsPackage) {
        return fsPackageMapper.selectFsPackageList(fsPackage);
    }

    /**
     * 新增套餐包
     *
     * @param fsPackage 套餐包
     * @return 结果
     */
    @Override
    public int insertFsPackage(FsPackage fsPackage) {

        fsPackage.setCreateTime(DateUtils.getNowDate());
        if (fsPackage.getPackageSubType() != 1) {
            if (fsPackage.getProductJson() != null) {
                JSONArray objects = JSONUtil.parseArray(fsPackage.getProductJson());
                List<FsPackagePruductDTO> products = JSONUtil.toList(objects, FsPackagePruductDTO.class);
                BigDecimal toal = new BigDecimal(0);
                for (FsPackagePruductDTO product : products) {
                    toal = toal.add(product.getCostPrice().multiply(new BigDecimal(product.getCount())));
                }
                fsPackage.setProductCostPrice(toal);
                SysConfig sysConfig = sysConfigService.selectConfigByConfigKey("his.store");
                Map<String, Object> config = (Map<String, Object>) JSON.parse(sysConfig.getConfigValue());
                Integer followRate = (Integer) config.get("followRate");
                BigDecimal in = new BigDecimal((fsPackage.getCycle() / followRate) * 300);
                fsPackage.setInquiryCostPrice(in);
                fsPackage.setTotalCostPrice(toal.add(in));
            }
        }
        return fsPackageMapper.insertFsPackage(fsPackage);
    }

    /**
     * 修改套餐包
     *
     * @param fsPackage 套餐包
     * @return 结果
     */
    @Override
    public int updateFsPackage(FsPackage fsPackage) {
        fsPackage.setUpdateTime(DateUtils.getNowDate());
        if (fsPackage.getPackageSubType() != null && fsPackage.getPackageSubType() != 1) {
            if (fsPackage.getProductJson() != null) {
                JSONArray objects = JSONUtil.parseArray(fsPackage.getProductJson());
                List<FsPackagePruductDTO> products = JSONUtil.toList(objects, FsPackagePruductDTO.class);
                BigDecimal toal = new BigDecimal(0);
                for (FsPackagePruductDTO product : products) {
                    toal = toal.add(product.getCostPrice().multiply(new BigDecimal(product.getCount())));
                }
                fsPackage.setProductCostPrice(toal);
                BigDecimal in = new BigDecimal((fsPackage.getCycle() / 6) * 300);
                fsPackage.setInquiryCostPrice(in);
                fsPackage.setTotalCostPrice(toal.add(in));
            }
        }
        return fsPackageMapper.updateFsPackage(fsPackage);
    }

    /**
     * 批量删除套餐包
     *
     * @param packageIds 需要删除的套餐包主键
     * @return 结果
     */
    @Override
    public int deleteFsPackageByPackageIds(Long[] packageIds) {

        return fsPackageMapper.deleteFsPackageByPackageIds(packageIds);
    }

    /**
     * 删除套餐包信息
     *
     * @param packageId 套餐包主键
     * @return 结果
     */
    @Override
    public int deleteFsPackageByPackageId(Long packageId) {
        return fsPackageMapper.deleteFsPackageByPackageId(packageId);
    }

    @Override
    public List<OptionsVO> selectAllPackageList() {
        return fsPackageMapper.selectAllPackageList();
    }

    @Override
    public List<FsPackageListVO> selectFsPackageListVO(FsPackageParam fsPackage) {
        return fsPackageMapper.selectFsPackageListVO(fsPackage);
    }

    @Override
    public String importData(List<FsPackage> list) {

        if (com.fs.common.utils.StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (FsPackage vo : list) {
            try {
                vo.setCreateTime(DateUtils.getNowDate());
                if (vo.getPackageSubType() != 1) {
                    if (vo.getProductJson() != null) {
                        JSONArray objects = JSONUtil.parseArray(vo.getProductJson());
                        List<FsPackagePruductDTO> products = JSONUtil.toList(objects, FsPackagePruductDTO.class);
                        BigDecimal toal = new BigDecimal(0);
                        for (FsPackagePruductDTO product : products) {
                            toal = toal.add(product.getCostPrice().multiply(new BigDecimal(product.getCount())));
                        }
                        vo.setProductCostPrice(toal);
                        BigDecimal in = new BigDecimal((vo.getCycle() / 6) * 300);
                        vo.setInquiryCostPrice(in);
                        vo.setTotalCostPrice(toal.add(in));
                    }
                }
                int i = fsPackageMapper.insertFsPackage(vo);

                successNum++;
                successMsg.append("<br/>" + successNum + "、名称 " + vo.getPackageName() + " 导入成功");

            } catch (Exception e) {

                failureNum++;
                String msg = "<br/>" + failureNum + "、名称 " + vo.getPackageName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public FsPackageVO selectFsPackageByPackageIdVO(Long packageId) {
        FsPackageVO fsPackageVO = fsPackageMapper.selectFsPackageByPackageIdVO(packageId);
        return fsPackageVO;
    }

    @Override
    public List<FsPackageExcelVO> selectFsPackageListExcelVO(FsPackage fsPackage) {
        List<FsPackageExcelVO> fsPackageExcelVOS = fsPackageMapper.selectFsPackageListExcelVO(fsPackage);
        for (FsPackageExcelVO fsPackageExcelVO : fsPackageExcelVOS) {
            String s = fsPackageMapper.selectFsDoctorNamesByPackageId(fsPackageExcelVO.getPackageId());
            fsPackageExcelVO.setDoctors(s);
            if (fsPackageExcelVO.getProductJson() != null && fsPackageExcelVO.getProductJson() != "") {
                JSONArray objects = JSONUtil.parseArray(fsPackageExcelVO.getProductJson());
                List<FsPackagePruductDTO> products = JSONUtil.toList(objects, FsPackagePruductDTO.class);
                fsPackageExcelVO.setProductNum(products.size());
            }

        }
        return fsPackageExcelVOS;
    }

    @Override
    public List<FsPackageListUVO> selectFsPackageListUVO(FsPackageListUParam param) {
        return fsPackageMapper.selectFsPackageListUVO(param);
    }

    @Override
    public List<FsPackageListVO> selectFsPackageListVByName(String fsPackage) {
        return fsPackageMapper.selectFsPackageListVByName(fsPackage);
    }

    @Override
    public int updatePackagesStatus(Long[] packageIds, Long status) {
        return fsPackageMapper.updatePackagesStatus(packageIds, status);
    }

    @Override
    public String convertImageToJpg(String imgUrl,Long packageId) {
        if (StringUtils.isBlank(imgUrl)) {
            throw new IllegalArgumentException("图片 URL 不能为空");
        }
        String url = "";
        try {
            // 获取文件后缀（忽略大小写）
            String suffix = imgUrl.contains(".") ? imgUrl.substring(imgUrl.lastIndexOf(".") + 1).toLowerCase() : "";
            if ("png".equals(suffix)) {
                // 下载图片
                BufferedImage originalImage = ImageIO.read(new URL(imgUrl));

                // 创建内存输出流
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

                // 转换 PNG → JPG（透明背景变成白色）
                Thumbnails.of(originalImage)
                        .scale(1.0) // 保持原尺寸
                        .outputFormat("jpg")
                        .toOutputStream(outputStream);

                // 转换为 MultipartFile
                CustomMultipartFile jpgFile = new CustomMultipartFile(
                        "converted.jpg",   // 字段名
                        "converted.jpg",   // 原始文件名
                        "image/jpeg",      // MIME 类型
                        outputStream.toByteArray() // 图片数据
                );
                if (!jpgFile.isEmpty()) {
                    // 上传文件
//                    String fileName = jpgFile.getOriginalFilename();
                    CloudStorageService storage = OSSFactory.build();
                    url = storage.uploadSuffix(jpgFile.getBytes(), ".jpg");
                }
            } else {
                return imgUrl;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (!imgUrl.equals(url) && packageId !=null) {
            //更新数据库
            FsPackage temp = new FsPackage();
            temp.setPackageId(packageId);
            temp.setImgUrl(url);
            updateFsPackage(temp);
            return url;
        }
        return null;
    }
}

