package com.izouma.wenlvju.web.performance;

import com.izouma.wenlvju.dto.ArrangeDTO;
import com.izouma.wenlvju.utils.SecurityUtils;
import com.izouma.wenlvju.web.BaseController;
import com.izouma.wenlvju.domain.performance.Arrange;
import com.izouma.wenlvju.service.performance.ArrangeService;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.performance.ArrangeRepo;
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("/arrange")
@AllArgsConstructor
public class ArrangeController extends BaseController {
    private ArrangeService arrangeService;
    private ArrangeRepo    arrangeRepo;

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


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

    @PostMapping("/all2")
    public Page<Arrange> all2(@RequestBody PageQuery pageQuery) {
        return arrangeService.all2(pageQuery);
    }

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

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

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

    @PostMapping("/group")
    public void group(@RequestBody ArrangeDTO record) {
        arrangeService.group(record);
    }

    @ApiOperation("发布")
    @PostMapping("/performanceId")
    public void publish(@RequestParam Long performanceId) {
        arrangeService.publish(performanceId);
    }

    @ApiOperation("专家段查看分组")
    @PostMapping("/byExpert")
    public Page<Arrange> byExpert(@RequestBody PageQuery pageQuery) {
        return arrangeService.byExpert(pageQuery, SecurityUtils.getAuthenticatedUser().getId());
    }

}

