package com.izouma.dingdong.web.backstage;

import com.izouma.dingdong.web.BaseController;
import com.izouma.dingdong.domain.backstage.Priority;
import com.izouma.dingdong.service.backstage.PriorityService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.backstage.PriorityRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.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("/priority")
@AllArgsConstructor
public class PriorityController extends BaseController {
    private PriorityService priorityService;
    private PriorityRepo priorityRepo;

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


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

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

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

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

