package com.gxwebsoft.bszx.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freewayso.image.combiner.ImageCombiner;
import com.freewayso.image.combiner.enums.OutputFormat;

import java.awt.Font;
import com.gxwebsoft.bszx.entity.BszxClass;
import com.gxwebsoft.bszx.mapper.BszxBmMapper;
import com.gxwebsoft.bszx.param.BszxClassParam;
import com.gxwebsoft.bszx.service.BszxBmService;
import com.gxwebsoft.bszx.entity.BszxBm;
import com.gxwebsoft.bszx.param.BszxBmParam;
import com.gxwebsoft.bszx.service.BszxClassService;
import com.gxwebsoft.cms.entity.CmsArticle;
import com.gxwebsoft.cms.service.CmsArticleService;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.utils.FileServerUtil;
import com.gxwebsoft.common.core.utils.ImageUtil;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 百色中学-报名记录Service实现
 *
 * @author 科技小王子
 * @since 2025-03-06 22:50:25
 */
@Service
public class BszxBmServiceImpl extends ServiceImpl<BszxBmMapper, BszxBm> implements BszxBmService {
  @Value("${config.upload-path}")
  private String uploadPath;
  @Value("${config.file-server}")
  private String fileServer;
  @Resource
  private ConfigProperties config;
  @Resource
  @Lazy
  private CmsArticleService cmsArticleService;
  @Resource
  private BszxClassService bszxClassService;

  @Override
  public PageResult<BszxBm> pageRel(BszxBmParam param) {
    PageParam<BszxBm, BszxBmParam> page = new PageParam<>(param);
    page.setDefaultOrder("id desc");
    List<BszxBm> list = baseMapper.selectPageRel(page, param);
    list.forEach(d -> {
      if(d.getClassId().equals(0)){
        final BszxClassParam classParam = new BszxClassParam();
        classParam.setGradeName(d.getGradeName());
        classParam.setName(d.getClassName());
        final List<BszxClass> bszxClasses = bszxClassService.listRel(classParam);
        if (!CollectionUtils.isEmpty(bszxClasses)) {
          BszxClass bszxClass = bszxClasses.get(0);
          d.setClassId(bszxClass.getId());
          d.setBranchId(bszxClass.getBranch());
          updateById(d);
        }
      }
    });
    return new PageResult<>(list, page.getTotal());
  }

  @Override
  public List<BszxBm> listRel(BszxBmParam param) {
    List<BszxBm> list = baseMapper.selectListRel(param);
    // 排序
    PageParam<BszxBm, BszxBmParam> page = new PageParam<>();
    page.setDefaultOrder("id desc");
    return page.sortRecords(list);
  }

  @Override
  public BszxBm getByIdRel(Integer id) {
    BszxBmParam param = new BszxBmParam();
    param.setId(id);
    return param.getOne(baseMapper.selectListRel(param));
  }


  /**
   * 生成捐款证书 <a href="https://portrait.gitee.com/sGodT/image-combiner">...</a>
   *
   * @return
   * @throws Exception
   */
  @Override
  public String generatePoster(BszxBm item) throws Exception {
    final CmsArticle article = cmsArticleService.getById(7859);
    if (ObjectUtil.isEmpty(article)) {
      return null;
    }
    if (ObjectUtil.isNotEmpty(item)) {

      // 百色一小项目
      if(item.getTenantId().equals(10547)){
        return "https://oss.wsdns.cn/20250915/721b1e49e9924f3a83d7c32186bae16d.png";
      }

      // 百色中学
      //      Font font = new Font("阿里巴巴普惠体", Font.PLAIN, 40);
      //合成器（指定背景图和输出格式，整个图片的宽高和相关计算依赖于背景图，所以背景图的大小是个基准）
      final ImageCombiner combiner = getImageCombiner(item, article);

      if (!FileUtil.exist(uploadPath + "/poster/" + item.getTenantId() + "/bm")) {
        FileUtil.mkdir(uploadPath + "/poster/" + item.getTenantId() + "/bm");
      }
      String basePath = "/poster/" + item.getTenantId() + "/bm/big-" + item.getId() + ".jpg";
      String smallPath = "/poster/" + item.getTenantId() + "/bm/" + item.getId() + ".jpg";
      String filename = uploadPath + basePath;
      String smallFileName = uploadPath + smallPath;
      combiner.save(filename);

      File input = new File(filename);
      File output = new File(smallFileName);
      ImageUtil.adjustQuality(input, output, 0.8f);
      if(input.exists()){
        input.delete();
      }
      return fileServer + smallPath + "?r=" + RandomUtil.randomNumbers(4);
    }
    return null;
  }

