package com.fs.course.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.util.IdUtil;
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.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.FsCoursePlaySourceConfig;
import com.fs.course.domain.FsUserCourseOrder;
import com.fs.course.domain.FsUserVipPackage;
import com.fs.course.mapper.FsCoursePlaySourceConfigMapper;
import com.fs.course.mapper.FsUserVipPackageMapper;
import com.fs.course.param.FsUserVipOrderCreateUParam;
import com.fs.course.param.FsUserVipOrderParam;
import com.fs.course.param.FsUserVipOrderPayUParam;
import com.fs.course.vo.FsUserVipOrderListPVO;
import com.fs.his.domain.*;
import com.fs.his.dto.PayConfigDTO;
import com.fs.his.mapper.*;
import com.fs.his.service.IFsStorePaymentService;
import com.fs.hisStore.domain.FsPayConfigScrm;
import com.fs.huifuPay.domain.HuiFuCreateOrder;
import com.fs.huifuPay.domain.HuifuCreateOrderResult;
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.PayCreateOrder;
import com.fs.tzBankPay.doman.PayCreateOrderResult;
import com.fs.tzBankPay.doman.PayType;
import com.fs.tzBankPay.doman.TzBankResult;
import com.fs.ybPay.domain.CreateWxOrderResult;
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.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.google.gson.Gson;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.course.mapper.FsUserVipOrderMapper;
import com.fs.course.domain.FsUserVipOrder;
import com.fs.course.service.IFsUserVipOrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * 购买会员订单Service业务层处理
 *
 * @author fs
 * @date 2024-06-27
 */
@Service
public class FsUserVipOrderServiceImpl implements IFsUserVipOrderService
{
    Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private FsUserVipOrderMapper fsUserVipOrderMapper;
    @Autowired
    private FsUserVipPackageMapper fsUserVipPackageMapper;
    @Autowired
    private FsUserMapper userMapper;
    @Autowired
    private FsCoursePlaySourceConfigMapper fsCoursePlaySourceConfigMapper;
    @Autowired
    private MerchantAppConfigMapper merchantAppConfigMapper;

    @Autowired
    private IFsStorePaymentService storePaymentService;

    @Autowired
    private FsStorePaymentMapper fsStorePaymentMapper;

    @Autowired
    private HuiFuService huiFuService;

    @Autowired
    private FsStorePaymentErrorMapper fsStorePaymentErrorMapper;

    @Autowired
    private IPayService ybPayService;

    @Autowired
    private WxPayService wxPayService;

    private WxPayProperties wxPayProperties;
    @Autowired
    private TzBankService tzBankService;

    @Autowired
    private IPayService payService;
    @Autowired
    private FsUserWxMapper fsUserWxMapper;


    /**
     * 查询购买会员订单
     *
     * @param orderId 购买会员订单主键
     * @return 购买会员订单
     */
    @Override
    public FsUserVipOrder selectFsUserVipOrderByOrderId(Long orderId)
    {
        return fsUserVipOrderMapper.selectFsUserVipOrderByOrderId(orderId);
    }

    /**
     * 查询购买会员订单列表
     *
     * @param fsUserVipOrder 购买会员订单
     * @return 购买会员订单
     */
    @Override
    public List<FsUserVipOrder> selectFsUserVipOrderList(FsUserVipOrder fsUserVipOrder)
    {
        return fsUserVipOrderMapper.selectFsUserVipOrderList(fsUserVipOrder);
    }

    /**
     * 新增购买会员订单
     *
     * @param fsUserVipOrder 购买会员订单
     * @return 结果
     */
    @Override
    public int insertFsUserVipOrder(FsUserVipOrder fsUserVipOrder)
    {
        fsUserVipOrder.setCreateTime(DateUtils.getNowDate());
        return fsUserVipOrderMapper.insertFsUserVipOrder(fsUserVipOrder);
    }

