package com.izouma.nineth.web;

import com.izouma.nineth.domain.BonusGive;
import com.izouma.nineth.domain.BonusGiveItem;
import com.izouma.nineth.repo.BonusGiveItemRepo;
import com.izouma.nineth.service.BonusGiveService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.BonusGiveRepo;
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("/bonusGive")
@AllArgsConstructor
public class BonusGiveController extends BaseController {
    private BonusGiveService  bonusGiveService;
    private BonusGiveRepo     bonusGiveRepo;
    private BonusGiveItemRepo bonusGiveItemRepo;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public BonusGive save(@RequestBody BonusGive record) {
        return bonusGiveService.save(record);
    }


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

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

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

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

    @PostMapping("/preview")
    public List<BonusGiveItem> preview(@RequestBody BonusGive bonusGive) {
        return bonusGiveService.preview(bonusGive);
    }

    @GetMapping("/items")
    public List<BonusGiveItem> items(Long bonusGiveId) {
        return bonusGiveItemRepo.findByBonusGiveId(bonusGiveId);
    }
}

