package com.fs.course.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.ip.IpUtils;
import com.fs.core.config.WxPayProperties;
import com.fs.core.utils.OrderCodeUtils;
import com.fs.course.domain.FsCourseProduct;
import com.fs.course.mapper.FsCourseProductMapper;
import com.fs.course.param.FsCourseProductOrderCreateParam;
import com.fs.course.param.FsCourseProductOrderListParam;
import com.fs.course.param.FsCourseProductOrderListUParam;
import com.fs.course.vo.FsCourseProductOrderListUVO;
import com.fs.course.vo.FsCourseProductOrderVO;
import com.fs.his.domain.*;
import com.fs.his.dto.PayConfigDTO;
import com.fs.his.enums.FsCourseProductOrderStatusEnum;
import com.fs.his.mapper.FsStorePaymentMapper;
import com.fs.his.mapper.FsUserWxMapper;
import com.fs.his.param.ApplyCourseProductOrderRefundParam;
import com.fs.his.param.FsCourseProductOrderComputeParam;
import com.fs.his.param.FsCourseProductOrderDoPayParam;
import com.fs.his.param.FsCourseProductOrderRefundParam;
import com.fs.his.service.IFsStorePaymentService;
import com.fs.his.service.IFsUserService;
import com.fs.his.service.IFsUserWxService;
import com.fs.his.utils.PhoneUtil;
import com.fs.huifuPay.domain.HuiFuCreateOrder;
import com.fs.huifuPay.domain.HuiFuRefundResult;
import com.fs.huifuPay.domain.HuifuCreateOrderResult;
import com.fs.huifuPay.sdk.opps.core.request.V2TradePaymentScanpayRefundRequest;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.system.service.ISysConfigService;
import com.fs.tzBankPay.TzBankService.TzBankService;
import com.fs.tzBankPay.doman.*;
import com.fs.ybPay.domain.CreateWxOrderResult;
import com.fs.ybPay.domain.OrderResult;
import com.fs.ybPay.domain.RefundResult;
import com.fs.ybPay.dto.OrderQueryDTO;
import com.fs.ybPay.dto.RefundDTO;
import com.fs.ybPay.dto.WxJspayDTO;
import com.fs.ybPay.service.IPayService;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.course.mapper.FsCourseProductOrderMapper;
import com.fs.course.domain.FsCourseProductOrder;
import com.fs.course.service.IFsCourseProductOrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * 拍单商品订单Service业务层处理
 *
 * @author fs
 * @date 2025-07-28
 */
@Service
public class FsCourseProductOrderServiceImpl extends ServiceImpl<FsCourseProductOrderMapper, FsCourseProductOrder> implements IFsCourseProductOrderService {
    Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private WxPayProperties wxPayProperties;

    @Autowired
    private FsCourseProductMapper courseProductMapper;

    @Autowired FsCourseProductOrderMapper courseProductOrderMapper;

    @Autowired
    private IFsUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IFsStorePaymentService storePaymentService;

    @Autowired
    SysConfigMapper sysConfigMapper;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    IPayService payService;

    @Autowired
    private FsStorePaymentMapper fsStorePaymentMapper;

    @Autowired
    private TzBankService tzBankService;

    @Autowired
    private HuiFuService huiFuService;

    @Autowired
    private IPayService ybPayService;

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    private static final int CODE_LENGTH = 12;

//    @Autowired
//    private IFsUserWxService userWxService;

    @Autowired
    private FsUserWxMapper fsUserWxMapper;


    /**
     * 查询拍单商品订单
     *
     * @param courseOrderId 拍单商品订单主键
     * @return 拍单商品订单
     */
    @Override
    public FsCourseProductOrder selectFsCourseProductOrderByCourseOrderId(Long courseOrderId)
    {
        return baseMapper.selectFsCourseProductOrderByCourseOrderId(courseOrderId);
    }

