package com.izouma.zhirongip.web;
import com.izouma.zhirongip.domain.ServiceDetail;
import com.izouma.zhirongip.service.ServiceDetailService;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.ServiceDetailRepo;
import com.izouma.zhirongip.utils.ObjUtils;
import com.izouma.zhirongip.utils.excel.ExcelUtils;
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("/serviceDetail")
@AllArgsConstructor
public class ServiceDetailController extends BaseController {
    private final ServiceDetailService serviceDetailService;
    private final ServiceDetailRepo    serviceDetailRepo;

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


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

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

    @GetMapping("/getByNavigationId/{navigationId}")
    public  List<ServiceDetail> getByNavigationId(@PathVariable Long navigationId) {
        return serviceDetailRepo.findAllByNavigationId(navigationId);
    }

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

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

