package com.izouma.nineth.web;
import com.izouma.nineth.domain.ActivityMaterial;
import com.izouma.nineth.service.ActivityMaterialService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.ActivityMaterialRepo;
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("/activityMaterial")
@AllArgsConstructor
public class ActivityMaterialController extends BaseController {
    private ActivityMaterialService activityMaterialService;
    private ActivityMaterialRepo activityMaterialRepo;

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


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

    @GetMapping("/get/{id}")
    public ActivityMaterial get(@PathVariable Long id) {
        return activityMaterialRepo.findById(id).orElseThrow(new BusinessException("活动材料无记录"));
    }

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

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

