package com.fs.his.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fs.common.constant.FsConstants;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.CustomException;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.*;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyDept;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.company.service.ICompanyDeptService;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.config.cloud.CloudHostProper;
import com.fs.core.utils.OrderCodeUtils;
import com.fs.erp.domain.ErpOrder;
import com.fs.erp.domain.ErpOrderItem;
import com.fs.erp.domain.ErpOrderPayment;
import com.fs.erp.dto.ErpOrderResponse;
import com.fs.erp.service.IErpOrderService;
import com.fs.his.config.FsSysConfig;
import com.fs.his.domain.*;
import com.fs.his.dto.ErpRemarkDTO;
import com.fs.his.enums.*;
import com.fs.his.mapper.*;
import com.fs.his.param.*;
import com.fs.his.service.*;
import com.fs.his.utils.ConfigUtil;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.utils.RedisCacheUtil;
import com.fs.his.vo.*;
import com.fs.qw.domain.QwUser;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.tzBankPay.doman.PayType;
import com.fs.ybPay.domain.OrderResult;
import com.fs.ybPay.dto.OrderQueryDTO;
import com.fs.ybPay.service.IPayService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.redisson.api.RObjectAsync;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.fs.his.utils.PhoneUtil.*;

/**
 * 积分商品订单Service业务层处理
 *
 * @author fs
 * @date 2023-11-02
 */
@Slf4j
@Service
public class FsIntegralOrderServiceImpl implements IFsIntegralOrderService
{
    @Autowired
    private FsIntegralOrderMapper fsIntegralOrderMapper;

    @Autowired
    private FsUserAddressMapper fsUserAddressMapper;

    @Autowired
    private FsUserMapper fsUserMapper;

    @Autowired
    private FsIntegralGoodsMapper fsIntegralGoodsMapper;
    @Autowired
    private FsUserIntegralLogsMapper fsUserIntegralLogsMapper;

    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private CompanyUserMapper companyUserMapper;
    @Autowired
    private IFsUserIntegralLogsService userIntegralLogsService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IPayService ybPayService;
    @Autowired
    private IFsStorePaymentService storePaymentService;
    @Autowired
    private IFsIntegralCartService cartService;

    @Autowired
    @Qualifier("erpOrderServiceImpl")
    private IErpOrderService gyOrderService;

    @Autowired
    @Qualifier("wdtErpOrderServiceImpl")
    private IErpOrderService wdtOrderService;

    @Autowired
    @Qualifier("hzOMSErpOrderServiceImpl")
    private IErpOrderService hzOMSOrderService;

    @Autowired
    @Qualifier("dfOrderServiceImpl")
    private IErpOrderService dfOrderService;

    @Autowired
    @Qualifier("JSTErpOrderServiceImpl")
    private IErpOrderService jSTOrderService;
    @Autowired
    @Qualifier("k9OrderScrmServiceImpl")
    private IErpOrderService k9OrderService;
    @Autowired
    private FsIntegralOrderDfMapper fsIntegralOrderDfMapper;

    @Autowired
    private ConfigUtil configUtil;

    @Autowired
    private CloudHostProper cloudHostProper;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private ICompanyUserService companyUserService;

    @Autowired
    private ICompanyDeptService companyDeptService;

    @Autowired
    private IFsExpressService expressService;

    @Autowired
    private IFsIntegralOrderDfService integralOrderDfService;

    @Autowired
    private IFsUserAddressService fsUserAddressService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;
    /**
     * 查询积分商品订单
     *
     * @param orderId 积分商品订单主键
     * @return 积分商品订单
     */
    @Override
    public FsIntegralOrder selectFsIntegralOrderByOrderId(Long orderId)
    {
        return fsIntegralOrderMapper.selectFsIntegralOrderByOrderId(orderId);
    }

    /**
     * 查询积分商品订单列表
     *
     * @param fsIntegralOrder 积分商品订单
     * @return 积分商品订单
     */
    @Override
    public List<FsIntegralOrder> selectFsIntegralOrderList(FsIntegralOrder fsIntegralOrder)
    {
        return fsIntegralOrderMapper.selectFsIntegralOrderList(fsIntegralOrder);
    }

    /**
     * 新增积分商品订单
     *
     * @param fsIntegralOrder 积分商品订单
     * @return 结果
     */
    @Override
    public int insertFsIntegralOrder(FsIntegralOrder fsIntegralOrder)
    {
        fsIntegralOrder.setCreateTime(DateUtils.getNowDate());
        return fsIntegralOrderMapper.insertFsIntegralOrder(fsIntegralOrder);
    }

    /**
     * 修改积分商品订单
     *
     * @param fsIntegralOrder 积分商品订单
     * @return 结果
     */
    @Override
    public int updateFsIntegralOrder(FsIntegralOrder fsIntegralOrder)
    {
        FsIntegralOrder order = fsIntegralOrderMapper.selectById(fsIntegralOrder.getOrderId());
        //当前状态
        Integer status = order.getStatus();
        Integer newStatus = fsIntegralOrder.getStatus();
        if (!status.equals(newStatus) && status.equals(2)){
            throw new CustomException("积分订单无法修改为待支付状态");
        }
        if (!status.equals(newStatus) && newStatus.equals(2)&&StrUtil.isBlank(fsIntegralOrder.getDeliverySn())) {
            throw new CustomException("修改为待发货时，请填写物流单号");
        }
        //其他逻辑，目前暂定这个
        return fsIntegralOrderMapper.updateFsIntegralOrder(fsIntegralOrder);
    }

    /**
     * 批量删除积分商品订单
     *
     * @param orderIds 需要删除的积分商品订单主键
     * @return 结果
     */
    @Override
    public int deleteFsIntegralOrderByOrderIds(Long[] orderIds)
    {
        return fsIntegralOrderMapper.deleteFsIntegralOrderByOrderIds(orderIds);
    }

    /**
     * 删除积分商品订单信息
     *
     * @param orderId 积分商品订单主键
     * @return 结果
     */
    @Override
    public int deleteFsIntegralOrderByOrderId(Long orderId)
    {
        return fsIntegralOrderMapper.deleteFsIntegralOrderByOrderId(orderId);
    }

    @Override
    public List<FsIntegralOrderListVO> selectFsIntegralOrderListVO(FsIntegralOrderParam fsIntegralOrder) {
        return fsIntegralOrderMapper.selectFsIntegralOrderListVO(fsIntegralOrder);
    }

