package com.izouma.zhirongip.web.resource;

import com.izouma.zhirongip.web.BaseController;
import com.izouma.zhirongip.domain.resource.PolicyLaw;
import com.izouma.zhirongip.service.resource.PolicyLawService;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.resource.PolicyLawRepo;
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("/policyLaw")
@AllArgsConstructor
public class PolicyLawController extends BaseController {
    private final PolicyLawService policyLawService;
    private final PolicyLawRepo policyLawRepo;

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


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

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

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

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

