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 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.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.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)) {
      //      Font font = new Font("阿里巴巴普惠体", Font.PLAIN, 40);
      //合成器（指定背景图和输出格式，整个图片的宽高和相关计算依赖于背景图，所以背景图的大小是个基准）
      ImageCombiner combiner = new ImageCombiner(article.getAddress(), OutputFormat.JPG);
      //加文本元素：姓名
//      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(" 校友"), 30, 160, 1008);
      } else {
        combiner.addTextElement(item.getName(), 30, 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();

      if (!FileUtil.exist(uploadPath + "/file/poster/" + item.getTenantId() + "/bm")) {
        FileUtil.mkdir(uploadPath + "/file/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 + "/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 BszxBm getByUserId(Integer userId) {
    return getOne(new LambdaQueryWrapper<BszxBm>().eq(BszxBm::getUserId, userId).last("limit 1"));
  }
}