  @NotNull
  private static ImageCombiner getImageCombiner(BszxBm item, CmsArticle article) throws Exception {
    ImageCombiner combiner = new ImageCombiner(article.getAddress(), OutputFormat.JPG);

    // 创建支持中文的字体
    Font chineseFont = createChineseFont(30);

    //加文本元素：姓名
//      if (item.getType().equals(0)) {
//        combiner.addTextElement(item.getName().concat(" 校友"), 40, 220, 540);
//      } else {
//        combiner.addTextElement(item.getName(), 40, 220, 540);
//      }

//      combiner.addTextElement(DateUtil.format(DateUtil.date(), "yyyy年MM月"), 28,650, 1566);
    //加图片元素：盖章
//      combiner.addImageElement("https://oss.wsdns.cn/20250304/6936b109b09b4919a3498ac5027e728b.png", 600, 1420);

    // 使用支持中文的字体添加文本
    if (item.getType().equals(0)) {
      combiner.addTextElement(item.getName().concat(" 校友"), chineseFont, 160, 1008);
    } else {
      combiner.addTextElement(item.getName(), chineseFont, 160, 1008);
    }

//      combiner.addTextElement(DateUtil.format(DateUtil.date(), "yyyy年MM月"), 28,650, 1566);
    //加图片元素：盖章
//      combiner.addImageElement("https://oss.wsdns.cn/20250304/6936b109b09b4919a3498ac5027e728b.png", 600, 1420);
    //执行图片合并
    combiner.combine();
    return combiner;
  }

  /**
   * 创建支持中文的字体
   * @param fontSize 字体大小
   * @return Font对象
   */
  private static Font createChineseFont(int fontSize) {
    try {
      // 尝试使用系统中文字体
      String[] chineseFonts = {
        "Alibaba PuHuiTi 2.0",
        "PingFang SC",         // 苹方 (macOS) - 优先使用
        "STHeiti",             // 华文黑体 (macOS)
        "Hiragino Sans GB",    // 冬青黑体 (macOS)
        "Microsoft YaHei",     // 微软雅黑 (Windows)
        "SimHei",              // 黑体 (Windows)
        "SimSun",              // 宋体 (Windows)
        "WenQuanYi Micro Hei", // 文泉驿微米黑 (Linux)
        "Noto Sans CJK SC",    // 思源黑体 (Linux)
        "Arial Unicode MS",    // 支持Unicode的Arial
        "DejaVu Sans"          // 备用字体
      };

      for (String fontName : chineseFonts) {
        Font font = new Font(fontName, Font.PLAIN, fontSize);
        // 检查字体是否能正确显示中文
        if (font.canDisplay('中') && font.canDisplay('文')) {
          System.out.println("✓ 成功使用字体: " + fontName + " (字号: " + fontSize + ")");
          return font;
        } else {
          System.out.println("✗ 字体不支持中文: " + fontName);
        }
      }

      // 如果没有找到合适的字体，尝试加载系统默认中文字体
      System.out.println("⚠ 警告：未找到预定义的中文字体，尝试使用系统默认字体");

      // 尝试使用逻辑字体名称，这些在Java中通常会映射到系统字体
      String[] logicalFonts = {"SansSerif", "Serif", "Monospaced", "Dialog", "DialogInput"};
      for (String logicalFont : logicalFonts) {
        Font font = new Font(logicalFont, Font.PLAIN, fontSize);
        if (font.canDisplay('中') && font.canDisplay('文')) {
          System.out.println("✓ 使用逻辑字体: " + logicalFont);
          return font;
        }
      }

      // 最后的备选方案
      System.err.println("❌ 严重警告：系统中没有找到任何支持中文的字体！请安装中文字体包。");
      return new Font("SansSerif", Font.PLAIN, fontSize);

    } catch (Exception e) {
      System.err.println("❌ 创建中文字体失败: " + e.getMessage());
      e.printStackTrace();
      return new Font("SansSerif", Font.PLAIN, fontSize);
    }
  }

  @Override
  public BszxBm getByUserId(Integer userId) {
    return getOne(new LambdaQueryWrapper<BszxBm>().eq(BszxBm::getUserId, userId).last("limit 1"));
  }
}
