package com.izouma.dingdong.web;
import com.izouma.dingdong.domain.FastAppraisal;
import com.izouma.dingdong.service.FastAppraisalService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.FastAppraisalRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.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("/fastAppraisal")
@AllArgsConstructor
public class FastAppraisalController extends BaseController {
    private FastAppraisalService fastAppraisalService;
    private FastAppraisalRepo fastAppraisalRepo;

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


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

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

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

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

