package com.izouma.nineth.web;

import com.izouma.nineth.domain.UserCoupon;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.UserCouponRepo;
import com.izouma.nineth.service.UserCouponService;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.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("/userCoupon")
@AllArgsConstructor
public class UserCouponController extends BaseController {
    private UserCouponService userCouponService;
    private UserCouponRepo    userCouponRepo;

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


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

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

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

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

