package com.gxwebsoft.cms.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.gxwebsoft.cms.entity.CmsPage;
import com.gxwebsoft.cms.param.CmsPageParam;
import com.gxwebsoft.cms.service.CmsPageService;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 单页管理控制器
 *
 * @author WorkBuddy
 * @since 2026-07-29
 */
@Tag(name = "单页管理")
@RestController
@RequestMapping("/api/cms/cms-page")
public class CmsPageController extends BaseController {

    @Resource
    private CmsPageService cmsPageService;

    @Operation(summary = "分页查询单页")
    @GetMapping("/page")
    public ApiResult<PageResult<CmsPage>> page(CmsPageParam param) {
        return success(cmsPageService.pageRel(param));
    }

    @Operation(summary = "查询全部单页")
    @GetMapping()
    public ApiResult<List<CmsPage>> list(CmsPageParam param) {
        return success(cmsPageService.listRel(param));
    }

    @Operation(summary = "根据id查询单页")
    @GetMapping("/{id}")
    public ApiResult<CmsPage> get(@PathVariable("id") Integer id) {
        final CmsPage page = cmsPageService.getByIdRel(id);
        if (ObjectUtil.isNotEmpty(page)) {
            return success(page);
        }
        return fail("单页ID不存在", null);
    }

    @Operation(summary = "根据path查询已发布单页(供公开站)")
    @GetMapping("/getByPath/{path}")
    public ApiResult<CmsPage> getByPath(@PathVariable("path") String path) {
        final CmsPage page = cmsPageService.getPublishedByPath(path);
        // 公开站约定：data 为空表示页面不存在或未发布
        return success(page);
    }

    @Operation(summary = "添加单页")
    @PreAuthorize("hasAuthority('cms:cmsPage:save')")
    @PostMapping()
    public ApiResult<?> save(@RequestBody CmsPage page) {
        User loginUser = getLoginUser();
        if (loginUser != null) {
            page.setTenantId(loginUser.getTenantId());
        }
        page.setTitle(StrUtil.trim(page.getTitle()));
        if (StrUtil.isBlank(page.getPath())) {
            return fail("访问路径(path)不能为空");
        }
        if (cmsPageService.saveRel(page)) {
            return success("添加成功");
        }
        // 区分是 path 重复还是其他失败
        if (cmsPageService.pathExists(page.getPath(), null)) {
            return fail("该访问路径(path)已被占用，请更换");
        }
        return fail("添加失败");
    }

    @Operation(summary = "修改单页")
    @PreAuthorize("hasAuthority('cms:cmsPage:update')")
    @PutMapping()
    public ApiResult<?> update(@RequestBody CmsPage page) {
        if (page.getPageId() == null) {
            return fail("缺少 pageId");
        }
        if (StrUtil.isNotBlank(page.getPath()) && cmsPageService.pathExists(page.getPath(), page.getPageId())) {
            return fail("该访问路径(path)已被占用，请更换");
        }
        if (cmsPageService.updateByIdRel(page)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @Operation(summary = "删除单页")
    @PreAuthorize("hasAuthority('cms:cmsPage:remove')")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (cmsPageService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @Operation(summary = "修改单页状态(草稿/发布/下线)")
    @PreAuthorize("hasAuthority('cms:cmsPage:update')")
    @PutMapping("/status")
    public ApiResult<?> updateStatus(@RequestBody Map<String, Object> body) {
        Object idObj = body.get("pageId");
        Object statusObj = body.get("status");
        if (idObj == null) {
            return fail("缺少 pageId");
        }
        CmsPage entity = new CmsPage();
        entity.setPageId(((Number) idObj).intValue());
        if (statusObj != null) {
            entity.setStatus(((Number) statusObj).intValue());
        }
        if (cmsPageService.updateById(entity)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }
}
