package com.izouma.wenlvju.web.regulation;

import com.alibaba.fastjson.JSONObject;
import com.izouma.wenlvju.domain.regulation.RecordCheck;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.regulation.RecordCheckRepo;
import com.izouma.wenlvju.service.regulation.RecordCheckService;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.SecurityUtils;
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.web.bind.annotation.*;

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

@RestController
@RequestMapping("/recordCheck")
@AllArgsConstructor
public class RecordCheckController extends BaseController {
    private RecordCheckService recordCheckService;
    private RecordCheckRepo    recordCheckRepo;

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


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

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

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

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

    @PostMapping("/batchSave")
    public void batchSave(String checks) {
        List<RecordCheck> collaborateList = JSONObject.parseArray(checks, RecordCheck.class);
        recordCheckService.batchSave(collaborateList, SecurityUtils.getAuthenticatedUser().getId());
    }
}

