package com.izouma.dingdong.web.merchant;

import com.izouma.dingdong.web.BaseController;
import com.izouma.dingdong.domain.merchant.Sales;
import com.izouma.dingdong.service.merchant.SalesService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.merchant.SalesRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.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("/sales")
@AllArgsConstructor
public class SalesController extends BaseController {
    private SalesService salesService;
    private SalesRepo salesRepo;

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


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

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

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

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

