package com.izouma.jiashanxia.web;

import com.izouma.jiashanxia.domain.SetMeal;
import com.izouma.jiashanxia.service.SetMealService;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.SetMealRepo;
import com.izouma.jiashanxia.utils.ObjUtils;
import com.izouma.jiashanxia.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("/setMeal")
@AllArgsConstructor
public class SetMealController extends BaseController {
    private SetMealService setMealService;
    private SetMealRepo    setMealRepo;

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


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

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

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

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

