package com.izouma.nineth.web;

import com.izouma.nineth.domain.SysConfig;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.SysConfigRepo;
import com.izouma.nineth.service.SysConfigService;
import com.izouma.nineth.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.math.BigDecimal;
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",
            "SysConfigServiceGetString"}, 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("参数无记录"));
    }

    @GetMapping("/getDecimal/{id}")
    public BigDecimal getDecimal(@PathVariable String id) {
        return sysConfigService.getBigDecimal(id);
    }

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

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

