package com.izouma.nineth.web;

import com.izouma.nineth.domain.ActivitySurpriseBox;
import com.izouma.nineth.domain.SurpriseBoxLog;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.SurpriseBoxLogRepo;
import com.izouma.nineth.utils.JpaUtils;
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.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/surpriseBoxLog")
@AllArgsConstructor
public class SurpriseBoxLogController  extends BaseController{
    private SurpriseBoxLogRepo surpriseBoxLogRepo;
    @PostMapping("/save")
    public SurpriseBoxLog save(@RequestBody SurpriseBoxLog record) {
        if (record.getId() != null) {
            SurpriseBoxLog orig = surpriseBoxLogRepo.findById(record.getId()).orElseThrow(new BusinessException("盒子记录无记录"));
            ObjUtils.merge(orig, record);
            return surpriseBoxLogRepo.save(orig);
        }
        return surpriseBoxLogRepo.save(record);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<SurpriseBoxLog> all(@RequestBody PageQuery pageQuery) {
        return surpriseBoxLogRepo.findAll(JpaUtils.toSpecification(pageQuery, SurpriseBoxLog.class), JpaUtils.toPageRequest(pageQuery));
    }

    @GetMapping("/get/{id}")
    public SurpriseBoxLog get(@PathVariable Long id) {
        return surpriseBoxLogRepo.findById(id).orElseThrow(new BusinessException("盒子记录无记录"));
    }

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

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