package com.izouma.wenlvju.web;

import com.izouma.wenlvju.domain.PerformanceApply;
import com.izouma.wenlvju.service.PerformanceApplyService;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.PerformanceApplyRepo;
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("/performanceApply")
@AllArgsConstructor
public class PerformanceApplyController extends BaseController {
    private PerformanceApplyService performanceApplyService;
    private PerformanceApplyRepo    performanceApplyRepo;

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


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

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

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

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

    @PostMapping("/audit")
    @ApiOperation("提现审核")
    public void audit(Long id, Boolean pass) {
        performanceApplyService.audit(id, pass);
    }

    @PostMapping("/autoArrangement")
    @ApiOperation("自动编排")
    public void autoArrangement(@RequestParam Long performanceId) {
        performanceApplyService.autoArrangement(performanceId);
    }

    @PostMapping("/autoAwards")
    @ApiOperation("自动评奖")
    public void autoAwards(@RequestParam Long performanceId) {
        performanceApplyService.autoAwards(performanceId);
    }
}