    /**
     * 修改购买会员订单
     *
     * @param fsUserVipOrder 购买会员订单
     * @return 结果
     */
    @Override
    public int updateFsUserVipOrder(FsUserVipOrder fsUserVipOrder)
    {
        fsUserVipOrder.setUpdateTime(DateUtils.getNowDate());
        return fsUserVipOrderMapper.updateFsUserVipOrder(fsUserVipOrder);
    }

    /**
     * 批量删除购买会员订单
     *
     * @param orderIds 需要删除的购买会员订单主键
     * @return 结果
     */
    @Override
    public int deleteFsUserVipOrderByOrderIds(Long[] orderIds)
    {
        return fsUserVipOrderMapper.deleteFsUserVipOrderByOrderIds(orderIds);
    }

    /**
     * 删除购买会员订单信息
     *
     * @param orderId 购买会员订单主键
     * @return 结果
     */
    @Override
    public int deleteFsUserVipOrderByOrderId(Long orderId)
    {
        return fsUserVipOrderMapper.deleteFsUserVipOrderByOrderId(orderId);
    }

    @Override
    public List<FsUserVipOrderListPVO> selectFsUserVipOrderListPVO(FsUserVipOrderParam param) {
        return fsUserVipOrderMapper.selectFsUserVipOrderListPVO(param);
    }

