package com.izouma.jiashanxia.web;

import com.izouma.jiashanxia.domain.OrderRefund;
import com.izouma.jiashanxia.service.OrderRefundService;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.OrderRefundRepo;
import com.izouma.jiashanxia.utils.ObjUtils;
import com.izouma.jiashanxia.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
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("/orderRefund")
@AllArgsConstructor
public class OrderRefundController extends BaseController {
    private OrderRefundService orderRefundService;
    private OrderRefundRepo    orderRefundRepo;

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


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

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

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

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

    @PostMapping("/apply")
    @ApiOperation("申请退款")
    public OrderRefund apply(@RequestParam Long orderId) {
        return orderRefundService.apply(orderId);
    }

    @PostMapping("/audit")
    @ApiOperation("审核退款")
    public void audit(@RequestParam Long id, @RequestParam Boolean pass) {
        orderRefundService.audit(id, pass);
    }

    @PostMapping("/cancel")
    @ApiOperation("取消退款")
    public void cancel(@RequestParam Long orderId) {
        orderRefundService.cancel(orderId);
    }
}

