package com.izouma.jmrh.web.stat;

import com.izouma.jmrh.web.BaseController;
import com.izouma.jmrh.domain.stat.CityIndexStat;
import com.izouma.jmrh.service.stat.CityIndexStatService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.stat.CityIndexStatRepo;
import com.izouma.jmrh.utils.ObjUtils;
import com.izouma.jmrh.utils.excel.ExcelUtils;

import lombok.AllArgsConstructor;
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("/cityIndexStat")
@AllArgsConstructor
public class CityIndexStatController extends BaseController {
    private CityIndexStatService cityIndexStatService;
    private CityIndexStatRepo cityIndexStatRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public CityIndexStat save(@RequestBody CityIndexStat record) {
        if (record.getId() != null) {
            CityIndexStat orig = cityIndexStatRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return cityIndexStatRepo.save(orig);
        }
        return cityIndexStatRepo.save(record);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<CityIndexStat> all(PageQuery pageQuery) {
        return cityIndexStatRepo.findAll(toSpecification(pageQuery,CityIndexStat.class), toPageRequest(pageQuery));
    }

    @GetMapping("/get/{id}")
    public CityIndexStat get(@PathVariable Long id) {
        return cityIndexStatRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

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

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

