package com.gxwebsoft.cms.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.cms.entity.*;
import com.gxwebsoft.cms.param.CmsNavigationParam;
import com.gxwebsoft.cms.service.CmsNavigationService;
import com.gxwebsoft.cms.service.CmsWebsiteFieldService;
import com.gxwebsoft.cms.service.CmsWebsiteSettingService;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.cms.service.CmsWebsiteService;
import com.gxwebsoft.cms.param.CmsWebsiteParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

import java.util.concurrent.TimeUnit;

/**
 * 网站信息记录表控制器
 *
 * @author 科技小王子
 * @since 2024-09-10 20:36:14
 */
@Slf4j
@Tag(name = "网站信息记录表管理")
@RestController
@RequestMapping("/api/cms/cms-website")
public class CmsWebsiteController extends BaseController {
  @Resource
  private CmsWebsiteService cmsWebsiteService;
  @Resource
  private RedisUtil redisUtil;
  @Resource
  private CmsWebsiteFieldService cmsWebsiteFieldService;
  @Resource
  private CmsNavigationService cmsNavigationService;
  @Resource
  private CmsWebsiteSettingService cmsWebsiteSettingService;

  private static final String SITE_INFO_KEY_PREFIX = "SiteInfo:";
  private static final String MP_INFO_KEY_PREFIX = "MpInfo:";
  private static final String SELECT_PAYMENT_KEY_PREFIX = "SelectPayment:";
  private static final String SYS_DOMAIN_SUFFIX = ".websoft.top";
  private static final String DOMAIN_SUFFIX = ".wsdns.cn";

  @Operation(summary = "分页查询网站信息记录表")
  @GetMapping("/page")
  public ApiResult<PageResult<CmsWebsite>> page(CmsWebsiteParam param) {
    // 使用关联查询
    return success(cmsWebsiteService.pageRel(param));
  }

  @Operation(summary = "查询全部网站信息记录表")
  @GetMapping()
  public ApiResult<List<CmsWebsite>> list(CmsWebsiteParam param) {
    // 使用关联查询
    return success(cmsWebsiteService.listRel(param));
  }

  @Operation(summary = "分页查询网站信息记录表")
  @GetMapping("/pageAll")
  public ApiResult<PageResult<CmsWebsite>> pageAll(CmsWebsiteParam param) {
    return success(cmsWebsiteService.pageRelAll(param));
  }

  @Operation(summary = "根据id查询网站信息记录表")
  @GetMapping("/{id}")
  public ApiResult<CmsWebsite> get(@PathVariable("id") Integer id) {
    // 使用关联查询
    return success(cmsWebsiteService.getByIdRel(id));
  }

  @Operation(summary = "根据id查询网站信息记录表")
  @GetMapping("/getAll/{id}")
  public ApiResult<CmsWebsite> getAll(@PathVariable("id") Integer id) {
    // 使用关联查询
    return success(cmsWebsiteService.getByIdRelAll(id));
  }

  // 注册流程：新租户超管尚未被 grantCmsPermission 赋予 cms:website:save，允许超管直接创建首个站点
  @PreAuthorize("hasAuthority('cms:website:save') or principal.getIsSuperAdmin() == true")
  @Operation(summary = "添加网站信息记录表")
  @PostMapping()
  public ApiResult<?> save(@RequestBody CmsWebsite cmsWebsite) {
    // 前端若指定了 websiteCode，先做唯一性校验
    if (StrUtil.isNotBlank(cmsWebsite.getWebsiteCode())) {
      long cnt = cmsWebsiteService.count(
          new LambdaQueryWrapper<CmsWebsite>()
              .eq(CmsWebsite::getWebsiteCode, cmsWebsite.getWebsiteCode())
      );
      if (cnt > 0) {
        return fail("应用标识 [" + cmsWebsite.getWebsiteCode() + "] 已存在，请更换");
      }
    }
    // 记录当前登录用户id
    User loginUser = getLoginUser();
    if (loginUser != null) {
      // 防重复建站：同一租户已存在站点时拒绝新增，
      // 避免并发请求/重复点击建出多条记录（getSiteInfo 仅取 limit 1，多余记录会成为孤儿数据）
      if (ObjectUtil.isNotEmpty(loginUser.getTenantId())) {
        long exist = cmsWebsiteService.count(
            new LambdaQueryWrapper<CmsWebsite>()
                .eq(CmsWebsite::getTenantId, loginUser.getTenantId())
                .eq(CmsWebsite::getDeleted, 0)
        );
        if (exist > 0) {
          return fail("当前租户已存在站点，请勿重复创建");
        }
      }
      cmsWebsite.setLoginUser(loginUser);
      return success("创建成功", cmsWebsiteService.create(cmsWebsite));
    }
    return fail("创建失败");
  }

