package com.izouma.jmrh.web;
import com.izouma.jmrh.domain.LoginLog;
import com.izouma.jmrh.service.LoginLogService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.LoginLogRepo;
import com.izouma.jmrh.utils.ObjUtils;
import com.izouma.jmrh.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("/loginLog")
@AllArgsConstructor
public class LoginLogController extends BaseController {
    private LoginLogService loginLogService;
    private LoginLogRepo loginLogRepo;

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


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

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

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

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

