package com.izouma.awesomeAdmin.web;

import com.izouma.awesomeAdmin.domain.SysConfig;
import com.izouma.awesomeAdmin.dto.PageQuery;
import com.izouma.awesomeAdmin.exception.BusinessException;
import com.izouma.awesomeAdmin.repo.SysConfigRepo;
import com.izouma.awesomeAdmin.service.SysConfigService;
import com.izouma.awesomeAdmin.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);
    }
}

