package com.gxwebsoft.cms.service.impl;

import com.gxwebsoft.cms.entity.CmsNavigation;
import com.gxwebsoft.cms.entity.CmsWebsite;
import com.gxwebsoft.shop.vo.MenuVo;
import com.gxwebsoft.shop.vo.ShopVo;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * CmsWebsiteServiceImpl 辅助方法
 * 包含转换和处理逻辑
 */
public class CmsWebsiteServiceImplHelper {

    /**
     * 处理过期时间，只处理真正需要的字段
     */
    public static void processExpirationTime(CmsWebsite website) {
        if (website.getExpirationTime() != null) {
            LocalDateTime now = LocalDateTime.now();
            Date expirationTimeDate = website.getExpirationTime();

            // 将Date转换为LocalDateTime进行计算
            LocalDateTime expirationTime = expirationTimeDate.toInstant()
                    .atZone(java.time.ZoneId.systemDefault())
                    .toLocalDateTime();

            // 计算是否即将过期（30天内过期）
            LocalDateTime thirtyDaysLater = now.plusDays(30);
            website.setSoon(expirationTime.isBefore(thirtyDaysLater) ? 1 : 0);

            // 计算是否已过期
            website.setExpired(expirationTime.isBefore(now) ? -1 : 1);

            // 计算剩余天数
            long daysBetween = ChronoUnit.DAYS.between(now, expirationTime);
            website.setExpiredDays(daysBetween);
        } else {
            // 没有过期时间的默认值
            website.setSoon(0);
            website.setExpired(1);
            website.setExpiredDays(0L);
        }
    }

  /**
   * 将实体对象转换为VO对象
   */
  public static ShopVo convertToVO(CmsWebsite website) {
    ShopVo vo = new ShopVo();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    // 基本信息
    vo.setAppId(website.getTenantId());
    vo.setAppName(website.getTenantName());
    vo.setTitle(website.getWebsiteName());
    vo.setKeywords(website.getKeywords());
    vo.setDescription(website.getComments());
    vo.setLogo(website.getWebsiteLogo());
    vo.setMpQrCode(website.getWebsiteDarkLogo());
    vo.setDomain(website.getDomain());
    vo.setAdminUrl(website.getAdminUrl());
    vo.setApiUrl(website.getApiUrl());
    vo.setRunning(website.getRunning());
    vo.setVersion(website.getVersion());
    if (website.getCreateTime() != null) {
      // 将Date转换为LocalDateTime后格式化
      LocalDateTime createTime = website.getCreateTime().toInstant()
              .atZone(java.time.ZoneId.systemDefault())
              .toLocalDateTime();
      vo.setCreateTime(createTime.format(formatter));
    }

    // 时间字段 - 格式化为字符串
    if (website.getExpirationTime() != null) {
      // 将Date转换为LocalDateTime后格式化
      LocalDateTime expirationTime = website.getExpirationTime().toInstant()
              .atZone(java.time.ZoneId.systemDefault())
              .toLocalDateTime();
      vo.setExpirationTime(expirationTime.format(formatter));
    }

    // 过期相关信息
    vo.setExpired(website.getExpired());
    vo.setExpiredDays(website.getExpiredDays());
    vo.setSoon(website.getSoon());

    // 状态信息
    vo.setStatusIcon(website.getStatusIcon());
    vo.setStatusText(website.getStatusText());

    // 复杂对象
    vo.setConfig(website.getConfig());
    vo.setServerTime(website.getServerTime());
    vo.setSetting(website.getSetting()); // CmsWebsiteSetting对象可以直接设置给Object类型

    // 导航信息
    vo.setTopNavs(convertNavigationToVO(website.getTopNavs()));
    vo.setBottomNavs(convertNavigationToVO(website.getBottomNavs()));

    return vo;
  }

  /**
   * 安全转换 target 字段为整数
   *
   * @param target 字符串类型的 target 值
   * @return 对应的整数值
   */
  private static Integer convertTargetToInteger(String target) {
    if (target == null) {
      return 0; // 默认值：当前窗口
    }

    switch (target.toLowerCase()) {
      case "_self":
        return 0; // 当前窗口
      case "_blank":
        return 1; // 新窗口
      default:
        // 如果是数字字符串，尝试直接转换
        try {
          return Integer.valueOf(target);
        } catch (NumberFormatException e) {
          // 转换失败时返回默认值
          return 0;
        }
    }
  }

  /**
   * 转换导航列表为VO
   * 整理导航栏目录结构(ShopInfo)
   */
  public static List<MenuVo> convertNavigationToVO(List<CmsNavigation> navigations) {
    if (navigations == null) {
      return null;
    }

    return navigations.stream().map(nav -> {
      MenuVo navVO = new MenuVo();
      navVO.setNavigationId(nav.getNavigationId());
      navVO.setTitle(nav.getTitle());
      navVO.setPath(nav.getPath());
      navVO.setIcon(nav.getIcon());
      navVO.setColor(nav.getColor());
      navVO.setParentId(nav.getParentId());
      navVO.setSort(nav.getSortNumber());
      navVO.setHide(nav.getHide());
      navVO.setTop(nav.getTop());
      navVO.setPath(nav.getPath());
      navVO.setTarget(convertTargetToInteger(nav.getTarget()));
      navVO.setModel(nav.getModel());

      // 递归处理子导航
      if (nav.getChildren() != null) {
        navVO.setChildren(convertNavigationToVO(nav.getChildren()));
      }

      return navVO;
    }).collect(Collectors.toList());
  }

  /**
   * 设置网站状态
   */
  public static void setWebsiteStatus(CmsWebsite website) {
    if (website.getRunning() != null) {
      switch (website.getRunning()) {
        case 0:
          website.setStatusIcon("🔴");
          website.setStatusText("未开通");
          break;
        case 1:
          website.setStatusIcon("🟢");
          website.setStatusText("正常运行");
          break;
        case 2:
          website.setStatusIcon("🟡");
          website.setStatusText("维护中");
          break;
        case 3:
          website.setStatusIcon("🔴");
          website.setStatusText("违规关停");
          break;
        default:
          website.setStatusIcon("❓");
          website.setStatusText("未知状态");
      }
    }
  }

  /**
   * 设置网站配置
   */
  public static void setWebsiteConfig(CmsWebsite website) {
    HashMap<String, Object> config = new HashMap<>();
    config.put("websiteName", website.getWebsiteName());
    config.put("websiteComments", website.getComments());
    config.put("websiteTitle", website.getWebsiteName());
    config.put("websiteKeywords", website.getKeywords());
    config.put("websiteDescription", website.getContent()); // 使用 content 字段作为描述
    config.put("websiteLogo", website.getWebsiteLogo());
    config.put("websiteIcon", website.getWebsiteIcon());
    config.put("domain", website.getDomain());
    website.setConfig(config);
  }

  /**
   * 设置服务器时间信息
   */
  public static void setServerTimeInfo(CmsWebsite website) {
    HashMap<String, Object> serverTime = new HashMap<>();
    LocalDateTime now = LocalDateTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    serverTime.put("currentTime", now.format(formatter));
    serverTime.put("timestamp", System.currentTimeMillis());
    serverTime.put("timezone", "Asia/Shanghai");

    website.setServerTime(serverTime);
  }

  /**
   * 设置网站设置信息
   */
  public static void setWebsiteSetting(CmsWebsite website) {
    // 这里可以根据需要设置网站的其他设置信息
    // 暂时设置为null，因为setting字段类型是CmsWebsiteSetting而不是HashMap
    website.setSetting(null);
  }
}
