package com.izouma.jiashanxia.web;

import com.izouma.jiashanxia.domain.Withdraw;
import com.izouma.jiashanxia.enums.PayMethod;
import com.izouma.jiashanxia.service.WithdrawService;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.WithdrawRepo;
import com.izouma.jiashanxia.utils.ObjUtils;
import com.izouma.jiashanxia.utils.SecurityUtils;
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.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/withdraw")
@AllArgsConstructor
public class WithdrawController extends BaseController {
    private WithdrawService withdrawService;
    private WithdrawRepo    withdrawRepo;

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


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

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/backAll")
    public Page<Withdraw> backAll(@RequestBody PageQuery pageQuery) {
        return withdrawService.backAll(pageQuery);
    }

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

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

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

    @PostMapping("/apply")
    @ApiOperation("提现申请")
    public Withdraw apply(@RequestParam BigDecimal amount, @RequestParam PayMethod payMethod,
                          @RequestParam String realName, @RequestParam String account) {
        return withdrawService.apply(SecurityUtils.getAuthenticatedUser().getId(),
                amount, payMethod, realName, account);
    }

    @PostMapping("/audit")
    @ApiOperation("提现审核")
    public void audit(Long id, Boolean pass) {
        withdrawService.audit(id, pass);
    }

}

