package com.izouma.nineth.web;

import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.izouma.nineth.domain.AdapayMerchant;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.AdapayMerchantRepo;
import com.izouma.nineth.service.AdapayMerchantService;
import com.izouma.nineth.utils.excel.ExcelUtils;
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.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/adapayMerchant")
@AllArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class AdapayMerchantController extends BaseController {
    private AdapayMerchantService adapayMerchantService;
    private AdapayMerchantRepo    adapayMerchantRepo;

    @PostMapping("/save")
    public AdapayMerchant save(@RequestBody AdapayMerchant record) {
        if (record.getId() != null) {
            return adapayMerchantService.update(record);
        }
        return adapayMerchantService.save(record);
    }

    @PostMapping("/all")
    public Page<AdapayMerchant> all(@RequestBody PageQuery pageQuery) {
        return adapayMerchantService.all(pageQuery);
    }

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

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

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

    @PostMapping("/select")
    public void select(@RequestParam Long id) throws Exception {
        adapayMerchantService.sendSelectEvent(id);
    }

    @PostMapping("/query")
    public Object query(@RequestParam Long id, @RequestParam String orderId) throws BaseAdaPayException {
        return adapayMerchantService.query(id, orderId);
    }

    @PostMapping("/refund")
    public Object refund(@RequestParam Long id, @RequestParam String orderId) throws BaseAdaPayException {
        return adapayMerchantService.refund(id, orderId);
    }

    @PostMapping("/querySettle")
    public Object querySettle(@RequestParam Long id, @RequestParam LocalDate start,
                              @RequestParam LocalDate end, @RequestParam Long userId) throws BaseAdaPayException {
        return adapayMerchantService.querySettle(id, start, end, userId);
    }
}

