package com.izouma.wenlvju.web.regulation;

import com.izouma.wenlvju.domain.regulation.RecordExpertAudit;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.regulation.RecordExpertAuditRepo;
import com.izouma.wenlvju.service.regulation.RecordExpertAuditService;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.excel.ExcelUtils;
import com.izouma.wenlvju.web.BaseController;
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("/recordExpertAudit")
@AllArgsConstructor
public class RecordExpertAuditController extends BaseController {
    private RecordExpertAuditService recordExpertAuditService;
    private RecordExpertAuditRepo    recordExpertAuditRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<RecordExpertAudit> all(@RequestBody PageQuery pageQuery) {
        return recordExpertAuditService.all(pageQuery);
    }

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

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

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

    @PreAuthorize("hasAnyRole('ADMIN','DISTRICT','DISTRICT_STAFF','EXPERT')")
    @PostMapping("/batchSave")
    public void batchSave(@RequestBody List<RecordExpertAudit> recordExpertAudits) {
//        List<RecordExpertAudit> recordExpertAudits = JSONObject.parseArray(audits, RecordExpertAudit.class);
        recordExpertAuditService.batchSave(recordExpertAudits);
    }
}

