package com.izouma.nineth.web;

import com.izouma.nineth.domain.BlindBoxItem;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.BlindBoxItemRepo;
import com.izouma.nineth.service.BlindBoxItemService;
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("/blindBoxItem")
@AllArgsConstructor
public class BlindBoxItemController extends BaseController {
    private BlindBoxItemService blindBoxItemService;
    private BlindBoxItemRepo blindBoxItemRepo;

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


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

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

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

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

