package com.izouma.zhirongip.web;
import com.izouma.zhirongip.domain.Partner;
import com.izouma.zhirongip.service.PartnerService;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.PartnerRepo;
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.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("/partner")
@AllArgsConstructor
public class PartnerController extends BaseController {
    private final PartnerService partnerService;
    private final PartnerRepo partnerRepo;

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


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

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

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

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

