package com.izouma.wenlvju.web.performance;

import com.izouma.wenlvju.web.BaseController;
import com.izouma.wenlvju.domain.performance.Participant;
import com.izouma.wenlvju.service.performance.ParticipantService;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.performance.ParticipantRepo;
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("/participant")
@AllArgsConstructor
public class ParticipantController extends BaseController {
    private ParticipantService participantService;
    private ParticipantRepo    participantRepo;

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


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

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

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

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

    @PostMapping("/batchSave")
    public void batchSave(@RequestBody List<Participant> participants) {
        participantService.batchSave(participants);
    }
}

