package com.izouma.dingdong.web.rider;

import com.izouma.dingdong.web.BaseController;
import com.izouma.dingdong.domain.rider.RiderSign;
import com.izouma.dingdong.service.rider.RiderSignService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.rider.RiderSignRepo;
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("/riderSign")
@AllArgsConstructor
public class RiderSignController extends BaseController {
    private RiderSignService riderSignService;
    private RiderSignRepo riderSignRepo;

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


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

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

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

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

