package com.izouma.jmrh.web;
import com.izouma.jmrh.domain.LikeRecord;
import com.izouma.jmrh.service.LikeRecordService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.LikeRecordRepo;
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("/likeRecord")
@AllArgsConstructor
public class LikeRecordController extends BaseController {
    private LikeRecordService likeRecordService;
    private LikeRecordRepo likeRecordRepo;

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


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

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

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

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

