package com.izouma.nineth.web;

import com.izouma.nineth.domain.PriceList;
import com.izouma.nineth.repo.CollectionRepo;
import com.izouma.nineth.service.PriceListService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.PriceListRepo;
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.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("/priceList")
@AllArgsConstructor
public class PriceListController extends BaseController {
    private PriceListService priceListService;
    private PriceListRepo    priceListRepo;
    private CollectionRepo   collectionRepo;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public PriceList save(@RequestBody PriceList record) {
        if (record.getId() != null) {
            PriceList orig = priceListRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            orig.setPrice(collectionRepo.lowestPrice(orig.getSearch()).stripTrailingZeros().toPlainString());
            return priceListRepo.save(orig);
        }
        record.setPrice(collectionRepo.lowestPrice(record.getSearch()).stripTrailingZeros().toPlainString());
        return priceListRepo.save(record);
    }


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

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/get/{id}")
    public PriceList get(@PathVariable Long id) {
        return priceListRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        priceListRepo.deleteById(id);
    }

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

