package com.gxwebsoft.cms.controller;

import com.gxwebsoft.cms.entity.CmsBannerGroup;
import com.gxwebsoft.cms.entity.CmsBannerItem;
import com.gxwebsoft.cms.mapper.CmsBannerItemMapper;
import com.gxwebsoft.cms.param.CmsBannerGroupParam;
import com.gxwebsoft.cms.service.CmsBannerGroupService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
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;

/**
 * 轮播组管理控制器
 *
 * @author WorkBuddy
 * @since 2026-07-19
 */
@Tag(name = "轮播组管理")
@RestController
@RequestMapping("/api/cms/cms-banner-group")
public class CmsBannerGroupController extends BaseController {

    @Resource
    private CmsBannerGroupService cmsBannerGroupService;

    @Resource
    private CmsBannerItemMapper cmsBannerItemMapper;

    @Operation(summary = "分页查询轮播组(带组内items)")
    @GetMapping("/page")
    public ApiResult<PageResult<CmsBannerGroup>> page(CmsBannerGroupParam param) {
        return success(cmsBannerGroupService.pageRel(param));
    }

    @Operation(summary = "查询全部轮播组(带组内items)")
    @GetMapping()
    public ApiResult<List<CmsBannerGroup>> list(CmsBannerGroupParam param) {
        return success(cmsBannerGroupService.listRel(param));
    }

    @Operation(summary = "根据id查询轮播组(含组内items)")
    @GetMapping("/{groupId}")
    public ApiResult<CmsBannerGroup> get(@PathVariable("groupId") Integer groupId) {
        CmsBannerGroup group = cmsBannerGroupService.getByIdRel(groupId);
        if (group == null) {
            return fail("轮播组不存在", group);
        }
        return success(group);
    }

    @Operation(summary = "添加轮播组(可携带items一次性创建)")
    @PreAuthorize("hasAuthority('cms:cmsBannerGroup:save')")
    @PostMapping()
    public ApiResult<?> save(@RequestBody CmsBannerGroup group) {
        if (cmsBannerGroupService.saveGroup(group)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @Operation(summary = "修改轮播组(可携带items一次性全量替换)")
    @PreAuthorize("hasAuthority('cms:cmsBannerGroup:update')")
    @PutMapping()
    public ApiResult<?> update(@RequestBody CmsBannerGroup group) {
        if (group.getGroupId() == null) {
            return fail("轮播组ID不能为空");
        }
        if (cmsBannerGroupService.updateGroup(group)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @Operation(summary = "删除轮播组(连带删除组内items)")
    @PreAuthorize("hasAuthority('cms:cmsBannerGroup:remove')")
    @DeleteMapping("/{groupId}")
    public ApiResult<?> remove(@PathVariable("groupId") Integer groupId) {
        if (cmsBannerGroupService.removeGroup(groupId)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @Operation(summary = "修改轮播组状态(启用/停用)")
    @PreAuthorize("hasAuthority('cms:cmsBannerGroup:update')")
    @PutMapping("/status")
    public ApiResult<?> updateStatus(@RequestBody CmsBannerGroup group) {
        CmsBannerGroup entity = new CmsBannerGroup();
        entity.setGroupId(group.getGroupId());
        entity.setStatus(group.getStatus());
        if (cmsBannerGroupService.updateById(entity)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    // ---------------- 单项 CRUD（可选，保存组时已全量提交items，以下接口用于单独维护） ----------------

    @Operation(summary = "单独新增轮播项")
    @PreAuthorize("hasAuthority('cms:cmsBannerGroup:save')")
    @PostMapping("/{groupId}/item")
    public ApiResult<?> addItem(@PathVariable("groupId") Integer groupId,
                                @RequestBody CmsBannerItem item) {
        item.setItemId(null);
        item.setGroupId(groupId);
        if (item.getLinkType() == null) {
            item.setLinkType(0);
        }
        if (cmsBannerGroupService.getById(groupId) == null) {
            return fail("轮播组不存在");
        }
        if (bannerItemInsert(item)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @Operation(summary = "单独修改轮播项")
    @PreAuthorize("hasAuthority('cms:cmsBannerGroup:update')")
    @PutMapping("/item")
    public ApiResult<?> updateItem(@RequestBody CmsBannerItem item) {
        if (item.getItemId() == null) {
            return fail("轮播项ID不能为空");
        }
        if (bannerItemUpdate(item)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @Operation(summary = "单独删除轮播项")
    @PreAuthorize("hasAuthority('cms:cmsBannerGroup:remove')")
    @DeleteMapping("/item/{itemId}")
    public ApiResult<?> removeItem(@PathVariable("itemId") Integer itemId) {
        if (bannerItemDelete(itemId)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    // ---------------- 单项CRUD依赖的mapper ----------------

    private boolean bannerItemInsert(CmsBannerItem item) {
        return cmsBannerItemMapper.insert(item) > 0;
    }

    private boolean bannerItemUpdate(CmsBannerItem item) {
        return cmsBannerItemMapper.updateById(item) > 0;
    }

    private boolean bannerItemDelete(Integer itemId) {
        return cmsBannerItemMapper.deleteById(itemId) > 0;
    }
}
