package com.gxwebsoft.shop.controller;

import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.utils.RequestUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.Payment;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.service.OrderRefundService;
import com.gxwebsoft.shop.entity.OrderRefund;
import com.gxwebsoft.shop.param.OrderRefundParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.service.OrderService;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.RSAConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.gxwebsoft.shop.consts.OrderPayType.PAY_TYPE_BALANCE;
import static com.gxwebsoft.shop.consts.OrderPayType.PAY_TYPE_WECHAT;

/**
 * 控制器
 *
 * @author 科技小王子
 * @since 2025-07-31 12:07:19
 */
@Api(tags = "管理")
@RestController
@RequestMapping("/api/shop/order-refund")
public class OrderRefundController extends BaseController {
    @Resource
    private OrderRefundService orderRefundService;
    @Resource
    private OrderService orderService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ConfigProperties config;
    @Resource
    private RequestUtil requestUtil;

    @ApiOperation("分页查询")
    @GetMapping("/page")
    public ApiResult<PageResult<OrderRefund>> page(OrderRefundParam param) {
        // 使用关联查询
        return success(orderRefundService.pageRel(param));
    }

    @ApiOperation("查询全部")
    @GetMapping()
    public ApiResult<List<OrderRefund>> list(OrderRefundParam param) {
        // 使用关联查询
        return success(orderRefundService.listRel(param));
    }

    @PreAuthorize("hasAuthority('shop:orderRefund:list')")
    @ApiOperation("根据id查询")
    @GetMapping("/{id}")
    public ApiResult<OrderRefund> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(orderRefundService.getByIdRel(id));
    }

    @ApiOperation("添加")
    @PostMapping()
    public ApiResult<?> save(@RequestBody OrderRefund orderRefund) {
        Order order = orderService.getById(orderRefund.getOrderId());
        orderRefund.setUserId(order.getUserId());
        if (orderRefund.getRefundMoney() == null) orderRefund.setRefundMoney(order.getPayPrice());
        order.setOrderStatus(4);
        orderService.updateById(order);
        orderRefund.setOrderRefundNo("R" + order.getOrderNo());
        if (orderRefundService.save(orderRefund)) {
            if (order.getPayType().equals(PAY_TYPE_WECHAT)) {
                orderRefund.setOrder(order);
                refund(orderRefund);
            } else if (order.getPayType().equals(PAY_TYPE_BALANCE)) {
                requestUtil.balanceRefund(order);
                order.setOrderStatus(6);
                order.setRefundTime(new Date());
                orderService.updateById(order);
            }
            return success("申请退款成功");
        }
        return fail("申请退款失败");
    }

    @ApiOperation("修改")
    @PutMapping()
    public ApiResult<?> update(@RequestBody OrderRefund orderRefund) {
        if (orderRefundService.updateById(orderRefund)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (orderRefundService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("批量添加")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<OrderRefund> list) {
        if (orderRefundService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @ApiOperation("批量修改")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<OrderRefund> batchParam) {
        if (batchParam.update(orderRefundService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("批量删除")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (orderRefundService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    public void refund(OrderRefund orderRefund) {
        String key = "mp-weixin:10559";
        final String string = redisUtil.get(key);
        final JSONObject mpWx = JSONObject.parseObject(string);
        String key2 = "Payment:".concat(PAY_TYPE_WECHAT.toString()).concat(":10559");
        final Payment payment = redisUtil.get(key2, Payment.class);
        final String uploadPath = config.getUploadPath();   // 服务器本地路径
        String privateKey = uploadPath.concat("/file").concat(payment.getApiclientKey());    // 秘钥证书
        String apiclientCert = uploadPath.concat("/file").concat(payment.getApiclientCert());

        Config config =
                new RSAConfig.Builder()
                        .merchantId(payment.getMchId())
                        .privateKeyFromPath(privateKey)
                        .merchantSerialNumber(payment.getMerchantSerialNumber())
                        .wechatPayCertificatesFromPath(apiclientCert)
                        .build();

        RefundService service = new RefundService.Builder().config(config).build();
        CreateRequest request = new CreateRequest();
        String refundNotifyUrl = "https://ngb-service-api.websoft.top/api/shop/order-refund/refund-notify";
        // 金额
        AmountReq amount = new AmountReq();
        amount.setTotal(orderRefund.getOrder().getPayPrice().multiply(BigDecimal.valueOf(100)).longValue());
        amount.setRefund(orderRefund.getRefundMoney().multiply(BigDecimal.valueOf(100)).longValue());
        amount.setCurrency("CNY");
        request.setNotifyUrl(refundNotifyUrl);
        request.setAmount(amount);
        request.setOutTradeNo(orderRefund.getOrder().getOrderNo());
        request.setOutRefundNo(orderRefund.getOrderRefundNo());
        service.create(request);
    }

    @PostMapping("/refund-notify")
    public ApiResult<?> refundNotify(@RequestBody String body, @RequestHeader Map<String, Object> header) throws ParseException {
        String key = "mp-weixin:10559";
        final String string = redisUtil.get(key);
        final JSONObject mpWx = JSONObject.parseObject(string);
        String key2 = "Payment:".concat(PAY_TYPE_WECHAT.toString()).concat(":10559");
        final Payment payment = redisUtil.get(key2, Payment.class);
        final String uploadPath = config.getUploadPath();   // 服务器本地路径
        String privateKey = uploadPath.concat("/file").concat(payment.getApiclientKey());    // 秘钥证书
        String apiclientCert = uploadPath.concat("/file").concat(payment.getApiclientCert());

        com.wechat.pay.java.core.notification.RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(header.get("wechatpay-serial").toString())
                .nonce(header.get("wechatpay-nonce").toString())
                .signature(header.get("wechatpay-signature").toString())
                .timestamp(header.get("wechatpay-timestamp").toString())
                .body(body)
                .build();
        NotificationConfig config = new RSAAutoCertificateConfig.Builder()
                .merchantId(payment.getMchId())
                .privateKeyFromPath(privateKey)
                .merchantSerialNumber(payment.getMerchantSerialNumber())
                .apiV3Key(payment.getApiKey())
                .build();
        // 初始化 NotificationParser
        NotificationParser parser = new NotificationParser(config);
        RefundNotification notification = parser.parse(requestParam, RefundNotification.class);
        String orderNo = notification.getOutTradeNo();
        if (notification.getRefundStatus().equals(Status.SUCCESS)) {
            Order order = orderService.getByOutTradeNo(orderNo);
            OrderRefund orderRefund = orderRefundService.getByOrderId(order.getOrderId());
            orderRefund.setRefundStatus(Status.SUCCESS);
            orderRefundService.updateById(orderRefund);

            order.setOrderStatus(6);
            order.setRefundTime(new Date());
            orderService.updateById(order);
        }
        return success();
    }

}
