package com.cyksj.web.controller.manage.sys;

import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.model.entity.MirrorNotice;
import com.cyksj.service.mange.RefreshCacheService;
import com.cyksj.service.sys.MirrorNoticeService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 镜像系统公告管理
 * @author chan
 * @date 2024/6/21 15:35
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/manage/mirror/notice")
public class CmsMirrorNoticeController {

    private final BeanSearcher beanSearcher;

    private final HttpServletRequest request;

    private final MirrorNoticeService mirrorNoticeService;

    private final RefreshCacheService refreshCacheService;

    /**
     * 公告列表
     */
    @GetMapping
    public Result<SearchResult<MirrorNotice>> get(){
        SearchResult<MirrorNotice> search = beanSearcher.search(MirrorNotice.class, MapUtils.flatBuilder(request.getParameterMap()).build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 新增公告
     */
    @PostMapping
    public Result<String> add(@RequestBody MirrorNotice mirrorNotice){
        mirrorNoticeService.save(mirrorNotice);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 修改公告
     */
    @PutMapping
    public Result<MirrorNotice> update(@RequestBody MirrorNotice mirrorNotice){
        if(mirrorNotice.getId() == null){
            throw BusinessRuntimeException.getInstance("缺少必填参数");
        }
        MirrorNotice oldNotice = mirrorNoticeService.getById(mirrorNotice.getId());
        if (oldNotice == null) {
            throw BusinessRuntimeException.getInstance("公告不存在");
        }
        mirrorNoticeService.updateById(mirrorNotice);
        refreshCacheService.refreshUserMirrorShopAdvertiseCache(null);
        return GatewayResponse.SUCCESS.newBuilder().toResult(mirrorNoticeService.getById(mirrorNotice.getId()));
    }

    /**
     * 删除公告
     */
    @DeleteMapping("/{id}")
    public Result<String> del(@PathVariable Long id){
        MirrorNotice mirrorNotice = mirrorNoticeService.getById(id);
        if (mirrorNotice == null) {
            throw BusinessRuntimeException.getInstance("公告不存在");
        }
        mirrorNoticeService.removeById(id);
        refreshCacheService.refreshUserMirrorShopAdvertiseCache(null);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }
}
