package com.izouma.jiashanxia.web;

import com.izouma.jiashanxia.domain.SysConfig;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.SysConfigRepo;
import com.izouma.jiashanxia.service.SysConfigService;
import com.izouma.jiashanxia.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/sysConfig")
@AllArgsConstructor
public class SysConfigController extends BaseController {
    private SysConfigService sysConfigService;
    private SysConfigRepo    sysConfigRepo;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
//    @CacheEvict(value = {"SysConfigServiceGetBigDecimal", "SysConfigServiceGetTime", "SysConfigServiceGetBoolean", "SysConfigServiceGetInt"}, allEntries = true)
    public SysConfig save(@RequestBody SysConfig record) {
        return sysConfigRepo.save(record);
    }


    @PostMapping("/all")
    public Page<SysConfig> all(@RequestBody PageQuery pageQuery) {
        return sysConfigService.all(pageQuery);
    }

    @GetMapping("/get/{id}")
    public SysConfig get(@PathVariable String id) {
        return sysConfigRepo.findByName(id).orElseThrow(new BusinessException("无记录"));
    }

    @PostMapping("/del/{id}")
    public void del(@PathVariable String id) {
        sysConfigRepo.deleteById(id);
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<SysConfig> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }
}

