package com.izouma.wenlvju.web.performance;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.wenlvju.domain.performance.Performance;
import com.izouma.wenlvju.domain.performance.PerformanceSchedule;
import com.izouma.wenlvju.domain.performance.Programme;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.performance.PerformanceRepo;
import com.izouma.wenlvju.repo.performance.PerformanceScheduleRepo;
import com.izouma.wenlvju.repo.performance.ProgrammeRepo;
import com.izouma.wenlvju.service.performance.PerformanceService;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.excel.ExcelUtils;
import com.izouma.wenlvju.web.BaseController;
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.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/performance")
@AllArgsConstructor
public class PerformanceController extends BaseController {
    private final PerformanceService      performanceService;
    private final PerformanceRepo         performanceRepo;
    private final ProgrammeRepo           programmeRepo;
    private final PerformanceScheduleRepo performanceScheduleRepo;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Performance save(@RequestBody Performance record) {
        if (record.getId() != null) {
            Performance orig = performanceRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return performanceRepo.save(orig);
        }
        Performance byYear = performanceRepo.findByYear(record.getYear());
        if (ObjectUtil.isNotNull(byYear)) {
            throw new BusinessException("每年度只能添加一次展演活动！");
        }
        return performanceRepo.save(record);
    }


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

    @PostMapping("/backAll")
    public Page<Performance> backAll(@RequestBody PageQuery pageQuery) {
        Map<Long, Long> programme = programmeRepo.findAll()
                .stream()
                .collect(Collectors.groupingBy(Programme::getPerformanceId, Collectors.counting()));
        return performanceService.all(pageQuery)
                .map(performance -> {
                    if (programme.containsKey(performance.getId())) {
                        performance.setProgrammeNum(programme.get(performance.getId()));
                    }
                    return performance;
                });
    }

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

    @GetMapping("/backGet/{id}")
    public Performance backGet(@PathVariable Long id) {
        Performance performance = performanceRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        performance.setProgrammeNum(programmeRepo.countAllByPerformanceId(id));
        return performance;
    }


    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        performanceRepo.softDelete(id);
        performanceScheduleRepo.softDeleteByPid(id);
    }

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

    @ApiOperation("发布")
    @PostMapping("/publish")
    public void publish(Long id, boolean publish) {
        Performance performance = performanceRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        performance.setPublish(publish);
        performanceRepo.save(performance);
    }

    @ApiOperation("获取上一年度")
    @PostMapping("/lastYear")
    public Performance lastYear() {
//        return performanceRepo.findLastYear();
        return performanceRepo.findByYear(String.valueOf(LocalDate.now().getYear() - 1));
    }
}

