package com.izouma.jmrh.web;
import com.izouma.jmrh.domain.AuditHistory;
import com.izouma.jmrh.service.AuditHistoryService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.AuditHistoryRepo;
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.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/auditHistory")
@AllArgsConstructor
public class AuditHistoryController extends BaseController {
    private AuditHistoryService auditHistoryService;
    private AuditHistoryRepo auditHistoryRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public AuditHistory save(@RequestBody AuditHistory record) {
        if (record.getId() != null) {
            AuditHistory orig = auditHistoryRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return auditHistoryRepo.save(orig);
        }
        record.setUser(SecurityUtils.getAuthenticatedUser());
        AuditHistory auditHistory = auditHistoryService.updateState(record);
        return auditHistoryRepo.save(auditHistory);
    }


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

    @GetMapping("/myAll")
    public Page<AuditHistory> myAll(PageQuery pageQuery) {
        pageQuery.getQuery().put("myUser",SecurityUtils.getAuthenticatedUser());
        return auditHistoryRepo.findAll(toSpecification(pageQuery,AuditHistory.class), toPageRequest(pageQuery));
    }

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

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

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

