package com.izouma.nineth.web;

import com.izouma.nineth.domain.OperationLog;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.OperationLogRepo;
import com.izouma.nineth.service.OperationLogService;
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.web.bind.annotation.*;

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

import static com.izouma.nineth.utils.JpaUtils.toPageRequest;
import static com.izouma.nineth.utils.JpaUtils.toSpecification;

@RestController
@RequestMapping("/operationLog")
@AllArgsConstructor
public class OperationLogController extends BaseController {
    private OperationLogService operationLogService;
    private OperationLogRepo operationLogRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<OperationLog> all(@RequestBody PageQuery pageQuery) {
        return operationLogRepo.findAll(toSpecification(pageQuery,OperationLog.class), toPageRequest(pageQuery));
    }

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

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

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

