package com.izouma.dingdong.web.rider;

import com.izouma.dingdong.web.BaseController;
import com.izouma.dingdong.domain.rider.DeliveryFee;
import com.izouma.dingdong.service.rider.DeliveryFeeService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.rider.DeliveryFeeRepo;
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.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/deliveryFee")
@AllArgsConstructor
public class DeliveryFeeController extends BaseController {
    private DeliveryFeeService deliveryFeeService;
    private DeliveryFeeRepo deliveryFeeRepo;

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


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

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

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

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

