package com.izouma.jmrh.web.stat;

import com.izouma.jmrh.web.BaseController;
import com.izouma.jmrh.domain.stat.TechTradeStat;
import com.izouma.jmrh.service.stat.TechTradeStatService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.stat.TechTradeStatRepo;
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("/techTradeStat")
@AllArgsConstructor
public class TechTradeStatController extends BaseController {
    private TechTradeStatService techTradeStatService;
    private TechTradeStatRepo techTradeStatRepo;

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


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

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

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

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

