package com.gxwebsoft.house.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 cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freewayso.image.combiner.ImageCombiner;
import com.freewayso.image.combiner.enums.OutputFormat;
import com.freewayso.image.combiner.enums.ZoomMode;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.utils.ImageUtil;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.system.controller.WxLoginController;
import com.gxwebsoft.common.system.service.SettingService;
import com.gxwebsoft.house.mapper.HouseInfoMapper;
import com.gxwebsoft.house.service.HouseInfoService;
import com.gxwebsoft.house.entity.HouseInfo;
import com.gxwebsoft.house.param.HouseInfoParam;
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.awt.*;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 房源信息表Service实现
 *
 * @author 科技小王子
 * @since 2025-03-05 13:47:14
 */
@Service
public class HouseInfoServiceImpl extends ServiceImpl<HouseInfoMapper, HouseInfo> implements HouseInfoService {

  @Value("${config.upload-path}")
  private String uploadPath;

  @Value("${config.file-server}")
  private String fileServer;

  @Resource
  private ConfigProperties config;

  @Resource
  private SettingService settingService;

  @Resource
  private RedisUtil redisUtil;
  @Resource
  private WxLoginController wxLoginController;

  private static final String ACCESS_TOKEN_KEY = "cache:wx:access_token";

  @Override
  public PageResult<HouseInfo> pageRel(HouseInfoParam param) {
    PageParam<HouseInfo, HouseInfoParam> page = new PageParam<>(param);
    // 只有在没有指定排序场景时才设置默认排序
    if (param.getSortScene() == null || param.getSortScene().isEmpty()) {
      page.setDefaultOrder("create_time desc");
    }
    List<HouseInfo> list = baseMapper.selectPageRel(page, param);
    return new PageResult<>(list, page.getTotal());
  }

  @Override
  public List<HouseInfo> listRel(HouseInfoParam param) {
    List<HouseInfo> list = baseMapper.selectListRel(param);
    // 排序
    PageParam<HouseInfo, HouseInfoParam> page = new PageParam<>();
    // 只有在没有指定排序场景时才使用默认排序
    if (param.getSortScene() == null || param.getSortScene().isEmpty()) {
      page.setDefaultOrder("create_time desc");
    }
    return page.sortRecords(list);
  }

  @Override
  public HouseInfo getByIdRel(Integer houseId) {
    HouseInfoParam param = new HouseInfoParam();
    param.setHouseId(houseId);
    return param.getOne(baseMapper.selectListRel(param));
  }

