package shop.alien.store.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import shop.alien.entity.result.R;
import shop.alien.store.feign.DiningServiceFeign;
import shop.alien.store.strategy.payment.PaymentStrategyFactory;
import shop.alien.util.common.constant.PaymentEnum;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lyx
 * @version 1.0
 * @date 2025/11/20 17:34
 */
@Slf4j
@Api(tags = {"2.5-支付接口"})
@CrossOrigin
@RestController
@RequestMapping("/payment")
@RequiredArgsConstructor
public class PaymentController {

    private final PaymentStrategyFactory paymentStrategyFactory;
    private final DiningServiceFeign diningServiceFeign;

    private static String authHeader(HttpServletRequest request) {
        String h = request.getHeader("Authorization");
        if (h == null || h.isEmpty()) {
            h = request.getHeader("authorization");
        }
        return h;
    }

    @ApiOperation("创建预支付订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "price", value = "订单金额", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "subject", value = "订单标题", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "smid", value = "smid", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "payType", value = "支付类型(alipay:支付宝, wechatPay:微信支付, wechatPayPartner:微信服务商模式, wechatPayMininProgram:微信小程序点餐)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "storeId", value = "门店ID（wechatPayPartner 必填，用于读取 store_info.wechat_sub_mchid）", required = false, paramType = "query", dataType = "int")
    })
    @RequestMapping("/prePay")
    public R prePay(
            HttpServletRequest request,
            @RequestParam String price,
            @RequestParam String subject,
            @RequestParam String payType,
            @RequestParam(required = false) String smid,
            @RequestParam(required = false) String payer,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) Integer storeId,
            @RequestParam(required = false) Integer couponId,
            @RequestParam(required = false) Integer payerId,
            @RequestParam(required = false) String tablewareFee,
            @RequestParam(required = false) String discountAmount,
            @RequestParam(required = false) String payAmount) {
        log.info("PaymentController:prePay, price: {}, subject: {}, payType: {}, orderNo: {}, storeId: {}", price, subject, payType, orderNo, storeId);
        try {
//            if ("wechatPayMininProgram".equals(payType) && storeId != null && orderNo != null && payer != null) {
//                return diningServiceFeign.prePay(
//                        authHeader(request), price, subject, payType, payer, orderNo, storeId,
//                        couponId, payerId, tablewareFee, discountAmount, payAmount);
//            }
            // 微信服务商 APP：传入 orderNo 时与小程序策略一致，绑定/刷新 store_order 与微信商户单号
            if ("wechatPayPartner".equals(payType) && storeId != null && orderNo != null) {
                return paymentStrategyFactory.getStrategy(payType).createPrePayOrder(
                        price, subject, payer, orderNo, storeId, couponId, payerId,
                        tablewareFee, discountAmount, payAmount);
            }
            if ("aliPayPartner".equals(payType)) {
                return paymentStrategyFactory.getStrategy(payType).createPreAliPayOrder(orderNo, price, subject, smid, storeId);
            }
            return paymentStrategyFactory.getStrategy(payType).createPrePayOrder(price, subject, storeId);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 微信服务商 APP 支付回调（需在商户平台将 notify_url 配置为本地址；验签通过后返回 204）
     */
    @RequestMapping("/weChatPartnerNotify")
    public ResponseEntity<?> weChatPartnerNotify(@RequestBody String notifyData, HttpServletRequest request) throws Exception {
        log.info("[微信服务商APP回调] 收到请求, Content-Length={}, Wechatpay-Serial={}",
                request.getContentLength(), request.getHeader("Wechatpay-Serial"));
        try {
            R<?> result = paymentStrategyFactory.getStrategy(PaymentEnum.WECHAT_PAY_PARTNER.getType())
                    .handleNotify(notifyData, request);
            if (R.isSuccess(result)) {
                return ResponseEntity.noContent().build();
            }
            String message = result != null && result.getMsg() != null ? result.getMsg() : "失败";
            Map<String, String> failBody = new HashMap<>(2);
            failBody.put("code", "FAIL");
            failBody.put("message", message);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(failBody);
        } catch (Exception e) {
            log.error("[微信服务商APP回调] 处理异常", e);
            String msg = e.getMessage() != null ? e.getMessage() : "失败";
            Map<String, String> failBody = new HashMap<>(2);
            failBody.put("code", "FAIL");
            failBody.put("message", msg);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(failBody);
        }
    }

    /**
     * 预留：非微信 V3 回调（当前未使用）
     */
    @RequestMapping("/notify")
    public R notify(String notifyData) {
        return null;
    }

    /**
     * 查询订单状态
     * @param transactionId 交易订单号（微信支付订单号/商户订单号）
     * @param payType 支付类型
     * @return 订单状态信息
     */
    /**
     * wechatPayPartner 查单需传 storeId，与预下单一致，用于解析子商户号。
     */
    @RequestMapping("/searchOrderByOutTradeNoPath")
    public R searchOrderByOutTradeNoPath(
            @RequestParam String transactionId,
            @RequestParam String payType,
            @RequestParam(required = false) Integer storeId) {
        try {
//            if ("wechatPayMininProgram".equals(payType) && storeId != null) {
//                return diningServiceFeign.searchOrderByOutTradeNoPath(transactionId, payType, storeId);
//            }
            return paymentStrategyFactory.getStrategy(payType).searchOrderByOutTradeNoPath(transactionId, storeId);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 退款接口
     * @param params 退款参数（包含订单号、退款金额等）
     * @return 退款结果
     */
    @RequestMapping("/refunds")
    public R refunds(@RequestBody Map<String, String> params) {
        try {
            return R.data(paymentStrategyFactory.getStrategy(params.get("payType")).handleRefund(params));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }
}