    @Override
    public List<FsIntegralOrderListVO> selectFsIntegralOrderListByJn(FsIntegralOrderParam fsIntegralOrder) {
        return fsIntegralOrderMapper.selectFsIntegralOrderListJn(fsIntegralOrder);
    }

    @Override
    public int sendGoods(FsIntegralOrder fsIntegralOrder) {

        FsIntegralOrder order = fsIntegralOrderMapper.selectFsIntegralOrderByOrderId(fsIntegralOrder.getOrderId());

        if (order==null){
            throw new CustomException("订单不存在");
        }
        if (order.getStatus()!=1L){
            throw new CustomException("非法更改");
        }
        FsIntegralOrder o1 = new FsIntegralOrder();
        o1.setOrderId(fsIntegralOrder.getOrderId());
        o1.setStatus(2);
        o1.setUpdateTime(new DateTime());
        o1.setDeliveryCode(fsIntegralOrder.getDeliveryCode());
        o1.setDeliveryName(fsIntegralOrder.getDeliveryName());
        o1.setDeliverySn(fsIntegralOrder.getDeliverySn());
        o1.setDeliveryTime(DateUtils.getNowDate());
        //增加字段，表示代服物流的账号，后续会使用该账号信息来查询物流。
        o1.setLoginAccount(fsIntegralOrder.getLoginAccount());
        return fsIntegralOrderMapper.updateFsIntegralOrder(o1);
    }

    @Override
    public List<FsIntegralOrderListUVO> selectFsIntegralOrderListUVO(FsIntegralOrderListUParam param) {
        return fsIntegralOrderMapper.selectFsIntegralOrderListUVO(param);
    }

    @Override
    @Transactional
    public R createOrder(FsIntegralOrderCreateParam param) {

        FsUser user=fsUserMapper.selectFsUserByUserId(param.getUserId());
        FsUserAddress address=fsUserAddressMapper.selectFsUserAddressByAddressId(param.getAddressId());
        FsIntegralGoods integralGoods=fsIntegralGoodsMapper.selectFsIntegralGoodsByGoodsId(param.getGoodsId());

        if (Objects.isNull(user)) {
            return R.error("用户不存在");
        }
        if (Objects.isNull(address)) {
            return R.error("地址不存在");
        }
        if (Objects.isNull(integralGoods)) {
            return R.error("商品不存在");
        }
        if(integralGoods.getStock()<=0L){
            return R.error("库存不足");
        }
        if(user.getIntegral()<integralGoods.getIntegral()){
            return R.error("积分不足");
        }
        if (integralGoods.getStatus() == 0) {
            return R.error("商品已经停售，请联系客户进行处理！");
        }

        // 减库存
        if (fsIntegralGoodsMapper.subStock(integralGoods.getGoodsId(), 1) <= 0) {
            throw new CustomException("库存不足");
        }

        // 清除商品缓存
        redisCacheUtil.delSpringCacheKey("getIntegralGoodsById", integralGoods.getGoodsId());
        redisCacheUtil.delRedisKey("getIntegralGoodsList");

        integralGoods.setNum(1);
        List<FsIntegralGoods> goodsItem = new ArrayList<>();
        goodsItem.add(integralGoods);

        // 创建订单
        return createOrder(user, address, integralGoods.getIntegral(),integralGoods.getCash(), goodsItem,param.getCompanyUserId());
    }

    /**
     * 创建订单
     */
    private R createOrder(FsUser user, FsUserAddress address, Long totalIntegral, BigDecimal totalCash, List<FsIntegralGoods> goodsItem, Long companyUserId) {
        FsIntegralOrder order = new FsIntegralOrder();
        String orderSn = null;
        try{
            orderSn = OrderCodeUtils.getOrderSn();
        }catch (Exception e){
            orderSn = IdUtil.getSnowflake(0, 0).nextIdStr();
        }
        if(StringUtils.isEmpty(orderSn)){
            throw new CustomException("订单生成失败，请重试");
        }

        // 现金
        if (totalCash.compareTo(BigDecimal.ZERO) > 0) {
            // 现金+积分
            order.setPayType(totalIntegral > 0 ? 3 : 2);
            order.setStatus(4);
            order.setIsPay(0);
            order.setPayMoney(totalCash);
        }
        // 积分
        else {
            order.setPayType(1);
            order.setStatus(1);
            order.setIsPay(1);
            order.setPayTime(LocalDateTime.now());
        }

        order.setOrderCode(orderSn);
        order.setUserId(user.getUserId());
        order.setBarCode(goodsItem.get(0).getBarCode());
        order.setIntegral(totalIntegral.toString());
        order.setItemJson(JSONUtil.toJsonStr(goodsItem));
        order.setUserName(address.getRealName());
        order.setUserAddress(address.getProvince()+" "+address.getCity()+" "+address.getDistrict()+" "+address.getDetail());
        order.setUserPhone(address.getPhone());
        order.setCreateTime(new Date());
        order.setCompanyUserId(companyUserId);
        CompanyUser companyUser = companyUserMapper.selectCompanyUserByCompanyUserId(companyUserId);
        if (ObjectUtil.isNotEmpty(companyUser)){
            order.setCompanyId(companyUser.getCompanyId());
        }

        //判断当前用户是否有关联企微ID
        if(ObjectUtil.isNotNull(user.getQwUserId())){
            //获取企微信息
            QwUser qwUser=qwUserMapper.selectOne(new LambdaQueryWrapper<QwUser>().select(QwUser::getId,QwUser::getCompanyId,QwUser::getCompanyUserId).eq(QwUser::getId,user.getQwUserId()));
            if(ObjectUtil.isNotNull(qwUser)){
                //写入企业微信ID、销售ID、公司id
                order.setQwUserId(qwUser.getId());
                order.setCompanyId(ObjectUtil.isNotNull(qwUser.getCompanyId())?qwUser.getCompanyId():null);
                order.setCompanyUserId(ObjectUtil.isNotNull(qwUser.getCompanyUserId())?qwUser.getCompanyUserId():null);
            }
        }

        if(fsIntegralOrderMapper.insertFsIntegralOrder(order)>0){
            if (order.getPayType() != 2) {
                // 验证积分是否足够，防止出现负数
                long remainingIntegral = user.getIntegral() - totalIntegral;
                if (remainingIntegral < 0) {
                    throw new CustomException("积分不足，无法创建订单");
                }

                //写入日志
                FsUser userMap=new FsUser();
                userMap.setUserId(user.getUserId());
                userMap.setIntegral(remainingIntegral);
                fsUserMapper.updateFsUser(userMap);
                FsUserIntegralLogs logs = new FsUserIntegralLogs();
                logs.setIntegral(-totalIntegral);
                logs.setUserId(order.getUserId());
                logs.setBalance(remainingIntegral);
                logs.setLogType(5);
                logs.setBusinessId(order.getOrderId().toString());
                logs.setCreateTime(new Date());
                fsUserIntegralLogsMapper.insertFsUserIntegralLogs(logs);
            }

            // 积分支付
            if (order.getPayType() == 1) {
                // 首次完成积分商城下单
                FsUserAddIntegralTemplateParam integralParam = new FsUserAddIntegralTemplateParam();
                integralParam.setUserId(order.getUserId());
                integralParam.setLogType(FsUserIntegralLogTypeEnum.TYPE_22.getValue());
                integralParam.setBusinessId(order.getOrderId().toString());
                userIntegralLogsService.addIntegralTemplate(integralParam);

                return R.ok("兑换成功").put("order",order).put("isPay", 1);
            }
            // 现金 或 积分+现金
            else {
                String redisKey = String.valueOf(StrUtil.format("{}{}", FsConstants.REDIS_INTEGRAL_ORDER_UNPAY, order.getOrderId()));
                redisCache.setCacheObject(redisKey,order.getOrderId(),30, TimeUnit.MINUTES);
                return R.ok().put("order",order).put("isPay", 0);
            }
        }
        else{
            throw new CustomException("订单创建失败");
        }
    }

