package com.izouma.wenlvju.web;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.wenlvju.domain.PerformanceScore;
import com.izouma.wenlvju.domain.User;
import com.izouma.wenlvju.service.PerformanceScoreService;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.PerformanceScoreRepo;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.SecurityUtils;
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("/performanceScore")
@AllArgsConstructor
public class PerformanceScoreController extends BaseController {
    private final PerformanceScoreService performanceScoreService;
    private final PerformanceScoreRepo    performanceScoreRepo;

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


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

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

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

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

    @ApiOperation("打分细则")
    @PostMapping("/breakdown")
    public List<PerformanceScore> breakdown(@RequestParam Long performanceApplyId) {

        return performanceScoreRepo.findAllByPerformanceApplyId(performanceApplyId);
    }

    @ApiOperation("评分此节目打分")
    @PostMapping("/myScore")
    public PerformanceScore myScore(@RequestParam Long performanceApplyId) {
        User user = SecurityUtils.getAuthenticatedUser();
        if (ObjectUtil.isNull(user)) {
            return null;
        }
        return performanceScoreRepo.findByPerformanceApplyIdAndUserId(performanceApplyId, user.getId());
    }
}