    @Override
    public R createVipPurchaseOrder(FsUserVipOrderCreateUParam param) {
        LocalDate now = LocalDate.now();
        FsUserVipPackage vipPackage = fsUserVipPackageMapper.selectFsUserVipPackageByPackageId(param.getPackageId());
        if (vipPackage==null){
            return R.error("会员开通套餐不存在");
        }
        if (vipPackage.getStatus()!=1){
            return R.error("会员开通套餐已下架");
        }
        FsUserVipOrder order = new FsUserVipOrder();
        order.setOrderCode(IdUtil.getSnowflake(0, 0).nextIdStr());
        order.setUserId(param.getUserId());
        order.setPackageId(param.getPackageId());
        order.setPayType(param.getPayType());
        order.setPurchaseDate(Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        order.setPrice(vipPackage.getPrice());
        order.setPayMoney(vipPackage.getSellPrice());
        order.setStatus(0);
        order.setCreateTime(new Date());
        if (fsUserVipOrderMapper.insertFsUserVipOrder(order)>0){
            return R.ok().put("order",order);
        }
        return R.error("会员开通订单生成失败");
    }


    @Override
    public R payment(FsUserVipOrderPayUParam param) {
        FsUserVipOrder order = fsUserVipOrderMapper.selectFsUserVipOrderByOrderId(param.getOrderId());
        if (order == null) {
            return R.error("订单不存在");
        }
        if (order.getStatus()!=0){
            return R.error("非法操作");
        }
        FsUser user = userMapper.selectFsUserByUserId(param.getUserId());

        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);
//        PayConfigDTO payConfigDTO = JSONUtil.toBean(json, PayConfigDTO.class);

//        String openId = Objects.isNull(user) ? "" : user.getMaOpenId();
//        if (StringUtils.isBlank(openId)){
//            Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
//                    .eq(FsUserWx::getFsUserId, param.getUserId())
//                    .eq(FsUserWx::getAppId, payConfigDTO.getAppId());
//            FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
//            if (Objects.nonNull(fsUserWx)){
//                openId = fsUserWx.getOpenId();
//            }
//        }
        String openId = null;
        String appId = param.getAppId();
        if (StringUtils.isNotBlank(appId)) {
            //查询fs_user_wx的openId
            Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
                    .eq(FsUserWx::getFsUserId, param.getUserId())
                    .eq(FsUserWx::getAppId, appId);
            FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
            if (fsUserWx != null) {
                openId = fsUserWx.getOpenId();
            }
        } else {
            appId = merchantAppConfig.getAppId();
            openId = Objects.isNull(user) ? "" : user.getMaOpenId();
            if (StringUtils.isBlank(openId)){
                Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
                        .eq(FsUserWx::getFsUserId, param.getUserId())
                        .eq(FsUserWx::getAppId, appId);
                FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
                if (Objects.nonNull(fsUserWx)){
                    openId = fsUserWx.getOpenId();
                }
            }
        }

        if(user!=null&& StringUtils.isNotEmpty(openId)) {
            if (order.getPayMoney().compareTo(new BigDecimal(0)) == 0) {
                this.payConfirm(order.getOrderCode(), "", "", "", 2,null,null);
                return R.ok().put("isPay", 1);
            } else {
                String payCode =  OrderCodeUtils.getOrderSn();
                if(StringUtils.isEmpty(payCode)){
                    return R.error("订单生成失败，请重试");
                }
                FsStorePayment storePayment = new FsStorePayment();
                storePayment.setStatus(0);
                storePayment.setPayMode(merchantAppConfig.getMerchantType());
                storePayment.setBusinessCode(order.getOrderCode());
                storePayment.setPayCode(payCode);
                storePayment.setPayMoney(order.getPayMoney());
                storePayment.setCreateTime(new Date());
                storePayment.setPayTypeCode("weixin");
                storePayment.setBusinessType(5);
                storePayment.setRemark("会员开通订单支付");
                storePayment.setOpenId(openId);
                storePayment.setUserId(user.getUserId());
                storePayment.setBusinessId(order.getOrderId().toString());
                storePayment.setAppId(appId);
                storePayment.setMerConfigId(merchantAppConfig.getId());
                if (storePaymentService.insertFsStorePayment(storePayment) > 0) {
                    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(wxPayProperties.getNotifyUrl());
                        wxPayService.setConfig(payConfig);
                        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
                        orderRequest.setOpenid(openId);//公众号支付提供用户openid
                        orderRequest.setBody("会员开通订单支付");
                        orderRequest.setOutTradeNo("appvip-" + 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 (merchantAppConfig.getMerchantType().equals("yb")) {
                        WxJspayDTO p = new WxJspayDTO();
                        // 使用setter方法为对象赋值
                        p.setPayMoney(storePayment.getPayMoney().toString());
                        p.setLowOrderId("appvip-" + storePayment.getPayCode());
                        p.setBody("会员开通订单支付");
                        p.setIsMinipg("1");
                        p.setOpenId(openId);
                        p.setAttach("");
                        p.setStoreid("0");
                        CreateWxOrderResult wxOrder = payService.createWxOrder(p);
                        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 (merchantAppConfig.getMerchantType().equals("tz")) {
                        PayCreateOrder o = new PayCreateOrder();
                        o.setOrderNo("appvip" + storePayment.getPayCode()); // 业务系统订单号
                        o.setTrxAmt(storePayment.getPayMoney().doubleValue()); // 交易金额
                        o.setBusinessCstNo(order.getUserId().toString()); // 业务平台客户号
                        String phone = "";
                        if (user.getPhone() != null && user.getPhone().length() > 4) {
                            phone = user.getPhone().substring(user.getPhone().length() - 4);
                        }
                        o.setPayerName("微信用户" + phone);
                        o.setGoodsInfo("会员开通订单支付"); // 订单信息
                        o.setOpenId(openId);
                        o.setOrderType(5);
                        o.setOrderId(order.getOrderId().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 (merchantAppConfig.getMerchantType().equals("hf")) {
                        HuiFuCreateOrder o = new HuiFuCreateOrder();
                        o.setTradeType("T_MINIAPP");
                        o.setOpenid(openId);
                        o.setAppId(appId);
                        o.setReqSeqId("appvip-" + storePayment.getPayCode());
                        o.setTransAmt(storePayment.getPayMoney().toString());
                        o.setGoodsDesc("会员开通订单支付");
                        o.setAppId(param.getAppId());
                        HuifuCreateOrderResult result = huiFuService.createOrder(o);
                        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 {
            return R.error("用户OPENID不存在");
        }
        return R.error();
    }

    @Override
    public R aliPayment(FsUserVipOrderPayUParam param) {
        FsUserVipOrder order = fsUserVipOrderMapper.selectFsUserVipOrderByOrderId(param.getOrderId());
        if (order == null) {
            return R.error("订单不存在");
        }
        if (order.getStatus()!=0){
            return R.error("非法操作");
        }
        FsUser user = userMapper.selectFsUserByUserId(param.getUserId());

        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());
//        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, param.getUserId())
                    .eq(FsUserWx::getAppId, appId);
            FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
            if (fsUserWx != null) {
                openId = fsUserWx.getOpenId();
            }
        } else {
            appId = merchantAppConfig.getAppId();
            openId = Objects.isNull(user) ? "" : user.getMaOpenId();
            if (StringUtils.isBlank(openId)){
                Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
                        .eq(FsUserWx::getFsUserId, param.getUserId())
                        .eq(FsUserWx::getAppId, appId);
                FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
                if (Objects.nonNull(fsUserWx)){
                    openId = fsUserWx.getOpenId();
                }
            }
        }

        if(user!=null){
            if(order.getPayMoney().compareTo(new BigDecimal(0))==1){
                String payCode =  OrderCodeUtils.getOrderSn();
                if(StringUtils.isEmpty(payCode)){
                    return R.error("订单生成失败，请重试");
                }
//                String json = configService.selectConfigByKey("his.pay");
//                PayConfigDTO payConfigDTO = JSONUtil.toBean(json, PayConfigDTO.class);
                FsStorePayment storePayment=new FsStorePayment();
                storePayment.setStatus(0);
                storePayment.setPayMode(merchantAppConfig.getMerchantType());
                storePayment.setBusinessCode(order.getOrderCode());
                storePayment.setPayCode(payCode);
                storePayment.setPayMoney(order.getPayMoney());
                storePayment.setCreateTime(new Date());
                storePayment.setPayTypeCode("alipay");
                storePayment.setBusinessType(5);
                storePayment.setRemark("会员开通订单支付");
//                storePayment.setOpenId(user.getMpOpenId());
                storePayment.setUserId(user.getUserId());
                storePayment.setBusinessId(order.getOrderId().toString());
                storePayment.setAppId(appId);
                storePayment.setMerConfigId(merchantAppConfig.getId());
                if(storePaymentService.insertFsStorePayment(storePayment)>0){

                    if (merchantAppConfig.getMerchantType().equals("yb")) {
                        return R.error("支付暂不可用!");
                    } else if (merchantAppConfig.getMerchantType().equals("tz")) {
                        PayCreateOrder o = new PayCreateOrder();
                        o.setOrderNo("appvip" + storePayment.getPayCode()); // 业务系统订单号
                        o.setTrxAmt(storePayment.getPayMoney().doubleValue()); // 交易金额
                        o.setBusinessCstNo(order.getUserId().toString()); // 业务平台客户号
                        String phone="";
                        if (user.getPhone()!=null&&user.getPhone().length()>4){
                            phone=user.getPhone().substring(user.getPhone().length()-4);
                        }
                        o.setPayerName("微信用户"+phone);
                        o.setGoodsInfo("会员开通订单支付"); // 订单信息
//                        o.setOpenId(user.getMpOpenId());
                        o.setOrderType(5);
                        o.setOrderId(order.getOrderId().toString());
                        o.setPayType(Arrays.asList(PayType.ALIPAY_BARCODE_PAYMENT.getCode()));
                        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 (merchantAppConfig.getMerchantType().equals("hf")) {
                        HuiFuCreateOrder o = new HuiFuCreateOrder();
                        o.setTradeType("A_NATIVE");
//                        o.setOpenid(user.getMaOpenId());
                        o.setAppId(appId);
                        o.setReqSeqId("appvip-"+storePayment.getPayCode());
                        o.setTransAmt(storePayment.getPayMoney().toString());
                        o.setGoodsDesc("会员开通订单支付");
                        HuifuCreateOrderResult result = huiFuService.createOrder(o);
                        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{
                this.payConfirm(order.getOrderCode(),"","","",2,null,null);
                return R.ok().put("isPay",1);
            }
        }
        else{
            return R.error("用户不存在");
        }
        return R.error();
    }

    @Override
    @Transactional
    public R payConfirm(String orderSn, String payCode, String tradeNo, String payType, Integer type,String bankTransactionId,String bankSerialNo){
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            FsUserVipOrder 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());
                        }
                        fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                        order=fsUserVipOrderMapper.selectFsUserVipOrderByOrderId(Long.parseLong(storePayment.getBusinessId()));
                    }
                }
                else{
                    logger.info("支付单号不存在:"+payCode);
                    return R.error("支付单号不存在");
                }
            }
            else if(type.equals(2)){
                order=fsUserVipOrderMapper.selectFsUserVipOrderByOrderCode(orderSn);
            }
            if(order.getStatus()!=0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error("非法操作");
            }
            return handleVipPurchaseCallback(order.getUserId(),order.getPackageId(), order.getOrderId());
        }catch (Exception e){
            logger.info("支付错误:"+e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            FsStorePaymentError err = new FsStorePaymentError();
            err.setOrderNo(orderSn);
            err.setOrderFlowNo(tradeNo);
            err.setStatus(0);
            err.setMsg(e.getMessage());
            err.setCreateTime(DateUtils.getNowDate());
            fsStorePaymentErrorMapper.insertFsStorePaymentError(err);
            return R.error();
        }
    }

    @Override
    public R updateUserVipInfo(Long userId,Long orderId) {
        FsUserVipOrder order = fsUserVipOrderMapper.selectFsUserVipOrderByOrderId(orderId);
        if (order==null){
            return R.error("更新会员信息失败，订单不存在");
        }
        if (order.getStatus()==0){
            return R.error("会员开通订单未支付");
        }
//        LocalDate now = LocalDate.now();
        FsUser user = userMapper.selectFsUserByUserId(userId);
        user.setIsVip(1);
        user.setVipStartDate(order.getPurchaseDate());
        if (order.getExpireDate()!=null){
            user.setVipEndDate(order.getExpireDate());
        }
        user.setVipStatus(1); // 正常状态
        userMapper.updateFsUser(user);
        return R.ok();
    }

    public LocalDate calculateExpireDate(LocalDate startDate, int months) {
        return startDate.plusMonths(months).minusDays(1);
    }

    public R handleVipPurchaseCallback(Long userId, Long packageId,Long orderId) {
        LocalDate now = LocalDate.now();
        FsUserVipPackage vipPackage = fsUserVipPackageMapper.selectFsUserVipPackageByPackageId(packageId);
        FsUser user = userMapper.selectFsUserByUserId(userId);

        LocalDate expireDate;
        if (user.getIsVip() == 1 && user.getVipEndDate() != null) {
            // 用户当前是VIP，续费
            LocalDate currentExpireDate = user.getVipEndDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            expireDate = calculateExpireDate(currentExpireDate.plusDays(1), vipPackage.getMonths());
        } else {
            // 用户当前不是VIP，购买新VIP
            expireDate = calculateExpireDate(now, vipPackage.getMonths());
            user.setIsVip(1);
            user.setVipStartDate(Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        }
        user.setVipEndDate(Date.from(expireDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
//        user.setVipLevel(vipPackage.getLevel());
        user.setVipStatus(1); // 正常状态
        userMapper.updateFsUser(user);

        // 更新VIP购买订单状态为已支付
        FsUserVipOrder order = fsUserVipOrderMapper.selectFsUserVipOrderByOrderId(orderId);
        order.setStatus(1);
        order.setPayTime(new Date());
        fsUserVipOrderMapper.updateFsUserVipOrder(order);
        return R.ok();
    }
}
