package com.izouma.wenlvju.web.performance;

import com.alibaba.fastjson.JSONObject;
import com.izouma.wenlvju.domain.performance.PerformanceSchedule;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.performance.PerformanceScheduleRepo;
import com.izouma.wenlvju.service.performance.PerformanceScheduleService;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.excel.ExcelUtils;
import com.izouma.wenlvju.web.BaseController;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/performanceSchedule")
@AllArgsConstructor
public class PerformanceScheduleController extends BaseController {
    private PerformanceScheduleService performanceScheduleService;
    private PerformanceScheduleRepo performanceScheduleRepo;

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


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

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

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

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

    @PostMapping("/batchSave")
    public void batchSave(String schedules) {
        List<PerformanceSchedule> scheduleList = JSONObject.parseArray(schedules, PerformanceSchedule.class);
        performanceScheduleService.batchSave(scheduleList);
    }
}

