package com.izouma.jmrh.web;

import com.izouma.jmrh.annotations.OperLog;
import com.izouma.jmrh.domain.Approval;
import com.izouma.jmrh.domain.ApprovalProcess;
import com.izouma.jmrh.service.ApprovalService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.ApprovalRepo;
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("/approval")
@AllArgsConstructor
public class ApprovalController extends BaseController {
    private ApprovalService approvalService;
    private ApprovalRepo    approvalRepo;

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

    @PostMapping("/create")
    @OperLog(value = "审批流程-创建", type = "创建")
    public ApprovalProcess create(@RequestBody Approval record) {
        return approvalService.create(record);
    }

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

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

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

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

