package com.izouma.dingdong.web;
import com.izouma.dingdong.domain.OrderGoodsSpec;
import com.izouma.dingdong.service.OrderGoodsSpecService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.OrderGoodsSpecRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.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("/orderGoodsSpec")
@AllArgsConstructor
public class OrderGoodsSpecController extends BaseController {
    private OrderGoodsSpecService orderGoodsSpecService;
    private OrderGoodsSpecRepo orderGoodsSpecRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<OrderGoodsSpec> all(PageQuery pageQuery) {
        return orderGoodsSpecRepo.findAll(toSpecification(pageQuery,OrderGoodsSpec.class), toPageRequest(pageQuery));
    }

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

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

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

    @GetMapping("/byOrder")
    @ApiOperation("按订单号查出规格")
    public List<OrderGoodsSpec> byOrder(Long orderId){
        return orderGoodsSpecRepo.findAllByOrderInfoId(orderId);
    }
}

