package com.izouma.wenlvju.web.performance;

import com.izouma.wenlvju.web.BaseController;
import com.izouma.wenlvju.domain.performance.ArrangeJudge;
import com.izouma.wenlvju.service.performance.ArrangeJudgeService;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.performance.ArrangeJudgeRepo;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.excel.ExcelUtils;

import io.swagger.annotations.ApiOperation;
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("/arrangeJudge")
@AllArgsConstructor
public class ArrangeJudgeController extends BaseController {
    private ArrangeJudgeService arrangeJudgeService;
    private ArrangeJudgeRepo    arrangeJudgeRepo;

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


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

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

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

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

    @ApiOperation("分配评委")
    @PostMapping("/assignJudge")
    public void assignJudge(String experts, String arranges) {
        arrangeJudgeService.assignJudge(experts, arranges);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("取消分配")
    @PostMapping("/cancelAssign")
    public void cancelAssign(String arranges) {
        arrangeJudgeService.cancelAssign(arranges);
    }
}

