package com.izouma.jmrh.web.stat;

import com.izouma.jmrh.web.BaseController;
import com.izouma.jmrh.domain.stat.CityData;
import com.izouma.jmrh.service.stat.CityDataService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.stat.CityDataRepo;
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("/cityData")
@AllArgsConstructor
public class CityDataController extends BaseController {
    private CityDataService cityDataService;
    private CityDataRepo cityDataRepo;

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


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

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

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

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

