package com.izouma.nineth.web;
import com.izouma.nineth.domain.AssetPost;
import com.izouma.nineth.service.AssetPostService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.AssetPostRepo;
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("/assetPost")
@AllArgsConstructor
public class AssetPostController extends BaseController {
    private AssetPostService assetPostService;
    private AssetPostRepo assetPostRepo;

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


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

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

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

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

