package com.izouma.uwip.web;
import com.izouma.uwip.domain.Attachment;
import com.izouma.uwip.service.AttachmentService;
import com.izouma.uwip.dto.PageQuery;
import com.izouma.uwip.exception.BusinessException;
import com.izouma.uwip.repo.AttachmentRepo;
import com.izouma.uwip.utils.ObjUtils;
import com.izouma.uwip.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("/attachment")
@AllArgsConstructor
public class AttachmentController extends BaseController {
    private AttachmentService attachmentService;
    private AttachmentRepo attachmentRepo;

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


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

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

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

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

