package com.izouma.nineth.web;

import com.izouma.nineth.domain.WithdrawApply;
import com.izouma.nineth.service.WithdrawApplyService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.WithdrawApplyRepo;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.math.BigDecimal;
import java.util.List;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/withdrawApply")
@AllArgsConstructor
@Slf4j
public class WithdrawApplyController extends BaseController {
    private WithdrawApplyService withdrawApplyService;
    private WithdrawApplyRepo    withdrawApplyRepo;

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

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/get/{id}")
    public WithdrawApply get(@PathVariable Long id) {
        return withdrawApplyRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

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

    @PostMapping("/apply")
    public WithdrawApply apply(@RequestParam BigDecimal amount) {
        return withdrawApplyService.apply(SecurityUtils.getAuthenticatedUser().getId(), amount);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/finish")
    public WithdrawApply finish(@RequestParam Long id, @RequestParam boolean approve, String reason) {
        return withdrawApplyService.finishWithdrawApply(id, approve, reason);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/approveAll")
    public void approveAll() throws ExecutionException, InterruptedException {
        withdrawApplyService.approveAllAsync();
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/applyAll")
    public void applyAll() throws ExecutionException, InterruptedException {
        withdrawApplyService.applyAll();
    }
}