  // 注册流程：新租户超管尚未被 grantCmsPermission 赋予 cms:website:update，允许超管直接更新站点
  @PreAuthorize("hasAuthority('cms:website:update') or principal.getIsSuperAdmin() == true")
  @Operation(summary = "修改网站信息记录表")
  @PutMapping()
  public ApiResult<?> update(@RequestBody CmsWebsite cmsWebsite) {
    // websiteCode 全局唯一，有值时校验是否与其他记录冲突（排除自身）
    if (StrUtil.isNotBlank(cmsWebsite.getWebsiteCode())) {
      long cnt = cmsWebsiteService.count(
          new LambdaQueryWrapper<CmsWebsite>()
              .eq(CmsWebsite::getWebsiteCode, cmsWebsite.getWebsiteCode())
              .ne(CmsWebsite::getWebsiteId, cmsWebsite.getWebsiteId())
      );
      if (cnt > 0) {
        return fail("应用标识 [" + cmsWebsite.getWebsiteCode() + "] 已存在，请更换");
      }
    } else {
      // 不允许通过此接口清空或修改 websiteCode（设为 null 则 MP 不更新该字段）
      cmsWebsite.setWebsiteCode(null);
    }
    if (cmsWebsiteService.updateById(cmsWebsite)) {
      // 站点信息（含 domain / templateId 等）有 1 天 Redis 缓存，改完必须立刻失效，
      // 否则公开站与后台链接拼接最长 1 天读到旧值（与 CmsNavigationController 写操作保持一致）。
      clearSiteInfoCacheQuietly();
      return success("修改成功");
    }
    return fail("修改失败");
  }

  // 注册流程：新租户超管尚未被 grantCmsPermission 赋予 cms:website:update，允许超管直接更新站点
  @PreAuthorize("hasAuthority('cms:website:update') or principal.getIsSuperAdmin() == true")
  @Operation(summary = "修改网站信息记录表")
  @PutMapping("/updateAll")
  public ApiResult<?> updateAll(@RequestBody CmsWebsite cmsWebsite) {
    if (cmsWebsiteService.updateByIdAll(cmsWebsite)) {
      clearSiteInfoCacheQuietly();
      return success("修改成功");
    }
    return fail("修改失败");
  }

  /**
   * 清除当前租户的站点信息缓存。
   * 缓存失效属于写操作的附带动作，异常不应影响主流程（更新本身已成功）。
   */
  private void clearSiteInfoCacheQuietly() {
    try {
      Integer tenantId = getTenantId();
      if (ObjectUtil.isEmpty(tenantId)) {
        return;
      }
      redisUtil.delete(SITE_INFO_KEY_PREFIX.concat(tenantId.toString()));
      redisUtil.delete(MP_INFO_KEY_PREFIX.concat(tenantId.toString()));
      log.info("已清除站点信息缓存，租户ID: {}", tenantId);
    } catch (Exception e) {
      log.warn("清除站点信息缓存失败: {}", e.getMessage());
    }
  }