    /**
     * 创建购物车订单
     * @param param 参数
     * @return  R
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R createCartOrder(FsIntegralCartOrderCreateParam param) {
        FsUser user=fsUserMapper.selectFsUserByUserId(param.getUserId());
        FsUserAddress address=fsUserAddressMapper.selectFsUserAddressByAddressId(param.getAddressId());

        if (Objects.isNull(user)) {
            throw new CustomException("用户不存在");
        }
        if (Objects.isNull(address)) {
            throw new CustomException("地址不存在");
        }

        Wrapper<FsIntegralCart> wrapper = Wrappers.<FsIntegralCart>lambdaQuery()
                .eq(FsIntegralCart::getUserId, user.getUserId())
                .in(FsIntegralCart::getId, param.getIds());
        List<FsIntegralCart> carts = cartService.list(wrapper);
        if (carts.isEmpty()) {
            throw new CustomException("请选择商品");
        }

        long totalIntegral = 0L;
        BigDecimal totalCash = BigDecimal.ZERO;
        List<FsIntegralGoods> goodsItem = new ArrayList<>();
        for (FsIntegralCart cart : carts) {
            FsIntegralGoods integralGoods = fsIntegralGoodsMapper.selectFsIntegralGoodsByGoodsId(cart.getGoodsId());
            if (Objects.isNull(integralGoods)) {
                throw new CustomException("商品不存在");
            }
            if(integralGoods.getStock() < cart.getCartNum()){
                throw new CustomException("库存不足");
            }
            if (integralGoods.getStatus() == 0) {
                return R.error(integralGoods.getGoodsName() + "商品已经停售，请联系客户进行处理！");
            }

            // 减库存
            if (fsIntegralGoodsMapper.subStock(integralGoods.getGoodsId(), cart.getCartNum()) <= 0) {
                throw new CustomException("库存不足");
            }

            // 清除商品缓存
            redisCacheUtil.delSpringCacheKey("getIntegralGoodsById", integralGoods.getGoodsId());

            totalIntegral += integralGoods.getIntegral() * cart.getCartNum();
            totalCash = totalCash.add(integralGoods.getCash().multiply(BigDecimal.valueOf(cart.getCartNum())));

            integralGoods.setNum(cart.getCartNum());
            goodsItem.add(integralGoods);
        }

        // 清除商品列表缓存
        redisCacheUtil.delRedisKey("getIntegralGoodsList");

        // 创建订单
        R result = createOrder(user, address, totalIntegral, totalCash, goodsItem, null);

        // 订单创建成功后，删除购物车中已下单的商品
        if (result.get("code").equals(200)) {
            cartService.delCartByIds(user.getUserId(), param.getIds());
        }
        return result;
    }

    @Override
    public String importProductDeliver(List<FsStoreProductDeliverExcelVO> list) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入商品数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (FsStoreProductDeliverExcelVO vo : list)
        {
            try
            {
                FsIntegralOrder o = fsIntegralOrderMapper.selectFsIntegralOrderByOrderCode(vo.getOrderCode());
                if (o==null){
                throw new CustomException("没有此订单");
                }
//                if (StrUtil.isBlank(o.getLoginAccount())&&CloudHostUtils.hasCloudHostName("金牛明医")) {
//                    throw new CustomException("订单未分拣");
//                }
                if (o.getStatus()!=1){
                    throw new CustomException("订单状态不为待发货");
                }
                // 判断每个字段是否为null或为空字符串
                if (vo.getOrderCode() == null || vo.getOrderCode().isEmpty()) {
                    throw new CustomException("订单编号为空");
                }

                if (vo.getDeliveryName() == null || vo.getDeliveryName().isEmpty()) {
                    throw new CustomException("快递名称为空");
                }

                if (vo.getDeliverySn() == null || vo.getDeliverySn().isEmpty()) {
                    throw new CustomException("快递单号为空");
                }
                FsIntegralOrder order = new FsIntegralOrder();
                order.setOrderId(o.getOrderId());
                order.setDeliverySn(vo.getDeliverySn());
                order.setDeliveryName(vo.getDeliveryName());
                order.setDeliveryTime(DateUtils.getNowDate());
                order.setDeliveryCode(vo.getDeliveryCode());

                order.setOrderCode(vo.getOrderCode());
                order.setStatus(2);

                int i = fsIntegralOrderMapper.updateFsIntegralOrder(order);
                FsIntegralOrderDf df = new FsIntegralOrderDf();//和创建erp的按钮接口数据操作保持一致，修改df记录，订单状态修改为待收货。
                df.setOrderId(order.getOrderId());
                df.setIsPush(1);
                df.setStatus(1);
                fsIntegralOrderDfMapper.updateById(df);//有就更新，没有也不影响。目前金牛在使用代服表。
                successNum++;
                successMsg.append("<br/>" + successNum + "、订单编号 " + vo.getOrderCode() + " 导入成功");

            }
            catch (Exception e)
            {

                failureNum++;
                String msg = "<br/>" + failureNum + "、订单编号 " + vo.getOrderCode()  + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public FsIntegralOrderPVO selectFsIntegralOrderPVO(Long orderId) {
        return fsIntegralOrderMapper.selectFsIntegralOrderPVO(orderId);
    }

    /**
     * 取消订单
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R cannelOrder(Long orderId) {
        // 取消订单
        FsIntegralOrder order = fsIntegralOrderMapper.selectFsIntegralOrderByOrderId(orderId);
        // 允许取消待支付(4)和待发货(1)的订单
        if (!order.getStatus().equals(4) && !order.getStatus().equals(1)){
            return R.error("非法操作，只能取消待支付或待发货的订单");
        }

        order.setStatus(5);
        fsIntegralOrderMapper.updateFsIntegralOrder(order);

        // 还原库存
        if (order.getItemJson().startsWith("[") && order.getItemJson().endsWith("]")){
            List<FsIntegralGoods> goodsItem = JSONUtil.toBean(order.getItemJson(), new TypeReference<List<FsIntegralGoods>>(){}, true);
            goodsItem.forEach(goods -> {
                fsIntegralGoodsMapper.addStock(goods.getGoodsId(), Objects.isNull(goods.getNum()) ? 1 : goods.getNum());
                // 清除商品缓存
                redisCacheUtil.delSpringCacheKey("getIntegralGoodsById", goods.getGoodsId());
            });
        } else {
            FsIntegralGoods integralGoods = JSONUtil.toBean(order.getItemJson(), FsIntegralGoods.class);
            fsIntegralGoodsMapper.addStock(integralGoods.getGoodsId(), Objects.isNull(integralGoods.getNum()) ? 1 : integralGoods.getNum());
            // 清除商品缓存
            redisCacheUtil.delSpringCacheKey("getIntegralGoodsById", integralGoods.getGoodsId());
        }
        // 清除商品列表缓存
        redisCacheUtil.delRedisKey("getIntegralGoodsList");

        // 还原积分（只有当订单消耗了积分时才退还）
        if (StringUtils.isNotEmpty(order.getIntegral()) && Long.parseLong(order.getIntegral()) > 0) {
            FsUser user=fsUserMapper.selectFsUserByUserId(order.getUserId());
            FsUser userMap=new FsUser();
            userMap.setUserId(user.getUserId());
            userMap.setIntegral(user.getIntegral() + Long.parseLong(order.getIntegral()));
            fsUserMapper.updateFsUser(userMap);
            FsUserIntegralLogs logs = new FsUserIntegralLogs();
            logs.setIntegral(Long.parseLong(order.getIntegral()));
            logs.setUserId(order.getUserId());
            logs.setBalance(userMap.getIntegral());
            logs.setLogType(5);
            logs.setBusinessId(order.getOrderId().toString());
            logs.setCreateTime(new Date());
            fsUserIntegralLogsMapper.insertFsUserIntegralLogs(logs);
        }

        return R.ok();
    }

    /**
     * 预支付
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R payment(FsIntegralOrderDoPayParam param, PaymentMethodEnum paymentMethod) {
        FsIntegralOrder order = fsIntegralOrderMapper.selectFsIntegralOrderByOrderId(param.getOrderId());
        if (Objects.isNull(order) || !order.getStatus().equals(4)
                || order.getPayMoney().compareTo(BigDecimal.ZERO) <= 0){
            return R.error("非法操作");
        }

        PayOrderParam payOrderParam = buildPayOrderParam(paymentMethod, order);
        return storePaymentService.processPayment(payOrderParam);
    }

    /**
     * 构建参数
     */
    private static PayOrderParam buildPayOrderParam(PaymentMethodEnum paymentMethod, FsIntegralOrder order) {
        PayOrderParam payOrderParam = new PayOrderParam();
        payOrderParam.setOrderId(order.getOrderId());
        payOrderParam.setOrderCode(order.getOrderCode());
        payOrderParam.setAmount(order.getPayMoney());
        payOrderParam.setUserId(order.getUserId());
        payOrderParam.setCompanyId(order.getCompanyId());
        payOrderParam.setCompanyUserId(order.getCompanyUserId());
        payOrderParam.setPaymentMethod(paymentMethod);
        payOrderParam.setBusinessType(BusinessTypeEnum.INTEGRAL_ORDER);
        return payOrderParam;
    }

