package com.fs.app.controller.live;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fs.app.annotation.Login;
import com.fs.app.controller.AppBaseController;
import com.fs.common.annotation.Log;
import com.fs.common.annotation.RateLimiter;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.enums.BusinessType;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.IpUtil;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.ip.IpUtils;
import com.fs.core.config.WxMaConfiguration;
import com.fs.core.utils.OrderCodeUtils;
import com.fs.erp.service.IErpOrderService;
import com.fs.his.dto.ExpressInfoDTO;
import com.fs.his.enums.ShipperCodeEnum;
import com.fs.his.service.IFsExpressService;
import com.fs.his.utils.ConfigUtil;
import com.fs.hisStore.domain.*;
import com.fs.hisStore.dto.FsStoreOrderComputeDTO;
import com.fs.course.domain.FsCoursePlaySourceConfig;
import com.fs.course.mapper.FsCoursePlaySourceConfigMapper;
import com.fs.his.domain.FsPayConfig;
import com.fs.his.domain.MerchantAppConfig;
import com.fs.his.mapper.MerchantAppConfigMapper;
import com.fs.hisStore.domain.FsUserScrm;
import com.fs.hisStore.enums.AfterSalesStatusEnum;
import com.fs.hisStore.enums.OrderInfoEnum;
import com.fs.hisStore.mapper.FsStorePaymentScrmMapper;
import com.fs.hisStore.service.IFsStoreAfterSalesScrmService;
import com.fs.hisStore.param.*;
import com.fs.hisStore.service.IFsStoreOrderScrmService;
import com.fs.hisStore.service.IFsUserScrmService;
import com.fs.huifuPay.domain.HuiFuCreateOrder;
import com.fs.huifuPay.domain.HuiFuQueryOrderResult;
import com.fs.huifuPay.domain.HuifuCreateOrderResult;
import com.fs.huifuPay.sdk.opps.core.request.V2TradePaymentScanpayQueryRequest;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.live.domain.LiveAfterSales;
import com.fs.live.domain.LiveOrder;
import com.fs.live.domain.LiveOrderPayment;
import com.fs.live.domain.LiveUserBehaviorTrack;
import com.fs.live.dto.LiveOrderComputeDTO;
import com.fs.live.enums.LiveAfterSalesStatusEnum;
import com.fs.live.enums.LiveOrderCancleReason;
import com.fs.live.mapper.LiveOrderPaymentMapper;
import com.fs.live.param.FsMyLiveOrderQueryParam;
import com.fs.live.param.LiveOrderComputedParam;
import com.fs.live.param.LiveOrderConfirmParam;
import com.fs.live.param.LiveOrderPayParam;
import com.fs.live.service.ILiveAfterSalesService;
import com.fs.live.service.ILiveOrderItemService;
import com.fs.live.service.ILiveOrderService;
import com.fs.live.service.ILiveUserBehaviorTrackService;
import com.fs.live.util.LiveBehaviorTrackUtil;
import com.fs.live.vo.FsMyLiveOrderListQueryVO;
import com.fs.live.vo.LiveOrderItemListUVO;
import com.fs.live.vo.LiveOrderListVo;
import com.fs.pay.pay.dto.OrderQueryDTO;
import com.fs.pay.service.IPayService;
import com.fs.store.config.StoreConfig;
import com.fs.system.service.ISysConfigService;
import com.fs.wx.miniapp.config.WxMaProperties;
import com.fs.ybPay.domain.OrderResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.fs.hisStore.constants.UserAppsLockConstant.LOCK_KEY_PAY;

/**
 * 订单Controller
 *
 * @author fs
 * @date 2025-07-08
 */
@Slf4j
@RestController
@RequestMapping("/app/live/liveOrder")
public class LiveOrderController extends AppBaseController
{
    Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private ILiveOrderService orderService;

    @Autowired
    private ILiveOrderItemService liveOrderItemService;

    @Autowired
    private WxMaProperties properties;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private LiveOrderPaymentMapper liveOrderPaymentMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IFsUserScrmService userService;

    @Autowired
    private ILiveAfterSalesService liveAfterSalesService;
    @Autowired
    IPayService ybPayService;
    @Autowired
    private HuiFuService huiFuService;
    @Autowired
    private IFsStoreOrderScrmService fsStoreOrderScrmService;
    @Autowired
    private IFsStoreAfterSalesScrmService fsStoreAfterSalesScrmService;
    @Autowired
    private FsStorePaymentScrmMapper fsStorePaymentScrmMapper;



    @Autowired
    private FsCoursePlaySourceConfigMapper fsCoursePlaySourceConfigMapper;
    @Autowired
    private MerchantAppConfigMapper merchantAppConfigMapper;
    @Autowired
    private ILiveUserBehaviorTrackService behaviorTrackService;




    /**
     * 查询订单列表
     */
    @Login
    @GetMapping("/list")
    public R list(LiveOrder liveOrder)
    {
        log.info("查询订单列表 参数: {}", JSON.toJSONString(liveOrder));

        PageHelper.startPage(Integer.parseInt(ServletUtils.getParameter("pageNum")) ,Integer.parseInt(ServletUtils.getParameter("pageSize")) );
        try {
            liveOrder.setUserId(getUserId());
            List<LiveOrderListVo> list = orderService.selectLiveOrderListVo(liveOrder);
            PageInfo<LiveOrderListVo> result = new PageInfo<>(list);
            return R.ok().put("data", result);
        } catch (Exception e) {
            log.error("查询失败！",e);
            return R.error("操作异常");
        }

    }

    /**
     *正在购买的用户
     * */
    @GetMapping(value = "/liveOrderUser/{liveId}")
    public R liveOrderUser(@PathVariable  String liveId)
    {
        return orderService.liveOrderUser(liveId);
    }


