package com.izouma.nineth.web;

import com.izouma.nineth.domain.Asset;
import com.izouma.nineth.service.AssetService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.AssetRepo;
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("/asset")
@AllArgsConstructor
public class AssetController extends BaseController {
    private AssetService assetService;
    private AssetRepo    assetRepo;

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


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

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

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

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

    @PostMapping("/publicShow")
    public void publicShow(@RequestParam Long id) {
        assetService.publicShow(id);
    }

    @PostMapping("/cancelPublic")
    public void cancelPublic(@RequestParam Long id) {
        assetService.cancelPublic(id);
    }
}