    /**
     * 查询拍单商品订单列表
     *
     * @param param 拍单商品订单
     * @return 拍单商品订单
     */
    @Override
    public List<FsCourseProductOrderVO> selectFsCourseProductOrderList(FsCourseProductOrderListParam param)
    {
        List<FsCourseProductOrderVO> productOrderVOS = baseMapper.selectFsCourseProductOrderList(param);
        if (CollectionUtils.isNotEmpty(productOrderVOS)) {
            productOrderVOS.forEach(productOrderVO -> {
                if (StringUtils.isNotEmpty(productOrderVO.getProductJson())) {
                    FsCourseProduct courseProduct = JSONUtil.toBean(productOrderVO.getProductJson(), FsCourseProduct.class);
                    productOrderVO.setProductName(courseProduct.getProductName());
                }
                if (productOrderVO.getUserPhone() != null && productOrderVO.getUserPhone().length() > 11) {
                    productOrderVO.setUserPhone(PhoneUtil.decryptPhoneMk(productOrderVO.getUserPhone()));
                } else {
                    if (productOrderVO.getUserPhone()!=null) {
                        productOrderVO.setUserPhone(productOrderVO.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                    }
                }
            });
        }
        return productOrderVOS;
    }

    /**
     * 新增拍单商品订单
     *
     * @param fsCourseProductOrder 拍单商品订单
     * @return 结果
     */
    @Override
    public int insertFsCourseProductOrder(FsCourseProductOrder fsCourseProductOrder)
    {
        fsCourseProductOrder.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertFsCourseProductOrder(fsCourseProductOrder);
    }

    /**
     * 修改拍单商品订单
     *
     * @param fsCourseProductOrder 拍单商品订单
     * @return 结果
     */
    @Override
    public int updateFsCourseProductOrder(FsCourseProductOrder fsCourseProductOrder)
    {
        fsCourseProductOrder.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateFsCourseProductOrder(fsCourseProductOrder);
    }

    /**
     * 批量删除拍单商品订单
     *
     * @param courseOrderIds 需要删除的拍单商品订单主键
     * @return 结果
     */
    @Override
    public int deleteFsCourseProductOrderByCourseOrderIds(Long[] courseOrderIds)
    {
        return baseMapper.deleteFsCourseProductOrderByCourseOrderIds(courseOrderIds);
    }

    /**
     * 删除拍单商品订单信息
     *
     * @param courseOrderId 拍单商品订单主键
     * @return 结果
     */
    @Override
    public int deleteFsCourseProductOrderByCourseOrderId(Long courseOrderId)
    {
        return baseMapper.deleteFsCourseProductOrderByCourseOrderId(courseOrderId);
    }

    @Override
    public R createOrder(FsCourseProductOrderCreateParam param) {
        FsCourseProduct courseProduct = courseProductMapper.selectFsCourseProductById(param.getCourseProductId());
        if (courseProduct == null) {
            return R.error("商品不存在");
        }

        FsCourseProductOrder courseProductOrder = new FsCourseProductOrder();
        BeanUtils.copyProperties(param, courseProductOrder);
        String orderCode =  OrderCodeUtils.getOrderSn();
        if(StringUtils.isEmpty(orderCode)){
            return R.error("订单生成失败，请重试");
        }
        courseProductOrder.setOrderCode(orderCode);
        courseProductOrder.setIsPay(0L);
        courseProductOrder.setCreateTime(new Date());
        courseProductOrder.setProductJson(JSON.toJSONString(courseProduct));
        courseProductOrder.setStatus(1L);
        courseProductOrder.setVerifyCode(VerificationCodeGenerator());
        try {
            if (baseMapper.insertFsCourseProductOrder(courseProductOrder) > 0) {
                return R.ok("下单成功").put("order",courseProductOrder);
            } else {
                return R.error("订单创建失败");
            }
        } catch (Exception e) {
            // 异常处理
            return R.error("订单创建失败：" + e.getMessage());
        }
    }

    @Override
    public FsCourseProductOrderListUVO selectCourseProductByCourseOrderId(Long courseOrderId) {
        FsCourseProductOrderListUVO productOrderListUVO = new FsCourseProductOrderListUVO();
        FsCourseProductOrder courseProductOrder = courseProductOrderMapper.selectFsCourseProductOrderByCourseOrderId(courseOrderId);
        if (ObjectUtil.isNotEmpty(courseProductOrder)) {
            BeanUtils.copyProperties(courseProductOrder, productOrderListUVO);
            productOrderListUVO.setProductJson(courseProductOrder.getProductJson());
        }
        return productOrderListUVO;
    }

    @Override
    public R computeOrder(FsCourseProductOrderComputeParam param) {
        FsCourseProductOrder courseProductOrder = courseProductOrderMapper.selectFsCourseProductOrderByCourseOrderId(param.getOrderId());
        if (courseProductOrder == null) {
            return R.error("订单不存在");
        }
        if (courseProductOrder.getStatus() != 1) {
            return R.error("订单状态不正确");
        }
        FsUser user = userService.selectFsUserByUserId(courseProductOrder.getUserId());

        String json = configService.selectConfigByKey("his.pay");
        PayConfigDTO payConfigDTO = JSONUtil.toBean(json, PayConfigDTO.class);
        String openId = null;
        String appId = param.getAppId();
        if (StringUtils.isNotBlank(appId)) {
            //查询fs_user_wx的openId
            Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
                    .eq(FsUserWx::getFsUserId, user.getUserId())
                    .eq(FsUserWx::getAppId, appId);
            FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
            logger.info("用户微信信息==============={}",fsUserWx);
            if (fsUserWx != null) {
                openId = fsUserWx.getOpenId();
            }
        } else {
            appId = payConfigDTO.getAppId();
            openId = Objects.isNull(user) ? "" : user.getMaOpenId();
            if (StringUtils.isBlank(openId)){
                Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
                        .eq(FsUserWx::getFsUserId, user.getUserId())
                        .eq(FsUserWx::getAppId, appId);
                FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
                logger.info("用户微信信息==============={}",fsUserWx);
                if (Objects.nonNull(fsUserWx)){
                    openId = fsUserWx.getOpenId();
                }
            }
        }

//        FsUserWx fsUserWx = userWxService.selectByAppIdAndUserId(param.getAppId(), user.getUserId(), 1);
//        logger.info("用户微信信息==============={}",fsUserWx);
//        if (user != null && fsUserWx != null && StringUtils.isNotEmpty(fsUserWx.getOpenId())) {
        if (user != null && StringUtils.isNotEmpty(openId)) {
            Map<String,Object> moneys= Maps.newHashMap();
            FsCourseProduct courseProduct = JSONUtil.toBean(courseProductOrder.getProductJson(), FsCourseProduct.class);
            moneys.put("payPrice",courseProduct.getProductPrice());
            moneys.put("product",courseProduct);
            return R.ok().put("moneys",moneys);
        } else {
            return R.error("用户不存在");
        }

    }

    @Override
    public List<FsCourseProductOrderListUVO> selectFsCourseProductOrderListUVO(FsCourseProductOrderListUParam param) {

        List<FsCourseProductOrderListUVO> productOrderListUVOS = baseMapper.selectFsCourseProductOrderListUVO(param);
        //订单商品价格
        if (CollectionUtils.isNotEmpty(productOrderListUVOS)) {
            productOrderListUVOS.forEach(item -> {
                FsCourseProduct courseProduct = JSONUtil.toBean(item.getProductJson(), FsCourseProduct.class);
                if (courseProduct != null) {
                    item.setPrice(courseProduct.getProductPrice());
                }
            });
        }
        return productOrderListUVOS;
    }

    @Override
    @Transactional
    public R payment(FsCourseProductOrderDoPayParam param) {
        logger.info("支付参数==============={}",param);
        FsCourseProductOrder courseProductOrder = courseProductOrderMapper.selectFsCourseProductOrderByCourseOrderId(param.getOrderId());
        logger.info("订单信息==============={}",courseProductOrder);
        if (!FsCourseProductOrderStatusEnum.STATUS_1.getValue().equals(courseProductOrder.getStatus())) {
            return R.error("非法操作");
        }
        FsCourseProduct courseProduct = JSONUtil.toBean(courseProductOrder.getProductJson(), FsCourseProduct.class);
        if (courseProduct == null) {
            return R.error("订单商品不存在");
        }
        FsUser user = userService.selectFsUserByUserId(param.getUserId());
        logger.info("用户信息==============={}",user);

        String json = configService.selectConfigByKey("his.pay");
        PayConfigDTO payConfigDTO = JSONUtil.toBean(json, PayConfigDTO.class);
        String openId = null;
        String appId = param.getAppId();
        if (StringUtils.isNotBlank(appId)) {
            //查询fs_user_wx的openId
            Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
                    .eq(FsUserWx::getFsUserId, user.getUserId())
                    .eq(FsUserWx::getAppId, appId);
            FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
            logger.info("用户微信信息==============={}",fsUserWx);
            if (fsUserWx != null) {
                openId = fsUserWx.getOpenId();
            }
        } else {
            appId = payConfigDTO.getAppId();
            openId = Objects.isNull(user) ? "" : user.getMaOpenId();
            if (StringUtils.isBlank(openId)){
                Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
                        .eq(FsUserWx::getFsUserId, user.getUserId())
                        .eq(FsUserWx::getAppId, appId);
                FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
                logger.info("用户微信信息==============={}",fsUserWx);
                if (Objects.nonNull(fsUserWx)){
                    openId = fsUserWx.getOpenId();
                }
            }
        }

//        FsUserWx fsUserWx = userWxService.selectByAppIdAndUserId(param.getAppId(), user.getUserId(), 1);
//        logger.info("用户微信信息==============={}",fsUserWx);
//        if (user != null && fsUserWx != null && StringUtils.isNotEmpty(fsUserWx.getOpenId())) {
        if (user != null && StringUtils.isNotEmpty(openId)) {
            if (courseProduct.getProductPrice().compareTo(new BigDecimal(0))==1) {
//                String json = configService.selectConfigByKey("his.pay");
//                PayConfigDTO payConfigDTO = JSONUtil.toBean(json, PayConfigDTO.class);
                String payCode =  OrderCodeUtils.getOrderSn();
                if(StringUtils.isEmpty(payCode)){
                    return R.error("订单生成失败，请重试");
                }
                FsStorePayment storePayment=new FsStorePayment();
                storePayment.setStatus(0);
                storePayment.setPayMode(payConfigDTO.getType());
                storePayment.setBusinessCode(courseProductOrder.getOrderCode());
                storePayment.setPayCode(payCode);
                storePayment.setPayMoney(courseProduct.getProductPrice());
                storePayment.setCreateTime(new Date());
                storePayment.setPayTypeCode("weixin");
                storePayment.setBusinessType(6);
                storePayment.setCompanyId(courseProductOrder.getCompanyId());
                storePayment.setCompanyUserId(courseProductOrder.getCompanyUserId());
                storePayment.setRemark("拍商品订单支付");
                storePayment.setOpenId(openId);
                storePayment.setUserId(user.getUserId());
                storePayment.setBusinessId(courseProductOrder.getCourseOrderId().toString());
                if (storePaymentService.insertFsStorePayment(storePayment) > 0) {
                    if (payConfigDTO.getType().equals("wx")) {
                        //创建微信订单
                        WxPayConfig payConfig = new WxPayConfig();
                        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.pay");
                        FsPayConfig fsPayConfig = new Gson().fromJson(sysConfig.getConfigValue(), FsPayConfig.class);
                        payConfig.setAppId(appId);
                        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(wxPayProperties.getNotifyUrl());
                        wxPayService.setConfig(payConfig);
                        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
                        orderRequest.setOpenid(openId);//公众号支付提供用户openid
                        orderRequest.setBody("拍商品订单支付");
                        orderRequest.setOutTradeNo("product-" + 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("data", orderResult).put("type", "wx").put("isPay", 0);
                        } catch (WxPayException e) {
                            e.printStackTrace();
                            throw new CustomException("支付失败" + e.getMessage());
                        }
                    } else if (payConfigDTO.getType().equals("yb")) {
                        WxJspayDTO p = new WxJspayDTO();
                        // 使用setter方法为对象赋值
                        p.setPayMoney(storePayment.getPayMoney().toString());
                        p.setLowOrderId("product-" + storePayment.getPayCode());
                        p.setBody("拍商品订单支付");
                        p.setIsMinipg("1");
                        p.setOpenId(openId);
                        p.setAttach("");
                        p.setStoreid("0");
                        CreateWxOrderResult wxOrder = payService.createWxOrder(p);
                        logger.info("易宝返回"+wxOrder);
                        if (wxOrder.getStatus().equals("100")) {
                            FsStorePayment mt=new FsStorePayment();
                            mt.setPaymentId(storePayment.getPaymentId());
                            mt.setTradeNo(wxOrder.getUpOrderId());
                            fsStorePaymentMapper.updateFsStorePayment(mt);
                            return R.ok().put("isPay", 0).put("data", wxOrder).put("type", "yb");
                        } else {
                            throw new CustomException("支付失败");
                        }
                    } else if (payConfigDTO.getType().equals("tz")) {
                        PayCreateOrder o = new PayCreateOrder();
                        o.setOrderNo("product" + storePayment.getPayCode()); // 业务系统订单号
                        o.setTrxAmt(storePayment.getPayMoney().doubleValue()); // 交易金额
                        o.setBusinessCstNo(courseProductOrder.getUserId().toString()); // 业务平台客户号
                        String phone="";
                        if (user.getPhone()!=null&&user.getPhone().length()>4){
                            phone=user.getPhone().substring(user.getPhone().length()-4);
                            if (user.getPhone().length()>11){
                                o.setPayerMobileNo(PhoneUtil.decryptPhone(user.getPhone()));
                            }else {
                                o.setPayerMobileNo(user.getPhone());
                            }
                        }
                        o.setPayerName("微信用户"+phone);
                        o.setGoodsInfo("拍商品订单支付"); // 订单信息
                        o.setOpenId(openId);
                        o.setOrderType(3);
                        o.setOrderId(courseProductOrder.getCourseOrderId().toString());
                        TzBankResult<PayCreateOrderResult> result = tzBankService.createOrder(o);
                        FsStorePayment mt=new FsStorePayment();
                        mt.setPaymentId(storePayment.getPaymentId());
                        mt.setTradeNo(result.getBody().getOrderFlowNo());
                        fsStorePaymentMapper.updateFsStorePayment(mt);
                        return R.ok().put("isPay", 0).put("data", result).put("type", "tz");
                    }else if (payConfigDTO.getType().equals("hf")) {
                        logger.info("创建汇付订单");
                        HuiFuCreateOrder o = new HuiFuCreateOrder();
                        o.setTradeType("T_MINIAPP");
                        o.setOpenid(openId);
                        o.setAppId(appId);
                        o.setReqSeqId("product-"+storePayment.getPayCode());
                        o.setTransAmt(storePayment.getPayMoney().toString());
                        o.setAppId(param.getAppId());
                        o.setGoodsDesc("拍商品订单支付");
                        HuifuCreateOrderResult result = huiFuService.createOrder(o);
                        logger.info("创建汇付支付："+result);
                        FsStorePayment mt=new FsStorePayment();
                        mt.setPaymentId(storePayment.getPaymentId());
                        mt.setTradeNo(result.getHf_seq_id());
                        mt.setAppId(appId);
                        storePaymentService.updateFsStorePayment(mt);
                        return R.ok().put("isPay", 0).put("data", result).put("type", "hf");
                    }
                }
            } else {
                //TODO 支付金额为0的业务
            }

        } else {
           return R.error("用户OPENID不存在");
        }
        return R.error();
    }

    @Override
    public R payConfirm(String orderSn, String payCode, String tradeNo, String payType, Integer type,String bankTransactionId,String bankSerialNo){
        logger.info("进入拍商品订单支付回调 orderSn: {}, payCode: {}, tradeNo: {}, payType: {}, type: {}",
                orderSn, payCode, tradeNo, payType, type);
        FsCourseProductOrder order = null;
        if(type.equals(1)){
            FsStorePayment storePayment = fsStorePaymentMapper.selectFsStorePaymentByPaymentCode(payCode);
            if (storePayment!=null){
                if(storePayment.getStatus().equals(0)){
                    FsStorePayment paymentMap=new FsStorePayment();
                    paymentMap.setPaymentId(storePayment.getPaymentId());
                    paymentMap.setStatus(1);
                    paymentMap.setPayTime(new Date());
                    paymentMap.setTradeNo(tradeNo);
                    paymentMap.setBankSerialNo(bankSerialNo);
                    paymentMap.setBankTransactionId(bankTransactionId);
                    if(payType.equals(PayType.WECHAT_MINI_PROGRAM_PAYMENT.getCode())){
                        paymentMap.setPayTypeCode(PayType.WECHAT_MINI_PROGRAM_PAYMENT.name());
                    }
                    else if(payType.equals(PayType.ALIPAY_BARCODE_PAYMENT.getCode())){
                        paymentMap.setPayTypeCode(PayType.ALIPAY_BARCODE_PAYMENT.name());
                    }
                    if (storePayment.getPayMode().equals("yb")){
                        OrderQueryDTO orderQueryDTO = new OrderQueryDTO();
                        orderQueryDTO.setUpOrderId(tradeNo);
                        OrderResult orderResult = ybPayService.getOrder(orderQueryDTO);
                        paymentMap.setBankSerialNo(orderResult.getBankOrderId());
                        paymentMap.setBankTransactionId(orderResult.getBankTrxId());
                    }
                    logger.info("更新支付记录");
                    fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                    order = courseProductOrderMapper.selectFsCourseProductOrderByCourseOrderId(Long.parseLong(storePayment.getBusinessId()));
                }
            }
            else{
                logger.info("支付单号不存在:"+payCode);
                return R.error("支付单号不存在");
            }
        } else if(type.equals(2)){
            order=courseProductOrderMapper.selectFsCourseProductOrderByOrderCode(orderSn);
        }
        FsCourseProduct courseProduct = JSONUtil.toBean(order.getProductJson(), FsCourseProduct.class);

        if (!order.getStatus().equals(FsCourseProductOrderStatusEnum.STATUS_1.getValue()) && courseProduct == null){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("非法操作");
        }

        logger.info("更新拍商品订单支付状态");
        FsCourseProductOrder map = new FsCourseProductOrder();
        map.setCourseOrderId(order.getCourseOrderId());
        map.setIsPay(1L);
        map.setStatus(FsCourseProductOrderStatusEnum.STATUS_2.getValue());
        map.setPayTime(new Date());
        courseProductOrderMapper.updateFsCourseProductOrder(map);
        return R.ok();
    }

    @Transactional
    @Override
    public R refund(FsCourseProductOrderRefundParam param) {
        FsCourseProductOrder courseProductOrder = courseProductOrderMapper.selectFsCourseProductOrderByCourseOrderId(param.getCourseOrderId());
        if (courseProductOrder == null) {
            throw new CustomException("订单不存在");
        }

        if (courseProductOrder.getIsPay() != 1 || !Objects.equals(courseProductOrder.getStatus(), FsCourseProductOrderStatusEnum.STATUS_NE1.getValue())) {
            throw new CustomException("此状态的订单不可退款");
        }

        FsCourseProduct courseProduct = JSONUtil.toBean(courseProductOrder.getProductJson(), FsCourseProduct.class);
        if (courseProduct == null) {
            throw new CustomException("订单商品不存在");
        }

        //修改拍商品订单状态
        FsCourseProductOrder mapOrder = new FsCourseProductOrder();
        mapOrder.setCourseOrderId(param.getCourseOrderId());
        mapOrder.setStatus(FsCourseProductOrderStatusEnum.STATUS_NE2.getValue());
        mapOrder.setRefundTime(new Date());
        courseProductOrderMapper.updateFsCourseProductOrder(mapOrder);

        if(courseProduct.getProductPrice().compareTo(new BigDecimal(0))==1){
            List<FsStorePayment> fsStorePayments = fsStorePaymentMapper.selectFsStorePaymentByPay(6, param.getCourseOrderId());
            if (fsStorePayments != null && fsStorePayments.size() == 1) {
                FsStorePayment payment=fsStorePayments.get(0);
                if(payment.getPayMode().equals("wx")){
                    WxPayConfig payConfig = new WxPayConfig();
                    SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.pay");
                    FsPayConfig fsPayConfig = new Gson().fromJson(sysConfig.getConfigValue(), FsPayConfig.class);
                    payConfig.setAppId(fsPayConfig.getAppId());
                    payConfig.setMchId(fsPayConfig.getWxMchId());
                    payConfig.setMchKey(fsPayConfig.getWxMchKey());

                    payConfig.setKeyPath(wxPayProperties.getKeyPath());

                    payConfig.setSubAppId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                    payConfig.setSubMchId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                    wxPayService.setConfig(payConfig);
                    WxPayRefundRequest refundRequest = new WxPayRefundRequest();
                    refundRequest.setOutTradeNo("product-"+payment.getPayCode());
                    refundRequest.setOutRefundNo("product-"+payment.getPayCode());
                    refundRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(payment.getPayMoney().toString()));
                    refundRequest.setRefundFee(WxPayUnifiedOrderRequest.yuanToFen(payment.getPayMoney().toString()));
                    try {
                        WxPayRefundResult refundResult = wxPayService.refund(refundRequest);
                        WxPayRefundQueryResult refundQueryResult = wxPayService.refundQuery("", refundResult.getOutTradeNo(), refundResult.getOutRefundNo(), refundResult.getRefundId());
                        if(refundQueryResult!=null&&refundQueryResult.getResultCode().equals("SUCCESS")){
                            FsStorePayment paymentMap=new FsStorePayment();
                            paymentMap.setPaymentId(payment.getPaymentId());
                            paymentMap.setStatus(-1);
                            paymentMap.setRefundTime(DateUtils.getNowDate());
                            paymentMap.setRefundMoney(payment.getPayMoney());
                            fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                        }
                        else {
                            throw new CustomException("退款请求失败"+refundQueryResult.getReturnMsg());
                        }
                    } catch (WxPayException e) {
                        throw new CustomException("退款请求失败"+e.getReturnMsg());
                    }
                } else if(payment.getPayMode().equals("yb")){
                    //易宝
                    RefundDTO refundDTO=new RefundDTO();
                    refundDTO.setRefundMoney(payment.getPayMoney().toString());
                    refundDTO.setLowRefundNo("product-"+payment.getPayCode());
                    refundDTO.setUpOrderId(payment.getTradeNo());
                    RefundResult result=payService.refund(refundDTO);
                    if(result.getState().equals("5")){
                        FsStorePayment paymentMap=new FsStorePayment();
                        paymentMap.setPaymentId(payment.getPaymentId());
                        paymentMap.setStatus(-1);
                        paymentMap.setRefundTime(DateUtils.getNowDate());
                        paymentMap.setRefundMoney(payment.getPayMoney());
                        fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                    }
                } else if(payment.getPayMode().equals("tz")){
                    RefundParam tzBankResult = new RefundParam();
                    // 使用set方法为对象的字段赋值
                    //商户原支付订单号
                    tzBankResult.setOldPayOutOrderNo("product"+payment.getPayCode());
                    // 商户退款订单号 对接平台系统里自己生成的退款订单号
                    tzBankResult.setRefundOrderNo("product"+payment.getPayCode());
                    // 交易发送时间 yyyyMMddHHmmss
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                    tzBankResult.setTrxSendTime(sdf.format(new Date()));

                    // 退款金额
                    tzBankResult.setRefundOrdTransAmt(payment.getPayMoney().doubleValue());
                    TzBankResult<com.fs.tzBankPay.doman.RefundResult> result = tzBankService.refund(tzBankResult);
                    if(result.getBody().getRefundOrdStatus().equals("90")){
                        FsStorePayment paymentMap=new FsStorePayment();
                        paymentMap.setPaymentId(payment.getPaymentId());
                        paymentMap.setStatus(-1);
                        paymentMap.setRefundTime(DateUtils.getNowDate());
                        paymentMap.setRefundMoney(payment.getPayMoney());
                        fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                    }
                } else if (payment.getPayMode().equals("hf")){

                    V2TradePaymentScanpayRefundRequest request = new V2TradePaymentScanpayRefundRequest();
                    request.setOrdAmt(payment.getPayMoney().toString());
                    request.setOrgReqDate(new SimpleDateFormat("yyyyMMdd").format(payment.getCreateTime()));
                    request.setReqSeqId("refund-"+payment.getPayCode());
                    Map<String, Object> extendInfoMap = new HashMap<>();
                    extendInfoMap.put("org_req_seq_id", "product-"+payment.getPayCode());
                    request.setExtendInfo(extendInfoMap);
                    HuiFuRefundResult refund = huiFuService.refund(request);
                    logger.info("拍商品订单退款返回结果:问诊订单id:"+courseProductOrder.getCourseOrderId()+refund);
                    if(refund.getResp_code().equals("00000000")&&(refund.getTrans_stat().equals("S")||refund.getTrans_stat().equals("P"))){
                        FsStorePayment paymentMap=new FsStorePayment();
                        paymentMap.setPaymentId(payment.getPaymentId());
                        paymentMap.setStatus(-1);
                        paymentMap.setRefundTime(DateUtils.getNowDate());
                        paymentMap.setRefundMoney(payment.getPayMoney());
                        fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                    }
                }

            }
        }

        return R.ok();
    }

