package com.izouma.dingdong.web;
import com.izouma.dingdong.domain.FeeRecord;
import com.izouma.dingdong.service.FeeRecordService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.FeeRecordRepo;
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("/feeRecord")
@AllArgsConstructor
public class FeeRecordController extends BaseController {
    private FeeRecordService feeRecordService;
    private FeeRecordRepo feeRecordRepo;

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


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

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

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

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

