package com.izouma.wenlvju.web;

import com.izouma.wenlvju.domain.Record;
import com.izouma.wenlvju.domain.Regulatory;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.enums.RegulatoryStatus;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.RecordRepo;
import com.izouma.wenlvju.repo.RegulatoryRepo;
import com.izouma.wenlvju.service.RegulatoryService;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
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.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/regulatory")
@AllArgsConstructor
public class RegulatoryController extends BaseController {
    private RegulatoryService regulatoryService;
    private RegulatoryRepo    regulatoryRepo;
    private RecordRepo        recordRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Regulatory save(@RequestBody Regulatory record) {
        if (record.getId() != null) {
            Regulatory orig = regulatoryRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return regulatoryRepo.save(orig);
        }
        if (record.getRecordId() != null) {
            Record record1 = recordRepo.findById(record.getRecordId()).orElseThrow(new BusinessException("无记录"));
            record1.setRegulatoryStatus(RegulatoryStatus.SUBMITTED);
            recordRepo.save(record1);
        }
        record.setTime(LocalDate.now());
        return regulatoryRepo.save(record);
    }

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<Regulatory> all(@RequestBody PageQuery pageQuery) {
        pageQuery.setSort("createdAt,desc");
        return regulatoryService.all(pageQuery);
    }

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

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

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

    @GetMapping("/byRecord")
    @ApiOperation("按检查记录查询")
    public List<Regulatory> byRecord(@RequestParam Long recordId) {
        return regulatoryRepo.findAllByRecordIdOrderByCreatedAtDesc(recordId);
    }
}

