package com.izouma.wenlvju.web;
import com.izouma.wenlvju.domain.RecordSpecialty;
import com.izouma.wenlvju.service.RecordSpecialtyService;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.RecordSpecialtyRepo;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.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("/recordSpecialty")
@AllArgsConstructor
public class RecordSpecialtyController extends BaseController {
    private RecordSpecialtyService recordSpecialtyService;
    private RecordSpecialtyRepo recordSpecialtyRepo;

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


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

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

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

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