  /**
   * 生成房产海报 <a href="https://portrait.gitee.com/sGodT/image-combiner">...</a>
   *
   * @param houseInfo 房源信息
   * @return 海报图片URL
   * @throws Exception 异常
   */
  @Override
  public String generatePoster(HouseInfo houseInfo) throws Exception {
    if (ObjectUtil.isEmpty(houseInfo)) {
      return null;
    }

    // 解析房源图片文件
    final String files = houseInfo.getFiles();
    if (StrUtil.isBlank(files)) {
      return null;
    }

    System.out.println("房源图片文件: " + files);

    try {
      // 解析JSON数组格式的图片文件
      JSONArray fileArray = JSONArray.parseArray(files);
      if (fileArray == null || fileArray.isEmpty()) {
        return null;
      }

      // 获取第一张图片作为主图
      JSONObject firstFile = fileArray.getJSONObject(0);
      if (firstFile == null) {
        return null;
      }

      String mainImageUrl = firstFile.getString("url");
      if (StrUtil.isBlank(mainImageUrl)) {
        return null;
      }

      ImageCombiner combiner = new ImageCombiner(mainImageUrl, OutputFormat.JPG);
      // 房源信息区域开始Y坐标
      int infoStartY = 330;
      int lineHeight = 40; // 增加行高
      int currentY = infoStartY;

      // 添加房源标题（黑色文字，居中）
      if (StrUtil.isNotBlank(houseInfo.getHouseTitle())) {
        combiner.addTextElement(houseInfo.getHouseTitle(), 32, 50, currentY)
                .setColor(Color.YELLOW)
                .setCenter(true);
        currentY += lineHeight + 10; // 标题后多留空间
      }

      // 添加房源价格信息（红色突出显示，居中）
      if (houseInfo.getRent() != null) {
        String priceText = "租金: ¥" + houseInfo.getRent();
        if (houseInfo.getMonthlyRent() != null) {
          priceText += "/月";
        }
        combiner.addTextElement(priceText, 26, 50, currentY)
                .setColor(Color.RED)
                .setCenter(true);
        currentY += lineHeight;
      }

      // 添加房源基本信息
      StringBuilder infoText = new StringBuilder();
      if (StrUtil.isNotBlank(houseInfo.getHouseType())) {
        infoText.append(houseInfo.getHouseType());
      }
      if (StrUtil.isNotBlank(houseInfo.getExtent())) {
        if (infoText.length() > 0) infoText.append(" | ");
        infoText.append(houseInfo.getExtent());
      }
      if (StrUtil.isNotBlank(houseInfo.getFloor())) {
        if (infoText.length() > 0) infoText.append(" | ");
        infoText.append(houseInfo.getFloor());
      }

//      if (infoText.length() > 0) {
//        combiner.addTextElement(infoText.toString(), 22, 50, currentY)
//                .setColor(Color.LIGHT_GRAY)
//                .setCenter(true);
//      }

      // 生成并添加小程序码（左上角）
      String qrCodeUrl = generateMiniProgramQRCode(houseInfo.getHouseId());
      if (StrUtil.isNotBlank(qrCodeUrl)) {
        // 小程序码放在左上角，尺寸占宽度20%（600*0.2=120px）
//        combiner.addImageElement(qrCodeUrl, 30, 30)
//                .setX(5);
          combiner.addImageElement(qrCodeUrl,40,40,150,150, ZoomMode.Width);
      }

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

      // 创建保存目录
      String posterDir = uploadPath + "/file/poster/" + houseInfo.getTenantId() + "/house";
      if (!FileUtil.exist(posterDir)) {
        FileUtil.mkdir(posterDir);
      }

      // 生成文件路径
      String basePath = "/poster/" + houseInfo.getTenantId() + "/house/big-" + houseInfo.getHouseId() + ".jpg";
      String smallPath = "/poster/" + houseInfo.getTenantId() + "/house/" + houseInfo.getHouseId() + ".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();
      }

      // 返回图片访问URL
      return fileServer + smallPath + "?r=" + RandomUtil.randomNumbers(4);

    } catch (Exception e) {
      System.err.println("生成房产海报失败: " + e.getMessage());
      e.printStackTrace();
      throw e;
    }
  }

  /**
   * 生成房源详情页小程序码
   *
   * @param houseId 房源ID
   * @return 小程序码图片URL
   */
  private String generateMiniProgramQRCode(Integer houseId) {
    try {
      String apiUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + wxLoginController.getAccessToken();
      final HashMap<String, Object> map = new HashMap<>();
      // 设置小程序页面路径：sub_pages/house/detail/ + houseId
      map.put("path", "sub_pages/house/detail/?houseId=" + houseId);
      // 可以设置环境版本，如果需要的话
//       map.put("env_version", "trial");

      // 获取图片 Buffer
      byte[] qrCode = HttpRequest.post(apiUrl)
              .body(JSON.toJSONString(map))
              .execute().bodyBytes();

      // 保存的文件名称
      final String fileName = CommonUtil.randomUUID8().concat(".png");
      // 保存路径
      String filePath = getUploadDir().concat("qrcode/house/") + fileName;

      // 确保目录存在
      String qrCodeDir = getUploadDir().concat("qrcode/house/");
      if (!FileUtil.exist(qrCodeDir)) {
        FileUtil.mkdir(qrCodeDir);
      }

      File file = FileUtil.writeBytes(qrCode, filePath);
      if (file != null) {
        return config.getFileServer().concat("/qrcode/house/").concat(fileName);
      }
    } catch (Exception e) {
      System.err.println("生成房源小程序码失败: " + e.getMessage());
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 获取微信小程序Access Token
   *
   * @return access_token
   */
//  private String getAccessToken() {
//    String key = ACCESS_TOKEN_KEY.concat(":").concat("1"); // 这里可以根据实际情况获取tenantId
//    System.out.println("key = " + key);
//    // 获取微信小程序配置信息
//    JSONObject setting = settingService.getBySettingKey("mp-weixin");
//    if (setting == null) {
//      throw new RuntimeException("请先配置小程序");
//    }
//
//    // 从缓存获取access_token
//    String value = redisUtil.get(key);
//    System.out.println("redisTemplate-value = " + value);
//    if (value != null) {
//      JSONObject response = JSON.parseObject(value);
//      String accessToken = response.getString("access_token");
//      if (StrUtil.isNotBlank(accessToken)) {
//        return accessToken;
//      }
//    }
//
//    // 微信获取凭证接口
//    String apiUrl = "https://api.weixin.qq.com/cgi-bin/token";
//    // 组装url参数
//    String url = apiUrl.concat("?grant_type=client_credential")
//            .concat("&appid=").concat(setting.getString("appId"))
//            .concat("&secret=").concat(setting.getString("appSecret"));
//
//    // 执行get请求
//    String result = cn.hutool.http.HttpUtil.get(url);
//    System.out.println("获取access_token结果: " + result);
//
//    // 解析access_token
//    JSONObject response = JSON.parseObject(result);
//    if (response.getString("access_token") != null) {
//      // 存入缓存
//      redisUtil.set(key, result, 7000L, TimeUnit.SECONDS);
//      return response.getString("access_token");
//    }
//
//    throw new RuntimeException("小程序配置不正确");
//  }

  /**
   * 文件上传位置(服务器)
   */
  private String getUploadDir() {
    return config.getUploadPath() + "file/";
  }

}
