package com.izouma.nineth.web;
import com.izouma.nineth.domain.Activity;
import com.izouma.nineth.service.ActivityService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.ActivityRepo;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
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("/activity")
@AllArgsConstructor
public class ActivityController extends BaseController {
    private ActivityService activityService;
    private ActivityRepo activityRepo;

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


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

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

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

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

