package com.izouma.jmrh.web;

import com.izouma.jmrh.annotations.OperLog;
import com.izouma.jmrh.domain.ApprovalProcess;
import com.izouma.jmrh.service.ApprovalProcessService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.ApprovalProcessRepo;
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.data.domain.Pageable;
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("/approvalProcess")
@AllArgsConstructor
public class ApprovalProcessController extends BaseController {
    private ApprovalProcessService approvalProcessService;
    private ApprovalProcessRepo    approvalProcessRepo;

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


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

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

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

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

    @GetMapping("/my")
    public Page<ApprovalProcess> my(Pageable pageable, Integer status) {
        return approvalProcessService.my(SecurityUtils.getAuthenticatedUser().getId(), status, pageable);
    }

    @GetMapping("/startProcess")
    public void startProcess(Long id) {
        approvalProcessService.startProcess(id);
    }

    @PostMapping("/next")
    @OperLog(value = "审批流程-审批", type = "审批")
    public void next(@RequestParam Long id, @RequestParam boolean pass, @RequestParam String remark, @RequestParam(defaultValue = "") List<Long> nextApprovers) {
        approvalProcessService.next(id, pass, remark, nextApprovers);
    }
}