    @Override
    public R applyRefund(ApplyCourseProductOrderRefundParam param) {
        FsCourseProductOrder courseProductOrder = courseProductOrderMapper.selectFsCourseProductOrderByCourseOrderId(param.getCourseOderId());
        if (courseProductOrder == null) {
            return R.error("订单不存在");
        }
        if (!Objects.equals(courseProductOrder.getStatus(), FsCourseProductOrderStatusEnum.STATUS_2.getValue())) {
            return R.error("订单状态异常，申请退款失败");
        }
        FsCourseProductOrder map = new FsCourseProductOrder();
        map.setCourseOrderId(courseProductOrder.getCourseOrderId());
        map.setRefundExplain(param.getRefundReason());
        map.setRefundTime(new Date());
        map.setStatus(FsCourseProductOrderStatusEnum.STATUS_NE1.getValue());
        if (courseProductOrderMapper.updateFsCourseProductOrder(map) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @Override
    public List<FsCourseProductOrderVO> selectFsCourseProductOrderDecodePhoneList(FsCourseProductOrderListParam param) {
        List<FsCourseProductOrderVO> productOrderVOS = baseMapper.selectFsCourseProductOrderList(param);
        if (CollectionUtils.isNotEmpty(productOrderVOS)) {
            productOrderVOS.forEach(productOrderVO -> {
                if (StringUtils.isNotEmpty(productOrderVO.getProductJson())) {
                    FsCourseProduct courseProduct = JSONUtil.toBean(productOrderVO.getProductJson(), FsCourseProduct.class);
                    productOrderVO.setProductName(courseProduct.getProductName());
                }
            });
        }
        return productOrderVOS;
    }

    //生成核销码
    private String VerificationCodeGenerator(){
        Random random = new Random();
        StringBuilder codeBuilder = new StringBuilder(CODE_LENGTH);
        for (int i = 0; i < CODE_LENGTH; i++) {
            int index = random.nextInt(CHARACTERS.length());
            codeBuilder.append(CHARACTERS.charAt(index));
        }
        return codeBuilder.toString();
    }

}