    /**
     * 支付回调
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R payConfirm(String orderSn, String payCode, String tradeNo, String payType, int type,String bankTransactionId,String bankSerialNo){
        log.info("进入积分商城订单支付回调 orderSn: {}, payCode: {}, tradeNo: {}, payType: {}, type: {}",
                orderSn, payCode, tradeNo, payType, type);
        FsIntegralOrder order = null;
        if (type == 1) {
            FsStorePayment storePayment = storePaymentService.selectFsStorePaymentByPaymentCode(payCode);
            if (Objects.isNull(storePayment)) {
                log.info("支付单号不存在 payCode: {}", payCode);
                return R.error("支付单号不存在");
            }

            if(storePayment.getStatus() == 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());
                }
                log.info("更新支付记录");
                storePaymentService.updateFsStorePayment(paymentMap);
                order = fsIntegralOrderMapper.selectFsIntegralOrderByOrderId(Long.parseLong(storePayment.getBusinessId()));
            }
        }
        else if (type == 2) {
            order = fsIntegralOrderMapper.selectFsIntegralOrderByOrderCode(orderSn);
        }

        if (Objects.isNull(order) || order.getStatus() != 4) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("非法操作");
        }

        // 首次完成积分商城下单
        FsUserAddIntegralTemplateParam integralParam = new FsUserAddIntegralTemplateParam();
        integralParam.setUserId(order.getUserId());
        integralParam.setLogType(FsUserIntegralLogTypeEnum.TYPE_22.getValue());
        integralParam.setBusinessId(order.getOrderId().toString());
        userIntegralLogsService.addIntegralTemplate(integralParam);

        clearCartAfterPayment(order);

        order.setIsPay(1);
        order.setStatus(1);
        order.setPayTime(LocalDateTime.now());
        fsIntegralOrderMapper.updateFsIntegralOrder(order);
        return R.ok();
    }

    /**
     * 支付成功后清空购物车
     * @param order 订单信息
     */
    private void clearCartAfterPayment(FsIntegralOrder order) {
        try {
            if (StringUtils.isEmpty(order.getItemJson())) {
                return;
            }

            List<Long> goodsIds = new ArrayList<>();

            // 解析订单商品信息,获取商品ID列表
            if (order.getItemJson().startsWith("[") && order.getItemJson().endsWith("]")) {
                // 多个商品
                List<FsIntegralGoods> goodsItem = JSONUtil.toBean(order.getItemJson(), new TypeReference<List<FsIntegralGoods>>(){}, true);
                for (FsIntegralGoods goods : goodsItem) {
                    if (goods.getGoodsId() != null) {
                        goodsIds.add(goods.getGoodsId());
                    }
                }
            } else if (order.getItemJson().startsWith("{") && order.getItemJson().endsWith("}")) {
                // 单个商品
                FsIntegralGoods goods = JSONUtil.toBean(order.getItemJson(), FsIntegralGoods.class);
                if (goods.getGoodsId() != null) {
                    goodsIds.add(goods.getGoodsId());
                }
            }

            // 删除购物车中对应商品
            if (!goodsIds.isEmpty()) {
                Wrapper<FsIntegralCart> wrapper = Wrappers.<FsIntegralCart>lambdaQuery()
                        .eq(FsIntegralCart::getUserId, order.getUserId())
                        .in(FsIntegralCart::getGoodsId, goodsIds);
                cartService.remove(wrapper);
                log.info("支付成功后清空购物车,userId: {}, goodsIds: {}", order.getUserId(), goodsIds);
            }
        } catch (Exception e) {
            log.error("清空购物车失败,orderId: {}, error: {}", order.getOrderId(), e.getMessage(), e);
        }
    }

