package com.izouma.wenlvju.web.regulation;

import com.izouma.wenlvju.domain.regulation.Complain;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.regulation.ComplainRepo;
import com.izouma.wenlvju.service.regulation.ComplainService;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.SecurityUtils;
import com.izouma.wenlvju.utils.excel.ExcelUtils;
import com.izouma.wenlvju.web.BaseController;
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("/complain")
@AllArgsConstructor
public class ComplainController extends BaseController {
    private ComplainService complainService;
    private ComplainRepo complainRepo;

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


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

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

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

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

