package com.gxwebsoft.cms.controller;

import cn.hutool.core.util.ObjectUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.cms.service.CmsWebsiteSettingService;
import com.gxwebsoft.cms.entity.CmsWebsiteSetting;
import com.gxwebsoft.cms.param.CmsWebsiteSettingParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.cms.mapper.CmsWebsiteSettingMapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 网站设置控制器
 *
 * @author 科技小王子
 * @since 2025-02-19 01:35:44
 */
@Tag(name = "网站设置管理")
@RestController
@RequestMapping("/api/cms/cms-website-setting")
public class CmsWebsiteSettingController extends BaseController {
    @Resource
    private CmsWebsiteSettingService cmsWebsiteSettingService;

    @Resource
    private CmsWebsiteSettingMapper cmsWebsiteSettingMapper;

    @Operation(summary = "分页查询网站设置")
    @GetMapping("/page")
    public ApiResult<PageResult<CmsWebsiteSetting>> page(CmsWebsiteSettingParam param) {
        // 使用关联查询
        return success(cmsWebsiteSettingService.pageRel(param));
    }

    @Operation(summary = "查询全部网站设置")
    @GetMapping()
    public ApiResult<List<CmsWebsiteSetting>> list(CmsWebsiteSettingParam param) {
        // 使用关联查询
        return success(cmsWebsiteSettingService.listRel(param));
    }

    @Operation(summary = "根据id查询网站设置")
    @GetMapping("/{id}")
    public ApiResult<CmsWebsiteSetting> get(@PathVariable("id") Integer id) {
      // 自定义查询忽略逻辑删除：能捞到 deleted IS NULL 的孤儿记录（旧逻辑遗留），
      // 避免“查不到→新建”时撞 website_id 唯一索引，导致前端报“未获取到网站设置记录”。
      final CmsWebsiteSetting existing = cmsWebsiteSettingMapper.selectByWebsiteIdIgnoreLogic(id);
      if (ObjectUtil.isEmpty(existing)) {
        // 真正没有记录才新建，并显式 setDeleted(0)，避免被 @TableLogic 查询过滤。
        final CmsWebsiteSetting setting = new CmsWebsiteSetting();
        setting.setWebsiteId(id);
        setting.setDeleted(0);
        cmsWebsiteSettingService.save(setting);
        return success(setting);
      }
      // 查到的是孤儿/已删除记录：复活为正常态（deleted=0）后返回，不再重复插入。
      if (existing.getDeleted() == null || existing.getDeleted() != 0) {
        cmsWebsiteSettingMapper.reviveById(existing.getId());
        existing.setDeleted(0);
      }
      return success(existing);
    }

    @PreAuthorize("hasAuthority('cms:website:save')")
    @Operation(summary = "添加网站设置")
    @PostMapping()
    public ApiResult<?> save(@RequestBody CmsWebsiteSetting cmsWebsiteSetting) {
        if (cmsWebsiteSettingService.save(cmsWebsiteSetting)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('cms:website:update')")
    @Operation(summary = "修改网站设置")
    @PutMapping()
    public ApiResult<?> update(@RequestBody CmsWebsiteSetting cmsWebsiteSetting) {
        if (cmsWebsiteSettingService.updateById(cmsWebsiteSetting)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

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

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

    @PreAuthorize("hasAuthority('cms:website:update')")
    @Operation(summary = "批量修改网站设置")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<CmsWebsiteSetting> batchParam) {
        if (batchParam.update(cmsWebsiteSettingService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

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

}
