package com.izouma.jmrh.web;

import com.izouma.jmrh.domain.DockingRecord;
import com.izouma.jmrh.domain.Message;
import com.izouma.jmrh.enums.DockingStatus;
import com.izouma.jmrh.repo.MessageRepo;
import com.izouma.jmrh.service.DockingRecordService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.DockingRecordRepo;
import com.izouma.jmrh.utils.ObjUtils;
import com.izouma.jmrh.utils.SecurityUtils;
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;
import java.util.Objects;

@RestController
@RequestMapping("/dockingRecord")
@AllArgsConstructor
public class DockingRecordController extends BaseController {
    private DockingRecordService dockingRecordService;
    private DockingRecordRepo    dockingRecordRepo;
    private MessageRepo          messageRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public DockingRecord save(@RequestBody DockingRecord record) {
        Objects.requireNonNull(record.getId(), "无记录");
        DockingRecord orig = dockingRecordRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
        ObjUtils.merge(orig, record);
        return dockingRecordRepo.save(orig);
    }

    public DockingRecord updateStatus(@RequestParam Long id, @RequestParam DockingStatus status) {
        return dockingRecordService.updateStatue(id, status);
    }

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

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

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

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