    @Login
    @ApiOperation("获取我的订单列表")
    @GetMapping("/getMyStoreOrderList")
    public R getMyStoreOrderList(FsMyLiveOrderQueryParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setUserId(Long.parseLong(getUserId()));
        List<FsMyLiveOrderListQueryVO> list=orderService.selectFsMyLiveOrderListVO(param);
        PageInfo<FsMyLiveOrderListQueryVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("获取销售公司订单列表")
    @GetMapping("/getCompanyStoreOrderList")
    public R getCompanyStoreOrderList(FsMyLiveOrderQueryParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsMyLiveOrderListQueryVO> list=orderService.selectFsCompanyLiveOrderListVO(param);
        PageInfo<FsMyLiveOrderListQueryVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("获取我的订单详情")
    @GetMapping("/getMyStoreOrderById")
    public R getMyStoreOrderById(@RequestParam("orderId") Long orderId, HttpServletRequest request){
        LiveOrder order=orderService.selectLiveOrderByOrderId(String.valueOf(orderId));
        order.setUserPhone(ParseUtils.parsePhone(order.getUserPhone()));
        order.setUserAddress(ParseUtils.parseIdCard(order.getUserAddress()));
        List<LiveOrderItemListUVO> list = liveOrderItemService.selectLiveOrderItemListUVOByOrderId(orderId);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(order.getCreateTime());
        String json=configService.selectConfigByKey("his.store");
        StoreConfig config= JSONUtil.toBean(json,StoreConfig.class);
        calendar.add(Calendar.MINUTE,config.getUnPayTime());
        SimpleDateFormat format = new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String payLimitTime = format.format(calendar.getTime() );
        //处理是否可以申请售后
        Integer isAfterSales=0;
        if(order.getStatus().equals(OrderInfoEnum.STATUS_3.getValue())) {
            //已完成订单
            isAfterSales=1;
            if (order.getFinishTime() != null) {
                if (config.getStoreAfterSalesDay() != null && config.getStoreAfterSalesDay() > 0) {
                    //判断完成时间是否超过指定时间
                    Calendar calendarAfterSales = new GregorianCalendar();
                    calendarAfterSales.setTime(order.getFinishTime());
                    calendarAfterSales.add(calendarAfterSales.DATE, config.getStoreAfterSalesDay()); //把日期往后增加一天,整数  往后推,负数往前移动
                    if (calendarAfterSales.getTime().getTime() < new Date().getTime()) {
                        isAfterSales = 0;
                    }
                }
            }
        }
        else if(order.getStatus()==1||order.getStatus()==2){
            isAfterSales=1;
        }
        return R.ok().put("isAfterSales",isAfterSales).put("order",order).put("items",list).put("payLimitTime",payLimitTime);
    }

    @Login
    @ApiOperation("获取订单")
    @GetMapping("/getStoreOrderById")
    public R getStoreOrderById(@RequestParam("orderId") Long orderId, HttpServletRequest request){
        LiveOrder order=orderService.selectLiveOrderByOrderId(String.valueOf(orderId));

        order.setUserPhone(ParseUtils.parsePhone(order.getUserPhone()));
        order.setUserAddress(ParseUtils.parseIdCard(order.getUserAddress()));

        String json=configService.selectConfigByKey("his.store");
        StoreConfig config=JSONUtil.toBean(json,StoreConfig.class);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(order.getCreateTime());
        calendar.add(Calendar.MINUTE,config.getUnPayTime());
        SimpleDateFormat format = new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String payLimitTime = format.format(calendar.getTime() );
        return R.ok().put("order",order).put("payLimitTime",payLimitTime);
    }


    @Login
    @ApiOperation("确认订单")
    @PostMapping("/confirm")
    @RateLimiter(time = 10, count = 10000, msg = "当前下单的人比较多，请稍后再试")
    public R confirm(@Validated @RequestBody LiveOrderConfirmParam param, HttpServletRequest request){
        param.setUserId(Long.valueOf(getUserId()));
        return orderService.confirmOrder(param);
    }
    @Login
    @ApiOperation("计算订单金额")
    @PostMapping("/computed")
    @RateLimiter(time = 10, count = 10000, msg = "当前下单的人比较多，请稍后再试")
    public R computed(@Validated @RequestBody LiveOrderComputedParam param, HttpServletRequest request){
        LiveOrderComputeDTO dto=orderService.computedOrder(Long.parseLong(getUserId()),param);
        return R.ok().put("data",dto);
    }

    @Login
    @ApiOperation("计算中奖订单")
    @PostMapping("/computedReward")
    public R computedReward(@Validated @RequestBody LiveOrderComputedParam param){
        log.info("计算中奖订单 {}",JSON.toJSONString(param));

        LiveOrderComputeDTO dto=orderService.computedReward(Long.parseLong(getUserId()),param);
        return R.ok().put("data",dto);
    }

    /**
     * 新增中奖订单
     */
    @Login
    @Log(title = "新增中奖订单", businessType = BusinessType.INSERT)
    @PostMapping("/createReward")
    @RepeatSubmit
    public R createReward(@RequestBody LiveOrder liveOrder)
    {
        // 校验appId
        if (StringUtils.isEmpty(liveOrder.getAppId())) {
            return R.error("appId不能为空");
        }
        log.info("新增中奖订单: {}", JSON.toJSONString(liveOrder));

        liveOrder.setUserId(getUserId());
        return orderService.createRewardLiveOrder(liveOrder);
    }

    /**
     * 新增订单
     */
    @Login
    @Log(title = "提交中奖订单", businessType = BusinessType.INSERT)
    @PostMapping("/payConfirmReward")
    @RepeatSubmit
    public R payConfirmReward(@RequestBody LiveOrder liveOrder)
    {
        // 校验appId
        if (StringUtils.isEmpty(liveOrder.getAppId())) {
            return R.error("appId不能为空");
        }
        log.info("新增订单: {}", JSON.toJSONString(liveOrder));

        liveOrder.setUserId(getUserId());
        return orderService.payConfirmReward(liveOrder);
    }

    @Login
    @ApiOperation("直播创建订单")
    @PostMapping("/create")
    @RateLimiter(time = 10, count = 10000, msg = "当前下单的人比较多，请稍后再试")
    public R create(@Validated @RequestBody LiveOrder param, HttpServletRequest request){
        // 校验appId
        if (StringUtils.isEmpty(param.getAppId())) {
            return R.error("appId不能为空");
        }
        String userId= getUserId();
        log.info("开始创建订单,登录用户id:{}", userId);
        param.setUserId(userId);
        R result = orderService.createLiveOrder(param);

        // 埋点：记录购买商品行为
        if (result.get("code").equals(200) && param.getLiveId() != null) {
            try {
                // 从返回结果中获取订单对象
                Object orderObj = result.get("order");
                Long orderId = null;
                if (orderObj != null && orderObj instanceof LiveOrder) {
                    LiveOrder order = (LiveOrder) orderObj;
                    orderId = order.getOrderId();
                }

                // 构建订单扩展信息
                Map<String, Object> orderInfo = new HashMap<>();
                if (param.getProductId() != null) {
                    orderInfo.put("productId", param.getProductId());
                }
                if (param.getProductNum() != null) {
                    orderInfo.put("productNum", param.getProductNum());
                }
                if (param.getPayPrice() != null) {
                    orderInfo.put("payPrice", param.getPayPrice());
                }
                // 添加订单详细信息
                if (orderObj != null) {
                    orderInfo.put("orderData", orderObj);
                }

                LiveUserBehaviorTrack track = LiveBehaviorTrackUtil.trackPurchase(
                    Long.parseLong(userId), param.getLiveId(), orderId, orderInfo);
                behaviorTrackService.asyncInsertLiveUserBehaviorTrack(track);
            } catch (Exception e) {
                log.error("[埋点] 记录购买商品行为失败, liveId={}, userId={}",
                    param.getLiveId(), userId, e);
            }
        }

        return result;
    }

    @Login
    @GetMapping(value = "/info/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") String orderId)
    {
        log.info("获取订单详细信息 参数: {}",orderId);
        LiveOrder liveOrder = orderService.selectLiveOrderByOrderId(orderId);
        if (liveOrder == null) {
            return AjaxResult.error("订单不存在");
        }
        // 仅允许查看本人订单，防止越权
        String currentUserId = getUserId();
        if (StringUtils.isEmpty(liveOrder.getUserId()) || !liveOrder.getUserId().equals(currentUserId)) {
            return AjaxResult.error("无权查看该订单");
        }
        //订单总价 临时处理为 商品金额（商品支付金额=应付金额-快递费+优惠券）
        if(ObjectUtil.isNotEmpty(liveOrder)) {
            liveOrder.setTotalPrice(liveOrder.getPayPrice().subtract(liveOrder.getPayPostage()).add(liveOrder.getDiscountMoney()));
        }
        return AjaxResult.success(liveOrder);
    }

    @Login
    @ApiOperation("支付")
    @PostMapping("/pay")
    @Transactional
    public R pay(HttpServletRequest request, @Validated @RequestBody LiveOrderPayParam param)
    {
        // 校验appId
        if (StringUtils.isEmpty(param.getAppId())) {
            return R.error("appId不能为空");
        }
        Long orderId = param.getOrderId();
        logger.info("开始处理支付请求, 订单号: {}, 支付类型: {}", orderId, param.getPayType());
        try{
            Long existPayedRecordId = orderService.isExistPayedRecord(param.getOrderId());
            if (null != existPayedRecordId) {
                orderService.payConfirmPayment(existPayedRecordId);
                return R.error("当前订单已支付");
            }
        } catch(Exception ex){
            log.error("校验当前订单是否存在已经支付的支付记录异常,param:{}",param,ex);
        }


        RLock lock = redissonClient.getLock(String.format(LOCK_KEY_PAY,orderId));
        R result = null;

        try {
            boolean locked = lock.tryLock(100, 30000, TimeUnit.MILLISECONDS);
            if (!locked) {
                logger.warn("订单正在处理中，获取锁失败, 订单号: {}", orderId);
                return R.error("订单正在处理中，请勿重复提交");
            }

            result = orderService.handleLiveOrderPay(param);

        } catch (InterruptedException e) {
            logger.error("获取支付锁的过程被中断, 订单号: {}", orderId, e);
            Thread.currentThread().interrupt();
            return R.error("支付处理被中断，请稍后重试");
        } catch (Throwable e) {
            logger.error("支付过程中发生异常, 订单号: {}", orderId, e);
            throw e;
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
                logger.debug("支付锁已释放, 订单号: {}", orderId);
            }
        }

        return result;
    }