    @Override
    public AjaxResult export(FsIntegralOrder fsIntegralOrder) {
        List<FsIntegralOrder> list = fsIntegralOrderMapper.selectFsIntegralOrderList(fsIntegralOrder);

        // 使用Set避免重复数据
        Set<FsIntegralOrder> fsIntegralOrderSet = new LinkedHashSet<>();

        for (FsIntegralOrder order : list) {
            // 处理手机号脱敏
            processPhoneNumber(order);

            // 处理商品信息
            processGoodsInfo(order, fsIntegralOrderSet);
        }

        ExcelUtil<FsIntegralOrder> util = new ExcelUtil<>(FsIntegralOrder.class);
        return util.exportExcel(new ArrayList<>(fsIntegralOrderSet), "积分商品订单数据");
    }

    @Override
    @Transactional
    public int cancelOrder(String orderCode) {
        //查询订单是否存在且是否未发货
        FsIntegralOrder fsIntegralOrder = fsIntegralOrderMapper.selectFsIntegralOrderByOrderCode(orderCode);
        if (null==fsIntegralOrder){
            throw new ServiceException("订单不存在");
        }
        if (fsIntegralOrder.getStatus()!=1){
            throw new ServiceException("订单已发货或已完成");
        }
        int i = 0;
        //修改订单状态
        i = fsIntegralOrderMapper.cancelOrder(fsIntegralOrder.getOrderId());
        if (i>0){
            //原路退回积分
            FsUser fsUser = fsUserMapper.selectFsUserByUserId(fsIntegralOrder.getUserId());
            fsUser.setIntegral(fsUser.getIntegral()+Long.parseLong(fsIntegralOrder.getIntegral()));
            i = fsUserMapper.updateFsUser(fsUser);
            Date now = new Date();
            //新增积分记录
            FsUserIntegralLogs fsUserIntegralLogs = new FsUserIntegralLogs();
            fsUserIntegralLogs.setBalance(fsUser.getIntegral());
            fsUserIntegralLogs.setBusinessId(fsIntegralOrder.getOrderId().toString());
            fsUserIntegralLogs.setUserId(fsIntegralOrder.getUserId());
            fsUserIntegralLogs.setLogType(27);
            fsUserIntegralLogs.setIntegral(Long.parseLong(fsIntegralOrder.getIntegral()));
            fsUserIntegralLogs.setBusinessType(2);
            fsUserIntegralLogs.setStatus(0);
            fsUserIntegralLogs.setCreateTime(now);
            fsUserIntegralLogs.setUpdateTime(now);
            i = fsUserIntegralLogsMapper.insertFsUserIntegralLogs(fsUserIntegralLogs);
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int mandatoryRefunds(String orderCode) {
        //查询订单是否存在且是否未发货
        FsIntegralOrder fsIntegralOrder = fsIntegralOrderMapper.selectFsIntegralOrderByOrderCode(orderCode);
        if (null==fsIntegralOrder){
            throw new ServiceException("订单不存在");
        }
        log.info("用户：{}退款订单编号：{}，退还积分{}", SecurityUtils.getLoginUser().getUser().getNickName(),fsIntegralOrder.getOrderCode(),fsIntegralOrder.getIntegral());
        //物流退单操作
        //用户说自己去对接物流，不必校验是否发货。
//        if (fsIntegralOrder.getStatus()!=1){
//            throw new ServiceException("订单已发货或已完成");
//        }
        int i = 0;
        //修改订单状态
        i = fsIntegralOrderMapper.cancelOrder(fsIntegralOrder.getOrderId());
        if (i>0){
            //原路退回积分
            FsUser fsUser = fsUserMapper.selectFsUserByUserId(fsIntegralOrder.getUserId());
            fsUser.setIntegral(fsUser.getIntegral()+Long.parseLong(fsIntegralOrder.getIntegral()));
            i = fsUserMapper.updateFsUser(fsUser);
            //新增积分记录
            FsUserIntegralLogs fsUserIntegralLogs = new FsUserIntegralLogs();
            fsUserIntegralLogs.setBalance(fsUser.getIntegral());
            fsUserIntegralLogs.setBusinessId(fsIntegralOrder.getOrderId().toString());
            fsUserIntegralLogs.setUserId(fsIntegralOrder.getUserId());
            fsUserIntegralLogs.setLogType(FsUserIntegralLogTypeEnum.TYPE_27.getValue());//20
            fsUserIntegralLogs.setIntegral(Long.parseLong(fsIntegralOrder.getIntegral()));
            fsUserIntegralLogs.setBusinessType(2);
            fsUserIntegralLogs.setStatus(0);
            fsUserIntegralLogs.setCreateTime(new Date());
            i = fsUserIntegralLogsMapper.insertFsUserIntegralLogs(fsUserIntegralLogs);
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int finishOrder(String orderCode) {
        //查询订单是否存在且是否未发货
        FsIntegralOrder fsIntegralOrder = fsIntegralOrderMapper.selectFsIntegralOrderByOrderCode(orderCode);
        if (null==fsIntegralOrder){
            throw new ServiceException("订单不存在");
        }
        if (fsIntegralOrder.getStatus()!=2){
            throw new ServiceException("订单未发货或者未支付，无法完成订单");
        }
        return fsIntegralOrderMapper.finishOrder(fsIntegralOrder.getOrderId(), fsIntegralOrder.getStatus());
    }

    @Override
    public List<FsIntegralOrder> selectFsIntegralOrderByOrderIds(List<Long> orderIds) {
        if (CollectionUtils.isEmpty(orderIds)) {
            return Collections.emptyList();
        }
        return fsIntegralOrderMapper.findOrderByIds(orderIds);
    }


    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void createErpOrder(Long orderId) throws ParseException {
        //判断是否开启erp
        FsSysConfig sysConfig = configUtil.getSysConfig();
        Integer erpOpen = sysConfig.getErpOpen();
        if (erpOpen == null || erpOpen == 0) {
            return;
        }
        //判断erp类型
        Integer erpType = sysConfig.getErpType();
        if (erpType == null) {
            return;
        }
        IErpOrderService erpOrderService = null;
        ErpOrder erpOrder = new ErpOrder();
        erpOrder.setShop_code(sysConfig.getErpShopCode());
        if (erpType == 1) {
            //管易
            erpOrderService = gyOrderService;
        } else if (erpType == 2) {
            //旺店通
            erpOrderService = wdtOrderService;
        } else if (erpType == 3) {
            //瀚智OMS
            erpOrderService = hzOMSOrderService;
        } else if (erpType == 4) {
            //代服
            erpOrderService = dfOrderService;
        } else if (erpType == 5) {
            //聚水潭
            erpOrderService = jSTOrderService;
            erpOrder.setShop_code(sysConfig.getErpJstShopCode());
        }else if (erpType == 6) {
            erpOrderService = k9OrderService;
        } else {
            return;
        }
        FsIntegralOrder order = fsIntegralOrderMapper.selectOne(Wrappers.<FsIntegralOrder>lambdaQuery().eq(FsIntegralOrder::getOrderId, orderId));
        if (order == null || !order.getStatus().equals(1)) {//1.待发货状态，只有待发货的订单可以创建erp订单
            return;
        }
        if (order.getCompanyId() != null) {
            erpOrder.setVip_code(order.getUserId().toString() + order.getCompanyId().toString());
        } else {
            erpOrder.setVip_code(order.getUserId().toString());
        }
        erpOrder.setPlatform_code(order.getOrderCode());

        erpOrder.setBuyer_account(order.getUserName());
        erpOrder.setSeller_memo(order.getRemark());
        List<ErpOrderPayment> payments = new ArrayList<>();
        ErpOrderPayment payment = new ErpOrderPayment();
        payment.setPay_type_code("weixin");
        payment.setPayment(0d);
        if (order.getPayTime() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String timeString = sdf.format(Date.from((order.getPayTime().atZone(ZoneId.systemDefault()).toInstant())));
            Date date = sdf.parse(timeString); // 时间格式转为时间戳
            long timeLong = date.getTime();
            payment.setPaytime(new Timestamp(timeLong));
        }
        payments.add(payment);

        //物流代收都发 互联网医院顺丰
        if (!("金牛明医".equals(cloudHostProper.getCompanyName()))) {
            //由于积分商品的字段缺失，没有剩余金额，默认为0，固定走下面逻辑，注释掉if判断，删除else代码。
//            if (order.getPayRemain().compareTo(new BigDecimal(0)) == 0) {
                //没有物流代收
                //大于100发发顺丰云配
                if (order.getPayMoney().compareTo(new BigDecimal(100)) > 0) {
                    //发互联网医院SF.0235488558_241101
                    FsExpress express = expressService.selectFsExpressByOmsCode("SF.0235488558_241101");
                    erpOrder.setExpress_code(express.getOmsCode());
                    order.setDeliveryName(express.getName());
                    order.setDeliveryCode(express.getCode());
                } else {
                    //发ztpdd
                    FsExpress express = expressService.selectFsExpressByOmsCode("CDYJFYD.400011111705_241230");
                    erpOrder.setExpress_code(express.getOmsCode());
                    order.setDeliveryName(express.getName());
                    order.setDeliveryCode(express.getCode());
                }
//            }
        }

        erpOrder.setPayments(payments);
        if (order.getCompanyId() != null) {
            Company company = companyService.selectCompanyById(order.getCompanyId());
            if (company != null) {
                erpOrder.setSeller_memo(company.getCompanyName());
            }
        }
        if (order.getCompanyUserId() != null) {
            CompanyUser companyUser = companyUserService.selectCompanyUserById(order.getCompanyUserId());
            if (companyUser != null) {
                CompanyDept dept = companyDeptService.selectCompanyDeptById(companyUser.getDeptId());
                if (dept != null) {
                    List<String> names = companyDeptService.selectCompanyDeptNamesByIds(dept.getAncestors());
                    if (names != null && names.size() > 0) {
                        //写备注
                        erpOrder.setSeller_memo(erpOrder.getSeller_memo() + "-" + StringUtils.join(names, ",") + "," + dept.getDeptName());
                    }
                }
                erpOrder.setSeller_memo(erpOrder.getSeller_memo() + "-" + companyUser.getNickName());
            }
        }
        ErpRemarkDTO remarkDTO = new ErpRemarkDTO();
        remarkDTO.setTotalPrice(BigDecimal.ZERO);//order.getTotalPrice()积分订单没有这个字段，写0
        remarkDTO.setPayPrice(BigDecimal.ZERO);//order.getPayPrice()积分订单没有这个字段，写0
        remarkDTO.setDeliveryMoney(BigDecimal.ZERO);//order.getPayDelivery()积分订单没有这个字段，写0
        remarkDTO.setPayMoney(order.getPayMoney());
        remarkDTO.setCouponMoney(BigDecimal.ZERO);//order.getDiscountMoney()积分订单没有这个字段，写0
        remarkDTO.setOrderId(order.getOrderCode());
        remarkDTO.setYdMoney(BigDecimal.ZERO);//order.getPayPrice().subtract(order.getPayMoney().subtract(order.getPayDelivery()))积分订单没有这个字段，写0
        if (order.getPayTime() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(Date.from((order.getPayTime().atZone(ZoneId.systemDefault()).toInstant())));
            remarkDTO.setPayTime(format);
        }
        erpOrder.setSeller_memo(erpOrder.getSeller_memo() + JSONUtil.toJsonStr(remarkDTO));
        erpOrder.setOrder_type_code("order");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        erpOrder.setDeal_datetime(sdf.format(new Date()));

        FsStoreOrderItem itemMap = new FsStoreOrderItem();
        itemMap.setOrderId(order.getOrderId());
        String itemJson = order.getItemJson();
        JSONArray jsonArray = JSON.parseArray(itemJson);
        List<ErpOrderItem> details = new ArrayList<>();
        jsonArray.forEach(obj -> {
            JSONObject jsonObject = (JSONObject) obj;
            ErpOrderItem item = new ErpOrderItem();
            item.setOid(jsonObject.getString("goodsId"));
            item.setItem_code(jsonObject.getString("barCode"));//商品编码
            item.setPrice(jsonObject.getString("otPrice"));//市场价
            item.setQty(jsonObject.getInteger("num"));//数量
            item.setRefund(0);
            details.add(item);
        });
        erpOrder.setDetails(details);
        erpOrder.setReceiver_name(order.getUserName().replaceAll("[^\\u4e00-\\u9fa5a-zA-Z0-9]", ""));

        //推送人电话查询，默认使用df表的erpphone

        FsIntegralOrderDf integralDfAccount = integralOrderDfService.getBaseMapper().selectById(order.getOrderId());
        String phone = null;
        if (StringUtils.isNotBlank(integralDfAccount.getErpPhone())) {
            phone = integralDfAccount.getErpPhone();
        } else {
            if (order.getUserPhone().length() > 11) {
                phone = decryptPhone(order.getUserPhone());
            } else {
                phone = order.getUserPhone();
            }
        }
        if (phone.length() > 11) {
            erpOrder.setReceiver_phone(phone);
        } else {
            erpOrder.setReceiver_mobile(phone);
        }
        String[] address = order.getUserAddress().split(" ");
        try{
            if (address.length < 3) {
                String kdnAddress = fsUserAddressService.getKdnAddress(order.getUserAddress());
                Map<String, Object> addDAta = (Map<String, Object>) com.alibaba.fastjson.JSON.parse(kdnAddress);
                Map<String, String> add = (Map<String, String>) addDAta.get("Data");
                erpOrder.setReceiver_province(add.get("ProvinceName"));
                erpOrder.setReceiver_city(add.get("CityName"));
                erpOrder.setReceiver_district(add.get("ExpAreaName"));
                erpOrder.setReceiver_address(add.get("StreetName") + add.get("Address"));
            } else {
                erpOrder.setReceiver_province(address[0]);
                erpOrder.setReceiver_city(address[1]);
                erpOrder.setReceiver_district(address[2]);
                //处理地址多空隔问题
                if (address.length > 3) {
                    StringBuffer addrs = new StringBuffer();
                    for (int i = 3; i < address.length; i++) {
                        addrs.append(address[i]);
                    }
                    erpOrder.setReceiver_address(addrs.toString());
                } else if (address.length == 3) {
                    erpOrder.setReceiver_address(address[2]);
                }
            }
        }catch (Exception e){
            log.error("地址错误：{}",e);
            throw new CustomException("地址格式不对请正确写入详细地址！！");
        }
        erpOrder.setReceiver_address(erpOrder.getReceiver_address().replace("+", "加"));
        erpOrder.setReceiver_address(erpOrder.getReceiver_address().replace("\n", ""));
        erpOrder.setIsIntegralOrder(true);

        ErpOrderResponse response = erpOrderService.addOrder(erpOrder);
        log.info("ErpCreate:" + order.getOrderCode() + ":" + JSONUtil.toJsonStr(response));
//        if (Boolean.TRUE.equals(response.getSuccess())) {
//            //支付成功后 将订单号写入待发货的REDIS中
////            redisCache.setCacheObject("delivery" + ":" + response.getCode(), order.getOrderCode());
//            //更新推送标识
//            integralDfAccount.setIsPush(1);
//            integralOrderDfService.getBaseMapper().updateById(integralDfAccount);
//        }
    }

    @Override
    public FsIntegralOrderImportResultVO importOrderStatusData(List<FsIntegralOrderExcelVO> list) {
        if (StringUtils.isNull(list) || list.isEmpty()) {
            throw new ServiceException("导入数据不能为空！");
        }
        FsIntegralOrderImportResultVO result = new FsIntegralOrderImportResultVO();

        for (int i = 0; i < list.size(); i++) {
            FsIntegralOrderExcelVO vo = list.get(i);
            int rowNum = i + 2; // Excel行号从2开始（第1行是表头）

            try {
                //1.必填参数
                ExcelUtils.validateRequiredFields(vo, rowNum);

                FsIntegralOrder order = fsIntegralOrderMapper.selectOne(Wrappers.<FsIntegralOrder>lambdaQuery().eq(FsIntegralOrder::getOrderCode, vo.getOrderCode()));
                if (order == null) {
                    FsIntegralOrderImportResultVO.ImportResultItem item = new FsIntegralOrderImportResultVO.ImportResultItem();
                    item.setRowNum(rowNum);
                    item.setOrderCode(vo.getOrderCode());
                    item.setErrorMessage("订单不存在");
                    result.getFailureList().add(item);
                    result.setFailureNum(result.getFailureNum() + 1);
                    continue;
                }

                FsIntegralOrder param = new FsIntegralOrder(); //修改订单的参数
                param.setOrderCode(vo.getOrderCode());
                param.setOrderId(order.getOrderId());

                if ("6".equals(vo.getStatus())) {
                    FsIntegralOrderImportResultVO.ImportResultItem item = new FsIntegralOrderImportResultVO.ImportResultItem();
                    item.setRowNum(rowNum);
                    item.setOrderCode(vo.getOrderCode());
                    item.setErrorMessage("该状态不支持修改为待推送");
                    result.getFailureList().add(item);
                    result.setFailureNum(result.getFailureNum() + 1);
                    continue;
                }
                if ("-1".equals(vo.getStatus())) {
                    FsIntegralOrderImportResultVO.ImportResultItem item = new FsIntegralOrderImportResultVO.ImportResultItem();
                    item.setRowNum(rowNum);
                    item.setOrderCode(vo.getOrderCode());
                    item.setErrorMessage("该状态不支持修改为退款中，需要手动申请退款");
                    result.getFailureList().add(item);
                    result.setFailureNum(result.getFailureNum() + 1);
                    continue;
                }
                if ("-2".equals(vo.getStatus())) {
                    FsIntegralOrderImportResultVO.ImportResultItem item = new FsIntegralOrderImportResultVO.ImportResultItem();
                    item.setRowNum(rowNum);
                    item.setOrderCode(vo.getOrderCode());
                    item.setErrorMessage("该状态不支持修改为退款中，需要审核完成退款");
                    result.getFailureList().add(item);
                    result.setFailureNum(result.getFailureNum() + 1);
                    continue;
                }

                Integer status = order.getStatus();

                if (StringUtils.isNotBlank(vo.getStatus())){
                    param.setStatus(Integer.valueOf(vo.getStatus()));
                    status = Integer.valueOf(vo.getStatus());
                }
                /**
                 * 地址和电话仅待推送可以修改,积分没有代付款的订单
                 */
                String userAddress = vo.getUserAddress();
                String userPhone = vo.getUserPhone();
                if (StringUtils.isNotBlank(userAddress) || StringUtils.isNotBlank(userPhone)){
                    // 不要使用误导性枚举
                    if (Objects.equals(FsIntegralOrderStatusEnum.STATUS_1.getValue(), status)) {
                        param.setUserAddress(userAddress.isEmpty()?null:userAddress);
                        param.setUserPhone(userPhone.isEmpty()?null:userPhone);
                    } else {
                        FsIntegralOrderImportResultVO.ImportResultItem item = new FsIntegralOrderImportResultVO.ImportResultItem();
                        item.setRowNum(rowNum);
                        item.setOrderCode(vo.getOrderCode());
                        item.setErrorMessage("该状态不支持修改收货人地址或电话");
                        result.getFailureList().add(item);
                        result.setFailureNum(result.getFailureNum() + 1);
                        continue;
                    }
                }

                // 处理物流字段（非必须，填了就更新）
                if (StringUtils.isNotBlank(vo.getDeliveryCode())) {
                    param.setDeliveryCode(vo.getDeliveryCode());
                }
                if (StringUtils.isNotBlank(vo.getDeliveryName())) {
                    param.setDeliveryName(vo.getDeliveryName());
                }
                if (StringUtils.isNotBlank(vo.getDeliverySn())) {
                    param.setDeliverySn(vo.getDeliverySn());
                }

                param.setDeliveryStatus((vo.getDeliveryStatus()==null|| vo.getDeliveryStatus().isEmpty())?null:Integer.valueOf(vo.getDeliveryStatus()));
                param.setDeliveryType(vo.getDeliveryType().isEmpty()?null:vo.getDeliveryType());
                param.setUpdateTime(DateUtils.getNowDate());

                fsIntegralOrderMapper.updateById(param);

                FsIntegralOrderImportResultVO.ImportResultItem item = new FsIntegralOrderImportResultVO.ImportResultItem();
                item.setRowNum(rowNum);
                item.setOrderCode(vo.getOrderCode());
                result.getSuccessList().add(item);
                result.setSuccessNum(result.getSuccessNum() + 1);

            } catch (Exception e) {
                FsIntegralOrderImportResultVO.ImportResultItem item = new FsIntegralOrderImportResultVO.ImportResultItem();
                item.setRowNum(rowNum);
                item.setOrderCode(vo.getOrderCode());
                item.setErrorMessage(e.getMessage());
                result.getFailureList().add(item);
                result.setFailureNum(result.getFailureNum() + 1);
            }
        }

        return result;
    }

    /**
     * 处理手机号脱敏
     */
    private void processPhoneNumber(FsIntegralOrder order) {
        String userPhone = order.getUserPhone();
        if (StringUtils.isNotBlank(userPhone) && !userPhone.chars().allMatch(Character::isDigit)) {
            order.setUserPhone(PhoneUtil.decryptPhone(userPhone));
        }
    }

    /**
     * 处理商品信息
     */
    private void processGoodsInfo(FsIntegralOrder order, Set<FsIntegralOrder> resultSet) {
        String itemJson = order.getItemJson();
        if (StringUtils.isBlank(itemJson)) {
            return;
        }

        try {
            // 判断是否为数组格式
            if (itemJson.startsWith("[") && itemJson.endsWith("]")) {
                // 数组格式 - 多个商品
                List<FsIntegralGoods> goodsList = JSONUtil.toBean(itemJson,
                        new TypeReference<List<FsIntegralGoods>>(){}, true);

                for (FsIntegralGoods goods : goodsList) {
                    if (ObjectUtil.isNotEmpty(goods)) {
                        FsIntegralOrder newOrder = cloneOrder(order);
                        newOrder.setGoodsName(goods.getGoodsName());
                        newOrder.setOtPrice(goods.getOtPrice());
                        resultSet.add(newOrder);
                    }
                }
            } else {
                // 单商品格式
                FsIntegralGoods goods = JSONUtil.toBean(itemJson, FsIntegralGoods.class);
                if (ObjectUtil.isNotEmpty(goods)) {
                    order.setGoodsName(goods.getGoodsName());
                    order.setOtPrice(goods.getOtPrice());
                    resultSet.add(order);
                }
            }
        } catch (Exception e) {
            // JSON解析异常处理，可以根据需要记录日志
            log.warn("解析商品JSON数据失败，orderId: {}, json: {}", order.getOrderId(), itemJson);
        }
    }

    /**
     * 克隆订单对象（用于多商品情况）
     */
    private FsIntegralOrder cloneOrder(FsIntegralOrder original) {
        // 这里需要根据实际情况实现对象的深拷贝或浅拷贝
        // 以下是简单示例，实际项目中可能需要使用BeanUtils或序列化方式
        FsIntegralOrder cloned = new FsIntegralOrder();
        BeanUtils.copyProperties(original, cloned);
        return cloned;
    }
}

