package com.izouma.jiashanxia.web;

import com.izouma.jiashanxia.domain.SetGoods;
import com.izouma.jiashanxia.service.SetGoodsService;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.SetGoodsRepo;
import com.izouma.jiashanxia.utils.ObjUtils;
import com.izouma.jiashanxia.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
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("/setGoods")
@AllArgsConstructor
public class SetGoodsController extends BaseController {
    private SetGoodsService setGoodsService;
    private SetGoodsRepo    setGoodsRepo;

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


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

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

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

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

    @PostMapping("/getSetGoods")
    @ApiOperation("获取套餐内商品信息")
    public List<SetGoods> getSetGoods(@RequestParam Long setId) {
        return setGoodsRepo.findAllBySetMealId(setId);
    }
}

