package com.izouma.uwip.web;
import com.izouma.uwip.domain.Patent;
import com.izouma.uwip.service.PatentService;
import com.izouma.uwip.dto.PageQuery;
import com.izouma.uwip.exception.BusinessException;
import com.izouma.uwip.repo.PatentRepo;
import com.izouma.uwip.utils.ObjUtils;
import com.izouma.uwip.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("/patent")
@AllArgsConstructor
public class PatentController extends BaseController {
    private final PatentService patentService;
    private final PatentRepo patentRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<Patent> all(@RequestBody PageQuery pageQuery) {
        return patentService.all(pageQuery);
    }

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

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

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

