package com.izouma.wenlvju.web.performance;

import com.izouma.wenlvju.utils.SecurityUtils;
import com.izouma.wenlvju.web.BaseController;
import com.izouma.wenlvju.domain.performance.ProgrammeScore;
import com.izouma.wenlvju.service.performance.ProgrammeScoreService;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.performance.ProgrammeScoreRepo;
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("/programmeScore")
@AllArgsConstructor
public class ProgrammeScoreController extends BaseController {
    private ProgrammeScoreService programmeScoreService;
    private ProgrammeScoreRepo    programmeScoreRepo;

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


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

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

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

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

    @ApiOperation("专家手机端打分")
    @PostMapping("/saveScore")
    public void saveScore(@RequestParam Long programmeId, Double score, String remark) {
        programmeScoreService.saveScore(programmeId, score, remark, SecurityUtils.getAuthenticatedUser().getId());
    }
}

