package com.gxwebsoft.bszx.service.impl;

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 com.gxwebsoft.bszx.entity.BszxBm;
import com.gxwebsoft.bszx.mapper.BszxPayMapper;
import com.gxwebsoft.bszx.service.BszxBmService;
import com.gxwebsoft.bszx.service.BszxPayService;
import com.gxwebsoft.bszx.entity.BszxPay;
import com.gxwebsoft.bszx.param.BszxPayParam;
import com.gxwebsoft.cms.entity.CmsArticle;
import com.gxwebsoft.cms.service.CmsArticleService;
import com.gxwebsoft.common.core.utils.ImageUtil;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.List;

/**
 * 百色中学-捐款记录Service实现
 *
 * @author 科技小王子
 * @since 2025-03-06 22:50:25
 */
@Service
public class BszxPayServiceImpl extends ServiceImpl<BszxPayMapper, BszxPay> implements BszxPayService {
  @Value("${config.upload-path}")
  private String uploadPath;
  @Value("${config.file-server}")
  private String fileServer;

  @Resource
  private CmsArticleService cmsArticleService;
  @Resource
  public BszxBmService bszxBmService;
  @Resource
  private BszxPayService bszxPayService;

  @Override
  public PageResult<BszxPay> pageRel(BszxPayParam param) {
    PageParam<BszxPay, BszxPayParam> page = new PageParam<>(param);
    page.setDefaultOrder("price desc, create_time desc");
    List<BszxPay> list = baseMapper.selectPageRel(page, param);
    list.forEach(item -> {
      if(item.getId().equals(2088)){
        item.setFormName("捐款用于设立阙里校友奖学金");
      }
    });
    return new PageResult<>(list, page.getTotal());
  }

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

  @Override
  public BszxPay getByIdRel(Integer id) {
    BszxPayParam param = new BszxPayParam();
    param.setId(id);
    final BszxPay item = param.getOne(baseMapper.selectListRel(param));
    final CmsArticle article = cmsArticleService.getById(item.getFormId());
    if (ObjectUtil.isNotEmpty(article)) {
      item.setArticle(article);
    }
    return item;
  }

  /**
   * 生成捐款证书 <a href="https://portrait.gitee.com/sGodT/image-combiner">...</a>
   */
  @Override
  public String generatePayCert(Integer id) throws Exception {
    final BszxPay payCert = getByIdRel(id);
    final CmsArticle item = cmsArticleService.getById(payCert.getFormId());
    final BszxBm bm = bszxBmService.getOne(new LambdaQueryWrapper<BszxBm>().eq(BszxBm::getUserId, payCert.getUserId()).last("limit 1"));
    final BigDecimal totalMoney = bszxPayService.sumMoney(new LambdaQueryWrapper<BszxPay>().eq(BszxPay::getUserId, payCert.getUserId()));
    if (StrUtil.isBlank(item.getAddress())) {
      return null;
    }
    if (ObjectUtil.isNotEmpty(payCert)) {
      //合成器（指定背景图和输出格式，整个图片的宽高和相关计算依赖于背景图，所以背景图的大小是个基准）
      ImageCombiner combiner = new ImageCombiner("https://oss.wsdns.cn/20250420/811a380e8e124097aa0940a7c68a1f72.jpeg", OutputFormat.JPG);
      //加图片元素：盖章
//      combiner.addImageElement("https://oss.wsdns.cn/20250304/6936b109b09b4919a3498ac5027e728b.png", 550, 926);
      //加文本元素：姓名
      String str;
      if (bm.getType().equals(0)) {
        str = bm.getName().concat(" 校友");
        combiner.addTextElement(str, 32, 930, 450);
      } else {
        str = bm.getName();
        combiner.addTextElement(str, 22, 880, 450);
      }
//      combiner.addTextElement(bm.getName(), 32,900, 450);
      //加文本元素：捐款证书内容
//      combiner.addTextElement("       承您慷慨解囊，襄助百色市百色中学", 32,200, 650);
//      combiner.addTextElement("百廿校庆“" + item.getTitle() + "”项目，捐赠人民币", 32,200, 700);
      combiner.addTextElement(totalMoney + "", 32, 1330, 600);
//      combiner.addTextElement("       您对学校的支持，为我们共同教育理", 32,200, 800);
//      combiner.addTextElement("想的实现增添了一份动力。", 32,200, 850);
//      combiner.addTextElement("       承蒙惠赠，隆情铭感，特颁此证，以资谢旌！", 32, 200, 900);
//      combiner.addTextElement("百色市百色中学", 32,560, 1015);
//      final Date createTime = payCert.getCreateTime();
//      combiner.addTextElement(DateUtil.format(createTime, "yyyy年MM月"), 28,586, 1060);
//      combiner.addTextElement("2025年4月15日", 28,580, 1060);

      //执行图片合并
      combiner.combine();

      if (!FileUtil.exist(uploadPath + "/file/poster/" + payCert.getTenantId() + "/pay")) {
        FileUtil.mkdir(uploadPath + "/file/poster/" + payCert.getTenantId() + "/pay");
      }
      String basePath = "/poster/" + payCert.getTenantId() + "/pay/big-" + id + ".jpg";
      String smallPath = "/poster/" + payCert.getTenantId() + "/pay/" + id + ".jpg";
      String filename = uploadPath + "/file" + basePath;
      String smallFileName = uploadPath + "/file" + 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;
  }

  @Override
  public BigDecimal sumMoney(LambdaQueryWrapper<BszxPay> wrapper) {
    return baseMapper.selectSumMoney(wrapper);
  }

  @Override
  public BigDecimal total() {
    try {
      // 使用数据库聚合查询统计捐款总金额，性能更高
      LambdaQueryWrapper<BszxPay> wrapper = new LambdaQueryWrapper<>();
      BigDecimal total = baseMapper.selectSumMoney(wrapper);

      if (total == null) {
        total = BigDecimal.ZERO;
      }

      return total;

    } catch (Exception e) {
      // 异常时返回0，确保接口稳定性
      return BigDecimal.ZERO;
    }
  }
}