  @PreAuthorize("hasAuthority('cms:website:remove')")
  @Operation(summary = "删除网站信息记录表")
  @DeleteMapping("/{id}")
  public ApiResult<?> remove(@PathVariable("id") Integer id) {
    if (cmsWebsiteService.removeById(id)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }

  @PreAuthorize("hasAuthority('cms:website:remove')")
  @Operation(summary = "删除网站信息记录表")
  @DeleteMapping("/removeAll/{id}")
  public ApiResult<?> removeAll(@PathVariable("id") Integer id) {
    if (cmsWebsiteService.removeByIdAll(id)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }

  @PreAuthorize("hasAuthority('cms:website:save')")
  @Operation(summary = "批量添加网站信息记录表")
  @PostMapping("/batch")
  public ApiResult<?> saveBatch(@RequestBody List<CmsWebsite> list) {
    if (cmsWebsiteService.saveBatch(list)) {
      return success("添加成功");
    }
    return fail("添加失败");
  }

  @PreAuthorize("hasAuthority('cms:website:update')")
  @Operation(summary = "批量修改网站信息记录表")
  @PutMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody BatchParam<CmsWebsite> batchParam) {
    if (batchParam.update(cmsWebsiteService, "website_id")) {
      return success("修改成功");
    }
    return fail("修改失败");
  }

  @PreAuthorize("hasAuthority('cms:website:remove')")
  @Operation(summary = "批量删除网站信息记录表")
  @DeleteMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
    if (cmsWebsiteService.removeByIds(ids)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }

  @Operation(summary = "网站基本信息")
  @GetMapping("/getSiteInfo")
  public ApiResult<CmsWebsite> getSiteInfo() {
    log.info("开始获取网站基本信息...");
    try {
      Integer tenantId = getTenantId();
      log.info("获取到租户ID: {}", tenantId);
      if (ObjectUtil.isEmpty(tenantId)) {
        log.warn("租户ID为空");
        return fail("租户ID不能为空", null);
      }

      String key = SITE_INFO_KEY_PREFIX + tenantId;

      // 尝试从缓存获取
      try {
        final String siteInfo = redisUtil.get(key);
        if (StrUtil.isNotBlank(siteInfo)) {
          log.info("从缓存获取网站信息： = {}", key);
          // 可以启用缓存返回，但先注释掉确保数据最新
          // return success(JSONUtil.parseObject(siteInfo, CmsWebsite.class));
        }
      } catch (Exception e) {
        log.warn("获取缓存失败: {}", e.getMessage());
      }

      // 获取站点信息
      CmsWebsite website = null;
      try {
        log.info("开始查询租户{}的站点信息", tenantId);
        website = cmsWebsiteService.getOne(new LambdaQueryWrapper<CmsWebsite>()
            .eq(CmsWebsite::getTenantId, tenantId)
            .eq(CmsWebsite::getDeleted, 0)
            .last("limit 1"));
        log.info("查询站点信息完成, website: {}", website != null ? "存在" : "不存在");
      } catch (Exception e) {
        log.error("查询站点信息失败: {}", e.getMessage(), e);
        return fail("查询站点信息失败: " + e.getMessage(), null);
      }

      // 创建默认站点
      if (ObjectUtil.isEmpty(website)) {
        return success("请先创建站点...", null);
      }

      // 安全地构建网站信息
      try {
        buildSafeWebsiteInfo(website);
      } catch (Exception e) {
        log.error("构建网站信息失败: {}", e.getMessage(), e);
        return fail("构建网站信息失败", null);
      }

      // 缓存结果
      try {
        redisUtil.set(key, website, 1L, TimeUnit.DAYS);
      } catch (Exception e) {
        log.warn("缓存网站信息失败: {}", e.getMessage());
      }

      return success(website);

    } catch (Exception e) {
      log.error("获取网站信息异常: {}", e.getMessage(), e);
      return fail("获取网站信息失败: " + e.getMessage(), null);
    }
  }

  /**
   * 安全地构建网站信息
   */
  private void buildSafeWebsiteInfo(CmsWebsite website) {
    if (website == null) {
      throw new IllegalArgumentException("网站对象不能为空");
    }

    // 1. 设置网站状态
    try {
      setWebsiteStatus(website);
    } catch (Exception e) {
      log.warn("设置网站状态失败: {}", e.getMessage());
      website.setStatus(0); // 默认状态
      website.setStatusText("状态未知");
    }

    // 2. 构建配置信息
    try {
      HashMap<String, Object> config = buildSafeWebsiteConfig(website);
      website.setConfig(config);
    } catch (Exception e) {
      log.warn("构建网站配置失败: {}", e.getMessage());
      website.setConfig(new HashMap<>());
    }

    // 3. 设置导航信息
    try {
      setSafeWebsiteNavigation(website);
    } catch (Exception e) {
      log.warn("设置网站导航失败: {}", e.getMessage());
      website.setTopNavs(new ArrayList<>());
      website.setBottomNavs(new ArrayList<>());
    }

    // 4. 设置网站设置信息
    try {
      setWebsiteSetting(website);
    } catch (Exception e) {
      log.warn("设置网站设置失败: {}", e.getMessage());
      // 设置为null，让前端知道没有设置信息
    }

    // 5. 构建服务器时间（使用LocalDateTime）
    try {
      HashMap<String, Object> serverTime = buildSafeServerTime();
      website.setServerTime(serverTime);
    } catch (Exception e) {
      log.warn("构建服务器时间失败: {}", e.getMessage());
      HashMap<String, Object> defaultTime = new HashMap<>();
      defaultTime.put("now", java.time.LocalDateTime.now().toString());
      website.setServerTime(defaultTime);
    }
  }

  private void setWebsiteStatus(CmsWebsite website) {
    // 空值检查，避免NullPointerException
    Integer running = website.getRunning();
    if (running == null) {
      // 默认状态：未开通
      website.setStatusIcon("error");
      website.setStatusText("状态未知");
      return;
    }

    if (!running.equals(1)) {
      // 未开通
      if (running.equals(0)) {
        website.setStatusIcon("error");
        website.setStatusText("该站点未开通");
      }
      // 维护中
      if (running.equals(2)) {
        website.setStatusIcon("warning");
      }
      // 已关闭
      if (running.equals(3)) {
        website.setStatusIcon("error");
        website.setStatusText("已关闭");
      }
      // 已欠费停机
      if (running.equals(4)) {
        website.setStatusIcon("error");
        website.setStatusText("已欠费停机");
      }
      // 违规关停
      if (running.equals(5)) {
        website.setStatusIcon("error");
        website.setStatusText("违规关停");
      }
    }
  }

  private HashMap<String, Object> buildWebsiteConfig(CmsWebsite website) {
    return buildSafeWebsiteConfig(website);
  }

  private HashMap<String, Object> buildSafeWebsiteConfig(CmsWebsite website) {
    HashMap<String, Object> config = new HashMap<>();

    try {
      // 获取网站字段配置
      LambdaQueryWrapper<CmsWebsiteField> wrapper = new LambdaQueryWrapper<>();
      wrapper.eq(CmsWebsiteField::getDeleted, 0);
      final List<CmsWebsiteField> fields = cmsWebsiteFieldService.list(wrapper);

      if (fields != null && !fields.isEmpty()) {
        fields.forEach(field -> {
          if (field != null && StrUtil.isNotBlank(field.getName())) {
            config.put(field.getName(), field.getValue() != null ? field.getValue() : "");
          }
        });
      }
    } catch (Exception e) {
      log.warn("获取网站字段配置失败: {}", e.getMessage());
    }

    // 安全地设置域名信息
    try {
      config.put("SysDomain", getSafeSysDomain(website));
      config.put("Domain", getSafeDomain(website));
    } catch (Exception e) {
      log.warn("设置域名信息失败: {}", e.getMessage());
      config.put("SysDomain", website.getTenantId() + ".websoft.top");
      config.put("Domain", website.getTenantId() + ".wsdns.cn");
    }

    return config;
  }

  private String getSysDomain(CmsWebsite website) {
    return getSafeSysDomain(website);
  }

  private String getDomain(CmsWebsite website) {
    return getSafeDomain(website);
  }

  private String getSafeSysDomain(CmsWebsite website) {
    if (website == null || website.getTenantId() == null) {
      return "unknown.websoft.top";
    }
    return StrUtil.isNotBlank(website.getWebsiteCode()) ?
        website.getWebsiteCode() + SYS_DOMAIN_SUFFIX :
        website.getTenantId() + SYS_DOMAIN_SUFFIX;
  }

  private String getSafeDomain(CmsWebsite website) {
    if (website == null || website.getTenantId() == null) {
      return "unknown.wsdns.cn";
    }

    if (StrUtil.isNotBlank(website.getDomain())) {
      return website.getDomain();
    }
    if (StrUtil.isNotBlank(website.getWebsiteCode())) {
      return website.getWebsiteCode() + DOMAIN_SUFFIX;
    }
    return website.getTenantId() + DOMAIN_SUFFIX;
  }

  private void setWebsiteNavigation(CmsWebsite website) {
    setSafeWebsiteNavigation(website);
  }

  private void setSafeWebsiteNavigation(CmsWebsite website) {
    if (website == null) {
      return;
    }

    // 设置顶部导航
    try {
      final CmsNavigationParam topParam = new CmsNavigationParam();
      topParam.setHide(0);
      topParam.setTop(0);
      topParam.setBottom(null);
      final List<CmsNavigation> topNavs = cmsNavigationService.listRel(topParam);

      if (topNavs != null && !topNavs.isEmpty()) {
        try {
          website.setTopNavs(CommonUtil.toTreeData(topNavs, 0,
              CmsNavigation::getParentId,
              CmsNavigation::getNavigationId,
              CmsNavigation::setChildren));
        } catch (Exception e) {
          log.warn("构建顶部导航树失败: {}", e.getMessage());
          website.setTopNavs(new ArrayList<>(topNavs));
        }
      } else {
        website.setTopNavs(new ArrayList<>());
      }
    } catch (Exception e) {
      log.warn("获取顶部导航失败: {}", e.getMessage());
      website.setTopNavs(new ArrayList<>());
    }

    // 设置底部导航
    try {
      final CmsNavigationParam bottomParam = new CmsNavigationParam();
      bottomParam.setHide(0);
      bottomParam.setTop(null);
      bottomParam.setBottom(0);
      final List<CmsNavigation> bottomNavs = cmsNavigationService.listRel(bottomParam);

      if (bottomNavs != null && !bottomNavs.isEmpty()) {
        try {
          website.setBottomNavs(CommonUtil.toTreeData(bottomNavs, 0,
              CmsNavigation::getParentId,
              CmsNavigation::getNavigationId,
              CmsNavigation::setChildren));
        } catch (Exception e) {
          log.warn("构建底部导航树失败: {}", e.getMessage());
          website.setBottomNavs(new ArrayList<>(bottomNavs));
        }
      } else {
        website.setBottomNavs(new ArrayList<>());
      }
    } catch (Exception e) {
      log.warn("获取底部导航失败: {}", e.getMessage());
      website.setBottomNavs(new ArrayList<>());
    }
  }

  private void setWebsiteSetting(CmsWebsite website) {
    final CmsWebsiteSetting setting = cmsWebsiteSettingService.getOne(new LambdaQueryWrapper<CmsWebsiteSetting>().eq(CmsWebsiteSetting::getWebsiteId, website.getWebsiteId()));
    if (ObjectUtil.isNotEmpty(setting)) {
      website.setSetting(setting);
    }
  }

  private HashMap<String, Object> buildServerTime() {
    return buildSafeServerTime();
  }

  private HashMap<String, Object> buildSafeServerTime() {
    HashMap<String, Object> serverTime = new HashMap<>();

    try {
      // 使用 LocalDateTime 替代 DateTime
      java.time.LocalDateTime now = java.time.LocalDateTime.now();
      java.time.LocalDate today = java.time.LocalDate.now();

      // 当前时间
      serverTime.put("now", now.toString());

      // 今天日期
      serverTime.put("today", today.toString());

      // 明天日期
      java.time.LocalDate tomorrow = today.plusDays(1);
      serverTime.put("tomorrow", tomorrow.toString());

      // 后天日期
      java.time.LocalDate afterDay = today.plusDays(2);
      serverTime.put("afterDay", afterDay.toString());

      // 今天星期几 (1=Monday, 7=Sunday)
      int week = today.getDayOfWeek().getValue();
      serverTime.put("week", week);

      // 下周同一天
      java.time.LocalDate nextWeek = today.plusWeeks(1);
      serverTime.put("nextWeek", nextWeek.toString());

      // 时间戳
      serverTime.put("timestamp", System.currentTimeMillis());

    } catch (Exception e) {
      log.error("构建服务器时间失败: {}", e.getMessage(), e);
      // 提供最基本的时间信息
      serverTime.put("now", java.time.LocalDateTime.now().toString());
      serverTime.put("today", java.time.LocalDate.now().toString());
      serverTime.put("timestamp", System.currentTimeMillis());
    }

    return serverTime;
  }

  @Operation(summary = "清除缓存")
  @DeleteMapping("/clearSiteInfo/{key}")
  public ApiResult<?> clearSiteInfo(@PathVariable("key") String key) {
    log.info("清除缓存开始，key: {}", key);
    System.out.println("清除缓存开始，key = " + key);
    // 清除指定key
    redisUtil.delete(key);
    // 清除缓存
    redisUtil.delete(SITE_INFO_KEY_PREFIX.concat(getTenantId().toString()));
    log.info("清除缓存结束，key: {}", SITE_INFO_KEY_PREFIX.concat(getTenantId().toString()));
    // 清除小程序缓存
    redisUtil.delete(MP_INFO_KEY_PREFIX.concat(getTenantId().toString()));
    // 选择支付方式
    redisUtil.delete(SELECT_PAYMENT_KEY_PREFIX.concat(getTenantId().toString()));
    return success("清除成功");
  }

  // ─── 发布管理 ────────────────────────────────────────────────────────

  @Operation(summary = "提交上架审核")
  @PostMapping("/submitReview")
  public ApiResult<?> submitReview(@RequestBody Map<String, Object> body) {
    Integer websiteId = body.get("websiteId") instanceof Number ? ((Number) body.get("websiteId")).intValue() : null;
    if (websiteId == null) return fail("websiteId 不能为空");
    String priceType = (String) body.get("priceType");
    Integer price = body.get("price") instanceof Number ? ((Number) body.get("price")).intValue() : 0;
    String subscriptionPeriod = (String) body.get("subscriptionPeriod");
    String appDescription = (String) body.get("appDescription");
    String detailDescription = (String) body.get("detailDescription");
    String screenshots = (String) body.get("screenshots");
    Integer userId = getLoginUserId();
    try {
      cmsWebsiteService.submitReview(websiteId, priceType, price, subscriptionPeriod,
          appDescription, detailDescription, screenshots, userId);
      return success("上架申请提交成功，等待审核");
    } catch (Exception e) {
      return fail(e.getMessage());
    }
  }

  @Operation(summary = "撤回审核申请")
  @PostMapping("/withdrawReview/{websiteId}")
  public ApiResult<?> withdrawReview(@PathVariable Integer websiteId) {
    try {
      cmsWebsiteService.withdrawReview(websiteId, getLoginUserId());
      return success("已撤回审核申请");
    } catch (Exception e) {
      return fail(e.getMessage());
    }
  }

  @Operation(summary = "下架应用")
  @PostMapping("/unpublish/{websiteId}")
  public ApiResult<?> unpublish(@PathVariable Integer websiteId) {
    try {
      cmsWebsiteService.unpublish(websiteId, getLoginUserId());
      return success("已下架");
    } catch (Exception e) {
      return fail(e.getMessage());
    }
  }

  @PreAuthorize("hasAuthority('cms:website:update')")
  @Operation(summary = "管理员审核通过")
  @PostMapping("/approveReview/{websiteId}")
  public ApiResult<?> approveReview(@PathVariable Integer websiteId) {
    try {
      cmsWebsiteService.approveReview(websiteId, getLoginUserId());
      return success("审核通过，应用已上架");
    } catch (Exception e) {
      return fail(e.getMessage());
    }
  }

  @PreAuthorize("hasAuthority('cms:website:update')")
  @Operation(summary = "管理员审核拒绝")
  @PostMapping("/rejectReview")
  public ApiResult<?> rejectReview(@RequestBody Map<String, Object> body) {
    Integer websiteId = body.get("websiteId") instanceof Number ? ((Number) body.get("websiteId")).intValue() : null;
    String rejectReason = (String) body.get("rejectReason");
    if (websiteId == null) return fail("websiteId 不能为空");
    if (rejectReason == null || rejectReason.isBlank()) return fail("请填写拒绝原因");
    try {
      cmsWebsiteService.rejectReview(websiteId, rejectReason, getLoginUserId());
      return success("已拒绝该应用上架申请");
    } catch (Exception e) {
      return fail(e.getMessage());
    }
  }

  @PreAuthorize("hasAuthority('cms:website:update')")
  @Operation(summary = "获取审核列表（管理员）")
  @GetMapping("/pageReviews")
  public ApiResult<PageResult<CmsWebsite>> pageReviews(CmsWebsiteParam param) {
    return success(cmsWebsiteService.pageReviews(param));
  }

}

