package com.izouma.wenlvju.web;

import com.izouma.wenlvju.domain.RecordExpert;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.RecordExpertRepo;
import com.izouma.wenlvju.service.RecordExpertService;
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.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/recordExpert")
@AllArgsConstructor
public class RecordExpertController extends BaseController {
    private RecordExpertService recordExpertService;
    private RecordExpertRepo recordExpertRepo;

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


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

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

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

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

    @PostMapping("/bySpecialtyId")
    public List<RecordExpert> bySpecialtyId(Long recordSpecialtyId){
        return recordExpertRepo.findAllByRecordSpecialtyId(recordSpecialtyId);
    }
}

