package com.izouma.wenlvju.web;

import com.izouma.wenlvju.domain.RateAudit;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.RateAuditRepo;
import com.izouma.wenlvju.service.RateAuditService;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.SecurityUtils;
import com.izouma.wenlvju.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("/rateAudit")
@AllArgsConstructor
public class RateAuditController extends BaseController {
    private RateAuditService rateAuditService;
    private RateAuditRepo rateAuditRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public RateAudit save(@RequestBody RateAudit record) {
        if (record.getId() != null) {
            RateAudit orig = rateAuditRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return rateAuditRepo.save(orig);
        }
//        record.setAuditTime(LocalDateTime.now());
        record.setUserId(SecurityUtils.getAuthenticatedUser().getId());
        return rateAuditRepo.save(record);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<RateAudit> all(@RequestBody PageQuery pageQuery) {
        pageQuery.setSort("createdAt,desc");
        return rateAuditService.all(pageQuery);
    }

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

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

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

