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.util.List;

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

    @PreAuthorize("hasRole('ADMIN')")
    @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("无记录"));
    }
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        adapayMerchantRepo.softDelete(id);
    }

    @PostMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, @RequestBody 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 {
        //orderId 实际上是支付平台的交易流水ID
        Object result = adapayMerchantService.refund(id, orderId);
        return result;
    }
}

