package com.izouma.wenlvju.web;

import com.alibaba.fastjson.JSONObject;
import com.izouma.wenlvju.domain.Collaborate;
import com.izouma.wenlvju.service.CollaborateService;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.CollaborateRepo;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.excel.ExcelUtils;
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("/collaborate")
@AllArgsConstructor
public class CollaborateController extends BaseController {
    private CollaborateService collaborateService;
    private CollaborateRepo    collaborateRepo;

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

    @PostMapping("/batchSave")
    public void batchSave(String collaborates) {
        List<Collaborate> collaborateList = JSONObject.parseArray(collaborates, Collaborate.class);
        collaborateService.batchSave(collaborateList);
    }

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

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

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

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