    @Login
    @ApiOperation("取消支付")
    @PostMapping("/cancelPay")
    public R cancelPay(@Validated @RequestBody LiveOrderPayParam param) {
        Long orderId = param.getOrderId();
        logger.info("用户取消支付 订单号: {}, 支付类型: {}", orderId, param.getPayType());
        RLock lock = redissonClient.getLock(String.format(LOCK_KEY_PAY,orderId));
        try {
            boolean locked = lock.tryLock(100, 30000, TimeUnit.MILLISECONDS);
            if (!locked) {
                logger.warn("订单正在处理中，获取锁失败, 订单号: {}", orderId);
                return R.error("订单正在处理中，请稍后再试");
            }
            handleCancelLiveOrderPay(param);
            return R.ok();
        } catch (InterruptedException e) {
            logger.error("获取取消支付锁的过程被中断, 订单号: {}", orderId, e);
            Thread.currentThread().interrupt();
            return R.error("取消支付处理被中断，请稍后重试");
        } catch (Throwable e) {
            logger.error("取消支付过程中发生异常, 订单号: {}", orderId, e);
            throw e;
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
                logger.debug("取消支付锁已释放, 订单号: {}", orderId);
            }
        }
    }



    private void handleCancelLiveOrderPay(LiveOrderPayParam param) {
        LiveOrder liveOrder = new LiveOrder();
        liveOrder.setOrderId(param.getOrderId());
        orderService.cancelOrder(liveOrder);
        redisCache.deleteObject("isPaying:"+param.getOrderId());
    }




    @Login
    @ApiOperation("修改支付类型")
    @PostMapping("/editPayType")
    @Transactional
    public R editPayType(HttpServletRequest request, @Validated @RequestBody FsStoreOrderPayParam param) {

        String orderId=redisCache.getCacheObject("isPaying:"+param.getOrderId());
        if(StringUtils.isNotEmpty(orderId)&&orderId.equals(param.getOrderId().toString())){
            return R.error("正在支付中...");
        }
        LiveOrder order=orderService.selectLiveOrderByOrderId(String.valueOf(param.getOrderId()));
        if(order==null){
            return R.error("订单不存在");
        }
        if(order.getStatus()!= OrderInfoEnum.STATUS_0.getValue()){
            return R.error("订单状态不正确");
        }
        List<LiveOrderPayment> payments = liveOrderPaymentMapper.selectLiveOrderPaymentByOrderId(order.getOrderId());
        if(payments.size()>0){
            for(LiveOrderPayment payment : payments){
                OrderQueryDTO orderQueryDTO = new OrderQueryDTO();
                orderQueryDTO.setLowOrderId("live-"+payment.getPayCode());
                OrderResult orderResult = ybPayService.getOrder(orderQueryDTO);
                if(orderResult.getStatus()!= null&&orderResult.getStatus().equals("100")){
                    if(orderResult.getState()!=null&&orderResult.getState().equals("0")){
                        return R.error("订单已支付");
                    }

                }
            }
        }
        FsUserScrm user=userService.selectFsUserById(Long.valueOf(order.getUserId()));
        if(user!=null&& StringUtils.isNotEmpty(user.getMaOpenId())){
            //已改价处理
            if(order.getIsEditMoney()!=null&&order.getIsEditMoney()==1){
                //改过价不做处理
            }
            else{
                String config=configService.selectConfigByKey("his.store");
                StoreConfig storeConfig= JSONUtil.toBean(config,StoreConfig.class);
                if(param.getPayType().equals(1)){
                    order.setPayType("1");
                    order.setPayMoney(order.getPayPrice());
                    order.setPayDelivery(BigDecimal.ZERO);
                }
                else if(param.getPayType().equals(2)){

                    order.setPayType("2");
                    BigDecimal payMoney=order.getPayPrice().multiply(new BigDecimal(storeConfig.getPayRate())).divide(new BigDecimal(100));
                    payMoney=new BigDecimal(payMoney.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    // 如果小程序需要支付的金额小于0.01元，不能走物流代收，让走货到付款 xgb
                    if (payMoney.compareTo(new BigDecimal("0.01")) < 0) {
                        return R.error("物流代收计算支付金额为0,不允许选择物流代收");
                    }
                    order.setPayDelivery(order.getPayPrice().subtract(payMoney));
                    order.setPayMoney(payMoney);
                }
                else if(param.getPayType().equals(3)){
                    //货到付款
                    order.setPayType("3");
                    BigDecimal amount=redisCache.getCacheObject("orderAmount:"+order.getOrderId());
                    BigDecimal payMoney = BigDecimal.ZERO;
                    if (amount != null){
                        payMoney=amount;
                    }
                    order.setPayMoney(payMoney);
                    order.setPayDelivery(order.getPayPrice().subtract(payMoney) );
                }
                orderService.updateLiveOrder(order);
            }
            return R.ok().put("order",order);
        }
        else{
            return R.error("用户OPENID不存在");
        }

    }
    @Login
    @ApiOperation("修改支付类型")
    @PostMapping("/clearPayType")
    @Transactional
    public R clearPayType(HttpServletRequest request, @Validated @RequestBody FsStoreOrderPayParam param) {
        redisCache.deleteObject("isPaying:"+param.getOrderId());
        return R.ok();
    }


//    @Login
//    @ApiOperation("支付尾款")
//    @PostMapping("/payRemain")
//    @Transactional
//    public R payRemain(HttpServletRequest request, @Validated @RequestBody FsStoreOrderPayParam param) {
//        LiveOrder order=orderService.selectLiveOrderByOrderId(String.valueOf(param.getOrderId()));
//        if(order==null){
//            return R.error("订单不存在");
//        }
//        if(order.getStatus()!= OrderInfoEnum.STATUS_2.getValue()){
//            return R.error("待收货订单可申请支付尾款");
//        }
//        if(order.getPayType().equals(1)){
//            return R.error("此订单已支付");
//        }
//        //只有顺风才可以付尾
//        if(!order.getDeliverySn().trim().equals("SF")){
//            return R.error("只有顺丰物流支持尾款支付");
//        }
//
//        if(!order.getIsPayRemain().equals(0)){
//            return R.error("此订单已支付");
//        }
//        FsUserScrm user=userService.selectFsUserById(order.getUserId());
//        if(user!=null&& StringUtils.isNotEmpty(user.getMaOpenId())){
//            String payCode = IdUtil.getSnowflake(0, 0).nextIdStr();
//            String json = configService.selectConfigByKey("his.pay");
//            FsPayConfigScrm fsPayConfig = JSON.parseObject(json, FsPayConfigScrm.class);
//            LiveOrderPayment storePayment=new LiveOrderPayment();
//            storePayment.setCompanyId(order.getCompanyId());
//            storePayment.setCompanyUserId(order.getCompanyUserId());
//            storePayment.setStatus(0);
//            storePayment.setPayMode(fsPayConfig.getType());
//            storePayment.setPayCode(payCode);
//            storePayment.setPayMoney(order.getPayDelivery());
//            storePayment.setCreateTime(new Date());
//            storePayment.setPayTypeCode("weixin");
//            storePayment.setBusinessType(2);
//            storePayment.setRemark("商城订单尾款支付");
//            storePayment.setOpenId(user.getRealName());
//            storePayment.setUserId(user.getUserId());
//            storePayment.setBusinessOrderId(order.getId().toString());
//            storePayment.setOrderId(order.getId());
//            storePayment.setIsPayRemain(1);
//            liveOrderPaymentMapper.insertFsStorePayment(storePayment);
//
//            if (fsPayConfig.getType().equals("hf")){
//                HuiFuCreateOrder o = new HuiFuCreateOrder();
//                o.setTradeType("T_MINIAPP");
//                o.setOpenid(user.getMaOpenId());
//                o.setReqSeqId("store_remain-"+storePayment.getPayCode());
//                o.setTransAmt(storePayment.getPayMoney().toString());
//                o.setGoodsDesc("商城订单尾款支付");
//                HuifuCreateOrderResult result = huiFuService.createOrder(o);
//                //创建订单
//                if(result.getResp_code()!=null&&(result.getResp_code().equals("00000000")||result.getResp_code().equals("00000100"))){
//
//                    LiveOrderPayment mt=new LiveOrderPayment();
//                    mt.setPaymentId(storePayment.getPaymentId());
//                    mt.setTradeNo(result.getHf_seq_id());
//                    liveOrderPaymentMapper.updateFsStorePayment(mt);
//                    redisCache.setCacheObject("isPaying:"+order.getId(),order.getId().toString(),1, TimeUnit.MINUTES);
//                    Map<String, Object> resultMap = JSON.parseObject(result.getPay_info(), new TypeReference<Map<String, Object>>() {});
//                    String s = (String) resultMap.get("package");
//                    resultMap.put("packageValue",s);
//                    return R.ok().put("payType",param.getPayType()).put("result",resultMap);
//                }
//                else{
//                    return R.error(result.getResp_desc());
//                }
//            }else if(fsPayConfig.getType().equals("wx")) {
//                WxPayConfig payConfig = new WxPayConfig();
//                payConfig.setAppId(fsPayConfig.getAppId());
//                payConfig.setMchId(fsPayConfig.getWxMchId());
//                payConfig.setMchKey(fsPayConfig.getWxMchKey());
//                payConfig.setSubAppId(org.apache.commons.lang3.StringUtils.trimToNull(null));
//                payConfig.setSubMchId(org.apache.commons.lang3.StringUtils.trimToNull(null));
//                payConfig.setKeyPath(null);
//                payConfig.setNotifyUrl(fsPayConfig.getNotifyUrlScrm());
//                wxPayService.setConfig(payConfig);
//                WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
//                orderRequest.setOpenid(user.getMaOpenId());//公众号支付提供用户openid
//                orderRequest.setBody("商城订单支付");
//                orderRequest.setOutTradeNo("store-" + storePayment.getPayCode());
//                orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(storePayment.getPayMoney().toString()));//测试
//                //orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(money));//测试
//                orderRequest.setTradeType("JSAPI");
//                orderRequest.setSpbillCreateIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
//                //调用统一下单接口，获取"预支付交易会话标识"
//                try {
//                    WxPayMpOrderResult orderResult = wxPayService.createOrder(orderRequest);
//                    return R.ok().put("result", orderResult).put("type", "wx").put("isPay", 0);
//                } catch (WxPayException e) {
//                    e.printStackTrace();
//                    throw new CustomException("支付失败" + e.getMessage());
//                }
//            }
//        }
//        else{
//            return R.error("用户OPENID不存在");
//        }
//        return R.error("无支付类型");
//    }


    @Login
    @ApiOperation("亲友支付")
    @PostMapping("/otherPayment")
    @Transactional
    public R otherPayment(@Validated @RequestBody FsStoreOrderOtherPayParam param, HttpServletRequest request){
        final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
        try {
            String ip = IpUtil.getRequestIp();
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(param.getCode());
            FsUserScrm user=userService.selectFsUserByMaOpenId(session.getOpenid());
            if(user==null){
                //创建
                user=new FsUserScrm();
                user.setUsername("");
                user.setNickname("微信用户");
                user.setStatus(1);
                user.setMaOpenId(session.getOpenid());
                user.setUnionId(session.getUnionid());
                user.setIsWeixinAuth(0);
                user.setLastIp(ip);
                user.setCreateTime(new Date());
                userService.insertFsUser(user);
            }
            LiveOrder order=orderService.selectLiveOrderByOrderId(String.valueOf(param.getOrderId()));
            if(order==null){
                return R.error("订单不存在");
            }
            if(order.getStatus()!= OrderInfoEnum.STATUS_0.getValue()){
                return R.error("此订单不能支付");
            }
            if(order.getPayMoney().compareTo(new BigDecimal(0))<1){
                return R.error("此订单没有可支付的金额");
            }

            String orderId=redisCache.getCacheObject("isPaying:"+order.getOrderId());
            if(StringUtils.isNotEmpty(orderId)&&orderId.equals(order.getOrderId().toString())){
                return R.error("正在支付中...");
            }

            if (StringUtils.isBlank(param.getAppId())) {
                throw new IllegalArgumentException("appId不能为空");
            }
            FsCoursePlaySourceConfig fsCoursePlaySourceConfig = fsCoursePlaySourceConfigMapper.selectCoursePlaySourceConfigByAppId(param.getAppId());
            if (fsCoursePlaySourceConfig == null) {
                throw new CustomException("未找到appId对应的小程序配置: " + param.getAppId());
            }
            Long merchantConfigId = fsCoursePlaySourceConfig.getMerchantConfigId();
            if (merchantConfigId == null || merchantConfigId <= 0) {
                throw new CustomException("小程序没有配置商户信息");
            }
            MerchantAppConfig merchantAppConfig = merchantAppConfigMapper.selectMerchantAppConfigById(fsCoursePlaySourceConfig.getMerchantConfigId());
            FsPayConfig fsPayConfig = JSON.parseObject(merchantAppConfig.getDataJson(), FsPayConfig.class);
            String payCode = IdUtil.getSnowflake(0, 0).nextIdStr();
            //易宝支付
            LiveOrderPayment storePayment=new LiveOrderPayment();
            storePayment.setCompanyId(order.getCompanyId());
            storePayment.setCompanyUserId(order.getCompanyUserId());
            storePayment.setStatus(0);
            storePayment.setPayCode(payCode);
            storePayment.setPayMode(merchantAppConfig.getMerchantType());
            storePayment.setPayMoney(order.getPayMoney());
            storePayment.setCreateTime(new Date());
            storePayment.setPayTypeCode("weixin");
            storePayment.setBusinessType(2);
            storePayment.setRemark("商城订单支付");
            storePayment.setOpenId(session.getOpenid());
            storePayment.setUserId(user.getUserId());
            storePayment.setBusinessId(order.getOrderId().toString());
            liveOrderPaymentMapper.insertLiveOrderPayment(storePayment);

            if (merchantAppConfig.getMerchantType().equals("hf")){
                HuiFuCreateOrder o = new HuiFuCreateOrder();
                o.setTradeType("T_MINIAPP");
                o.setOpenid(user.getMaOpenId());
                o.setReqSeqId("store-"+storePayment.getPayCode());
                o.setTransAmt(storePayment.getPayMoney().toString());
                o.setGoodsDesc("商城订单支付");
                HuifuCreateOrderResult result = huiFuService.createOrder(o);
                if(result.getResp_code()!=null&&(result.getResp_code().equals("00000000")||result.getResp_code().equals("00000100"))){

                    LiveOrderPayment mt=new LiveOrderPayment();
                    mt.setPaymentId(storePayment.getPaymentId());
                    mt.setTradeNo(result.getHf_seq_id());
                    liveOrderPaymentMapper.updateLiveOrderPayment(mt);
                    redisCache.setCacheObject("isPaying:"+order.getOrderId(),order.getOrderId().toString(),1, TimeUnit.MINUTES);
                    Map<String, Object> resultMap = JSON.parseObject(result.getPay_info(), new TypeReference<Map<String, Object>>() {});
                    String s = (String) resultMap.get("package");
                    resultMap.put("packageValue",s);
                    return R.ok().put("result",resultMap);
                }
                else{
                    return R.error(result.getResp_desc());
                }
            }else  if (merchantAppConfig.getMerchantType().equals("wx")){
                //创建微信订单
                WxPayConfig payConfig = new WxPayConfig();
                payConfig.setAppId(fsCoursePlaySourceConfig.getAppid());
                payConfig.setMchId(fsPayConfig.getWxMchId());
                payConfig.setMchKey(fsPayConfig.getWxMchKey());
                payConfig.setSubAppId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                payConfig.setSubMchId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                payConfig.setKeyPath(null);
                payConfig.setNotifyUrl(fsPayConfig.getNotifyUrlScrm());
                wxPayService.setConfig(payConfig);
                WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
                orderRequest.setOpenid(user.getMaOpenId());//公众号支付提供用户openid
                orderRequest.setBody("商城订单支付");
                orderRequest.setOutTradeNo("store-" + storePayment.getPayCode());
                orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(storePayment.getPayMoney().toString()));//测试
                //orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(money));//测试
                orderRequest.setTradeType("JSAPI");
                orderRequest.setSpbillCreateIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
                //调用统一下单接口，获取"预支付交易会话标识"
                try {
                    WxPayMpOrderResult orderResult = wxPayService.createOrder(orderRequest);
                    return R.ok().put("result", orderResult).put("type", "wx").put("isPay", 0);
                } catch (WxPayException e) {
                    e.printStackTrace();
                    throw new CustomException("支付失败" + e.getMessage());
                }
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
        return R.error("无支付类型");
    }

    @Login
    @ApiOperation("亲友支付")
    @PostMapping("/otherPaymentRemain")
    @Transactional
    public R otherPaymentRemain(@Validated @RequestBody FsStoreOrderOtherPayParam param, HttpServletRequest request){
        final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
        try {
            String ip = IpUtil.getRequestIp();
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(param.getCode());
            FsUserScrm user=userService.selectFsUserByMaOpenId(session.getOpenid());
            if(user==null){
                //创建
                user=new FsUserScrm();
                user.setUsername("");
                user.setNickname("微信用户");
                user.setStatus(1);
                user.setMaOpenId(session.getOpenid());
                user.setUnionId(session.getUnionid());
                user.setIsWeixinAuth(0);
                user.setLastIp(ip);
                user.setCreateTime(new Date());
                userService.insertFsUser(user);
            }
            LiveOrder order=orderService.selectLiveOrderByOrderId(String.valueOf(param.getOrderId()));
            if(order==null){
                return R.error("订单不存在");
            }
            if(order.getStatus()!= OrderInfoEnum.STATUS_2.getValue()){
                return R.error("待收货订单可申请支付尾款");
            }
            if(order.getPayType().equals(1)){
                return R.error("此订单已支付");
            }
            //只有顺风才可以付尾
            if(!order.getDeliverySn().trim().equals("SF")){
                return R.error("只有顺丰物流支持尾款支付");
            }

            String payCode = IdUtil.getSnowflake(0, 0).nextIdStr();
            if (StringUtils.isBlank(param.getAppId())) {
                throw new IllegalArgumentException("appId不能为空");
            }
            FsCoursePlaySourceConfig fsCoursePlaySourceConfig = fsCoursePlaySourceConfigMapper.selectCoursePlaySourceConfigByAppId(param.getAppId());
            if (fsCoursePlaySourceConfig == null) {
                throw new CustomException("未找到appId对应的小程序配置: " + param.getAppId());
            }
            Long merchantConfigId = fsCoursePlaySourceConfig.getMerchantConfigId();
            if (merchantConfigId == null || merchantConfigId <= 0) {
                throw new CustomException("小程序没有配置商户信息");
            }
            MerchantAppConfig merchantAppConfig = merchantAppConfigMapper.selectMerchantAppConfigById(fsCoursePlaySourceConfig.getMerchantConfigId());
            FsPayConfig fsPayConfig = JSON.parseObject(merchantAppConfig.getDataJson(), FsPayConfig.class);
            LiveOrderPayment storePayment=new LiveOrderPayment();
            storePayment.setCompanyId(order.getCompanyId());
            storePayment.setCompanyUserId(order.getCompanyUserId());
            storePayment.setStatus(0);
            storePayment.setPayMode(merchantAppConfig.getMerchantType());
            storePayment.setPayCode(payCode);
            storePayment.setPayMoney(order.getPayDelivery());
            storePayment.setCreateTime(new Date());
            storePayment.setPayTypeCode("weixin");
            storePayment.setBusinessType(2);
            storePayment.setRemark("直播订单尾款支付");
            storePayment.setOpenId(user.getRealName());
            storePayment.setUserId(user.getUserId());
            storePayment.setBusinessId(order.getOrderId().toString());
            liveOrderPaymentMapper.insertLiveOrderPayment(storePayment);

            if (merchantAppConfig.getMerchantType().equals("hf")){
                HuiFuCreateOrder o = new HuiFuCreateOrder();
                o.setTradeType("T_MINIAPP");
                o.setOpenid(user.getMaOpenId());
                o.setReqSeqId("live-"+storePayment.getPayCode());
                o.setTransAmt(storePayment.getPayMoney().toString());
                o.setGoodsDesc("直播订单支付");
                HuifuCreateOrderResult result = huiFuService.createOrder(o);
                if(result.getResp_code()!=null&&(result.getResp_code().equals("00000000")||result.getResp_code().equals("00000100"))){

                    LiveOrderPayment mt=new LiveOrderPayment();
                    mt.setPaymentId(storePayment.getPaymentId());
                    mt.setTradeNo(result.getHf_seq_id());
                    liveOrderPaymentMapper.updateLiveOrderPayment(mt);
                    redisCache.setCacheObject("isPaying:"+order.getOrderId(),order.getOrderId().toString(),1, TimeUnit.MINUTES);
                    Map<String, Object> resultMap = JSON.parseObject(result.getPay_info(), new TypeReference<Map<String, Object>>() {});
                    String s = (String) resultMap.get("package");
                    resultMap.put("packageValue",s);
                    return R.ok().put("result",resultMap);
                }
                else{
                    return R.error(result.getResp_desc());
                }
            }else  if (merchantAppConfig.getMerchantType().equals("wx")){
                //创建微信订单
                WxPayConfig payConfig = new WxPayConfig();
                payConfig.setAppId(fsCoursePlaySourceConfig.getAppid());
                payConfig.setMchId(fsPayConfig.getWxMchId());
                payConfig.setMchKey(fsPayConfig.getWxMchKey());
                payConfig.setSubAppId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                payConfig.setSubMchId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                payConfig.setKeyPath(null);
                payConfig.setNotifyUrl(fsPayConfig.getNotifyUrlScrm());
                wxPayService.setConfig(payConfig);
                WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
                orderRequest.setOpenid(user.getMaOpenId());//公众号支付提供用户openid
                orderRequest.setBody("直播订单支付");
                orderRequest.setOutTradeNo("live-" + storePayment.getPayCode());
                orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(storePayment.getPayMoney().toString()));//测试
                //orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(money));//测试
                orderRequest.setTradeType("JSAPI");
                orderRequest.setSpbillCreateIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
                //调用统一下单接口，获取"预支付交易会话标识"
                try {
                    WxPayMpOrderResult orderResult = wxPayService.createOrder(orderRequest);
                    return R.ok().put("result", orderResult).put("type", "wx").put("isPay", 0);
                } catch (WxPayException e) {
                    e.printStackTrace();
                    throw new CustomException("支付失败" + e.getMessage());
                }
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
        return R.error("无支付类型");
    }


    @Login
    @ApiOperation("取消订单")
    @PostMapping("/cancelOrder")
//    @Log(title = "取消订单", businessType = BusinessType.UPDATE)
    public R cancelOrder( @Validated @RequestBody FsStoreOrderCancelParam param, HttpServletRequest request){
        LiveOrder order=orderService.selectLiveOrderByOrderId(String.valueOf(param.getOrderId()));
        if (ObjectUtil.isNull(order)) {
            throw new CustomException("订单不存在");
        }
        if (order.getStatus() !=0) {
            throw new CustomException("非法操作");
        }
        order.setCouponUserId(Long.parseLong(getUserId()));
        orderService.cancelOrder(order);

        return R.ok("操作成功");
    }
    @Login
    @ApiOperation("物流查询")
    @PostMapping("/getExpress")
    public R getExpress(@Validated @RequestBody FsStoreOrderExpressParam param, HttpServletRequest request){
        LiveOrder order=orderService.selectLiveOrderByOrderId(String.valueOf(param.getOrderId()));
        if (ObjectUtil.isNull(order)) {
            throw new CustomException("订单不存在");
        }
        if (order.getStatus() <2) {
            throw new CustomException("未发货订单不能查询");
        }
        return orderService.getExpress(order);
    }

    @Login
    @ApiOperation("物流查询多运单号")
    @PostMapping("/getExpressMulti")
    public R getExpressMulti( @Validated @RequestBody FsStoreOrderExpressParam param){
        log.info("物流查询多运单号 请求参数: {}", JSON.toJSONString(param));
        LiveOrder order=orderService.selectLiveOrderByOrderId(String.valueOf(param.getOrderId()));
        if (ObjectUtil.isNull(order)) {
            throw new CustomException("订单不存在");
        }
//        if (order.getStatus() < 2) {
//            throw new CustomException("未发货订单不能查询");
//        }
        return orderService.getExpressMulti(order);
    }



    @Login
    @ApiOperation("完成订单")
    @PostMapping("/finishOrder")
    public R finishOrder( @Validated @RequestBody FsStoreOrderFinishParam param, HttpServletRequest request){
        return orderService.finishOrder(param.getOrderId());
    }


    @Login
    @ApiOperation("获取订单总数")
    @GetMapping("/getOrderCount")
    public R getOrderCount( HttpServletRequest request){
        Integer count0=orderService.selectFsStoreOrderCount(Long.parseLong(getUserId()),0);
        Integer count1=orderService.selectFsStoreOrderCount(Long.parseLong(getUserId()),1);
        Integer count2=orderService.selectFsStoreOrderCount(Long.parseLong(getUserId()),2);
        Integer afterSalesCount=liveAfterSalesService.selectLiveAfterSalesCount(Long.parseLong(getUserId()),0);
        return R.ok().put("count0",count0).put("count1",count1).put("count2",count2).put("afterSalesCount",afterSalesCount);
    }


    @ApiOperation("批量生成售后订单并退款")
//    @PostMapping("/batchCreateAfterSalesAndRefund")
    public R batchCreateAfterSalesAndRefund(@RequestBody List<String> payCodes) {
        if (payCodes == null || payCodes.isEmpty()) {
            return R.error("支付订单号列表不能为空");
        }

        List<Map<String, Object>> results = new ArrayList<>();

        for (String payCode : payCodes) {
            Map<String, Object> result = new HashMap<>();
            result.put("payCode", payCode);

            try {
                // 先查询支付记录
                // 先尝试查询商城订单支付记录
                FsStorePaymentScrm storePayment = fsStorePaymentScrmMapper.selectFsStorePaymentByCode(payCode.split("-")[1]);

                if (storePayment != null) {
                    // 商城订单支付记录
                    result.put("paymentType", "store");
                    result.put("paymentId", storePayment.getPaymentId());

                    // 根据支付记录查询订单
                    FsStoreOrderScrm storeOrder = null;
                    if (storePayment.getOrderId() != null) {
                        storeOrder = fsStoreOrderScrmService.selectFsStoreOrderById(storePayment.getOrderId());
                    } else if (StringUtils.isNotEmpty(storePayment.getBusinessOrderId())) {
                        // 如果没有orderId，尝试通过businessOrderId查询
                        storeOrder = fsStoreOrderScrmService.selectFsStoreOrderByOrderCode(storePayment.getBusinessOrderId());
                    }

                    if (storeOrder == null) {
                        result.put("success", false);
                        result.put("message", "根据支付记录未找到对应的订单");
                        results.add(result);
                        continue;
                    }

                    result.put("orderCode", storeOrder.getOrderCode());
                    result.put("orderId", storeOrder.getId());

                    // 查询售后记录
                    FsStoreAfterSalesScrm queryAfterSales = new FsStoreAfterSalesScrm();
                    queryAfterSales.setOrderCode(storeOrder.getOrderCode());
                    List<FsStoreAfterSalesScrm> existingAfterSales = fsStoreAfterSalesScrmService.selectFsStoreAfterSalesList(queryAfterSales);

                    FsStoreAfterSalesScrm afterSales = null;
                    if (existingAfterSales == null || existingAfterSales.isEmpty()) {
                        // 创建售后记录
                        afterSales = new FsStoreAfterSalesScrm();
                        afterSales.setOrderCode(storeOrder.getOrderCode());
                        afterSales.setRefundAmount(storeOrder.getPayMoney());
                        afterSales.setServiceType(0); // 0仅退款
                        afterSales.setReasons("系统自动生成售后订单");
                        afterSales.setExplains("系统自动生成售后订单");
                        afterSales.setExplainImg(null);
                        afterSales.setStatus(AfterSalesStatusEnum.STATUS_4.getValue()); // 4财务已审核（退款成功）
                        afterSales.setSalesStatus(3); // 3已完成
                        afterSales.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
                        afterSales.setIsDel(0);
                        afterSales.setUserId(storeOrder.getUserId());
                        afterSales.setOrderStatus(storeOrder.getStatus());
                        afterSales.setCompanyId(storeOrder.getCompanyId());
                        afterSales.setCompanyUserId(storeOrder.getCompanyUserId());
                        if (storeOrder.getPackageJson() != null) {
                            afterSales.setPackageJson(storeOrder.getPackageJson());
                        }
                        if (storeOrder.getIsPackage() != null) {
                            afterSales.setIsPackage(storeOrder.getIsPackage());
                        }
                        fsStoreAfterSalesScrmService.insertFsStoreAfterSales(afterSales);
                        result.put("afterSalesCreated", true);
                    } else {
                        afterSales = existingAfterSales.get(0);
                        result.put("afterSalesCreated", false);
                        result.put("afterSalesId", afterSales.getId());
                    }

                    // 修改订单状态为退款成功
                    storeOrder.setStatus(OrderInfoEnum.STATUS_NE2.getValue()); // -2退款成功
                    storeOrder.setRefundStatus(OrderInfoEnum.REFUND_STATUS_2.getValue()); // 2已退款
                    storeOrder.setRefundPrice(storeOrder.getPayMoney());
                    fsStoreOrderScrmService.updateFsStoreOrder(storeOrder);

                    result.put("success", true);
                    result.put("message", "处理成功");
                    result.put("afterSalesId", afterSales != null ? afterSales.getId() : null);

                } else {
                    // 尝试查询直播订单支付记录
                    LiveOrderPayment livePayment = liveOrderPaymentMapper.selectLiveOrderPaymentByPaymentCode(payCode.split("-")[1]);

                    if (livePayment != null) {
                        // 直播订单支付记录
                        result.put("paymentType", "live");
                        result.put("paymentId", livePayment.getPaymentId());

                        // 根据支付记录查询订单
                        LiveOrder liveOrder = null;
                        if (StringUtils.isNotEmpty(livePayment.getBusinessId())) {
                            // businessId 是订单ID（Long类型转String）
                            try {
                                Long orderId = Long.parseLong(livePayment.getBusinessId());
                                liveOrder = orderService.selectLiveOrderByOrderId(String.valueOf(orderId));
                            } catch (NumberFormatException e) {
                                // 如果不是数字，可能是订单号
                                liveOrder = orderService.selectLiveOrderByOrderId(livePayment.getBusinessId());
                            }
                        } else if (StringUtils.isNotEmpty(livePayment.getBusinessCode())) {
                            // 通过businessCode（订单号）查询
                            liveOrder = orderService.selectLiveOrderByOrderId(livePayment.getBusinessCode());
                        }

                        if (liveOrder == null) {
                            result.put("success", false);
                            result.put("message", "根据支付记录未找到对应的订单");
                            results.add(result);
                            continue;
                        }

                        result.put("orderCode", liveOrder.getOrderCode());
                        result.put("orderId", liveOrder.getOrderId());

                        // 查询售后记录
                        LiveAfterSales queryAfterSales = new LiveAfterSales();
                        queryAfterSales.setOrderId(liveOrder.getOrderId());
                        List<LiveAfterSales> existingAfterSales = liveAfterSalesService.selectLiveAfterSalesList(queryAfterSales);

                        LiveAfterSales afterSales = null;
                        if (existingAfterSales == null || existingAfterSales.isEmpty()) {
                            // 创建售后记录
                            afterSales = new LiveAfterSales();
                            afterSales.setOrderId(liveOrder.getOrderId());
                            afterSales.setRefundAmount(liveOrder.getPayMoney());
                            afterSales.setRefundType(0); // 0仅退款
                            afterSales.setReasons("系统自动生成售后订单");
                            afterSales.setExplains("系统自动生成售后订单");
                            afterSales.setExplainImg(null);
                            afterSales.setStatus(LiveAfterSalesStatusEnum.STATUS_4.getValue()); // 4财务已审核（退款成功）
                            afterSales.setSalesStatus(3); // 3已完成
                            afterSales.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
                            afterSales.setIsDel(0);
                            afterSales.setUserId(Long.valueOf(liveOrder.getUserId()));
                            afterSales.setOrderStatus(liveOrder.getStatus());
                            afterSales.setCompanyId(liveOrder.getCompanyId());
                            afterSales.setCompanyUserId(liveOrder.getCompanyUserId());
                            liveAfterSalesService.insertLiveAfterSales(afterSales);
                            result.put("afterSalesCreated", true);
                        } else {
                            afterSales = existingAfterSales.get(0);
                            result.put("afterSalesCreated", false);
                            result.put("afterSalesId", afterSales.getId());
                        }

                        // 修改订单状态为退款成功
                        liveOrder.setStatus(OrderInfoEnum.STATUS_NE2.getValue()); // -2退款成功
                        liveOrder.setRefundStatus(String.valueOf(OrderInfoEnum.REFUND_STATUS_2.getValue())); // 2已退款
                        liveOrder.setRefundMoney(liveOrder.getPayMoney());
                        liveOrder.setRefundTime(new Date());
                        orderService.updateLiveOrder(liveOrder);

                        result.put("success", true);
                        result.put("message", "处理成功");
                        result.put("afterSalesId", afterSales != null ? afterSales.getId() : null);

                    } else {
                        result.put("success", false);
                        result.put("message", "未找到对应的支付记录");
                    }
                }

            } catch (Exception e) {
                logger.error("处理支付订单失败: " + payCode, e);
                result.put("success", false);
                result.put("message", "处理失败: " + e.getMessage());
            }

            results.add(result);
        }

        return R.ok().put("results", results);
    }

}
