package com.fzm.mall.server.front.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fzm.mall.server.front.asset.model.OrderPay;
import com.fzm.mall.server.front.asset.model.UserAsset;
import com.fzm.mall.server.front.asset.model.UserAssetRecord;
import com.fzm.mall.server.front.asset.model.po.qo.OrderQO;
import com.fzm.mall.server.front.asset.model.vo.order.OrderDetailVO;
import com.fzm.mall.server.front.asset.model.vo.order.OrderVO;
import com.fzm.mall.server.front.asset.service.IOrderPayService;
import com.fzm.mall.server.front.asset.service.IUserAssetRecordService;
import com.fzm.mall.server.front.asset.service.IUserAssetService;
import com.fzm.mall.server.front.base.PageVO;
import com.fzm.mall.server.front.constant.CommonConst;
import com.fzm.mall.server.front.constant.GoodMainConst;
import com.fzm.mall.server.front.constant.MALLGlobalConfig;
import com.fzm.mall.server.front.constant.PaymentTypeConst;
import com.fzm.mall.server.front.constant.cache.MallCacheHeader;
import com.fzm.mall.server.front.enums.*;
import com.fzm.mall.server.front.goods.model.*;
import com.fzm.mall.server.front.goods.model.vo.GoodsVo;
import com.fzm.mall.server.front.goods.model.vo.SkuVo;
import com.fzm.mall.server.front.goods.service.*;
import com.fzm.mall.server.front.merchant.model.Merchant;
import com.fzm.mall.server.front.merchant.service.IMerchantService;
import com.fzm.mall.server.front.mq.MsgProducer;
import com.fzm.mall.server.front.order.mapper.OrderSkuMapper;
import com.fzm.mall.server.front.order.mapper.RefundMapper;
import com.fzm.mall.server.front.order.model.*;
import com.fzm.mall.server.front.order.mapper.OrderMapper;
import com.fzm.mall.server.front.order.model.po.NftOrderPo;
import com.fzm.mall.server.front.order.model.po.PreSaleOrderVo;
import com.fzm.mall.server.front.order.model.po.TranDto;
import com.fzm.mall.server.front.order.model.vo.*;
import com.fzm.mall.server.front.order.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.front.redis.OrderRedis;
import com.fzm.mall.server.front.repository.RedisRepository;
import com.fzm.mall.server.front.user.model.User;
import com.fzm.mall.server.front.user.service.IRedisService;
import com.fzm.mall.server.front.user.service.IUserService;
import com.fzm.mall.server.front.util.ChainUtil;
import com.fzm.mall.server.front.util.OrderUtil;
import com.fzm.mall.server.front.util.TimeUtil;
import io.netty.util.internal.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户购物订单表 服务实现类
 * </p>
 *
 * @author fzm
 * @since 2021-03-02
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    private final OrderRedis orderRedis;
    private final IMerchantService merchantService;
    private final IGoodSkuService goodSkuService;
    private final IGoodSpuService spuService;
    private final IGoodSkuPropService skuPropService;
    private final IOrderDetailService orderDetailService;
    private final OrderMapper orderMapper;
    private final RedisRepository redisRepository;
    private final OrderSkuMapper orderSkuMapper;
    private final IMarketingCouponService marketingCouponService;
    private final IMarketingPromotionService marketingPromotionService;
    private final IDistributionTemplateService distributionTemplateService;
    private final IPayService payService;
    private final IUserAssetService userAssetService;
    private final ICountService countService;
    private final IDeliveryService deliveryService;
    private final IGoodsCouponService goodsCouponService;
    private final IOrderPayService orderPayService;
    private final IGoodCommentService goodCommentService;
    private final RefundMapper refundMapper;
    private final ISkuService skuService;
    private final IUserAssetRecordService userAssetRecordService;
    private final IGoodsPromotionService promotionService;
    private final IGoodsCouponService couponService;
    private final IPreSaleService preSaleService;
    private final MsgProducer msgProducer;
    private final IUserService userService;
    private final INftService nftService;
    private final ISpuService ispuService;
    private final IRedisService redisService;
    private final IOrderBindBoxService orderBindBoxService;

    @Autowired
    private ChainUtil chainUtil;


    /**
     * 查询订单
     */
    @Override
    public Order order(final String oid) {
        Order order = orderRedis.getOrder(oid);
        if (order != null) {
            return order;
        }
        QueryWrapper<Order> qw = new QueryWrapper<>();
        qw.eq("oid", oid);
        order = getOne(qw);
        if (order != null) {
            orderRedis.setOrder(oid, order);
        }
        return order;
    }

    /**
     * 查询出订单以及商家名称
     */
    @Override
    public OrderVO orderVO(final String oid) {
        Order order = order(oid);
        OrderVO orderVO = new OrderVO();
        if (order != null) {
            BeanUtils.copyProperties(order, orderVO);
            String merchantId = order.getMerchantId();
            OrderPay orderPay = orderPayService.getByPayId(orderVO.getPayId());
            orderVO.setPayType(orderPay.getPayType());
            orderVO.setPayTime(orderPay.getPayTime());
            Merchant info = merchantService.info(merchantId);
            if (info != null) {
                orderVO.setEnterpriseName(info.getEnterpriseName());
            }
            orderVO.setMerchantId(merchantId);
            GoodsPromotion promotion = promotionService.getByOid(oid);
            if (promotion != null) {
                orderVO.setPromotionAmount(promotion.getAmount().setScale(2, BigDecimal.ROUND_DOWN));
            }
            GoodsCoupon goodsCoupon = couponService.getByOid(oid);
            if (goodsCoupon != null) {
                orderVO.setCouponAmount(goodsCoupon.getAmount().setScale(2, BigDecimal.ROUND_DOWN));
            }
            buildOrderVO(orderVO);
        }
        return orderVO;
    }

    /**
     * 构建OrderVO
     */
    @Override
    public void buildOrderVO(OrderVO orderVO) {
        String oid = orderVO.getOid();
        List<OrderDetail> listOrderDetail = orderDetailService.listOrderDetail(oid);
        List<OrderDetailVO> orders = new ArrayList<>(listOrderDetail.size());
        for (OrderDetail po : listOrderDetail) {
            OrderDetailVO vo = new OrderDetailVO();
            BeanUtils.copyProperties(po, vo);
            String gid = po.getGoodsId();
            String skuId = po.getSkuId();
            GoodSpu goodSpu = spuService.goodSpu(gid);
            SkuVo sku = skuService.getBySkuId(skuId);
            Integer type = goodSpu.getType();
            vo.setType(type);
            if (type == 2) {
                //预售商品
                PreSale preSale = preSaleService.getByGoodsId(gid);
                vo.setPreSale(preSale);
            }
            String commonentId = goodCommentService.getCommonentId(oid, skuId);
            vo.setCommentId(commonentId);
            /**
             * 待支付的盲盒订单需要隐藏规格信息
             */
            boolean hideSku = orderVO.getOrderState() == OrderStateEnum.ORDER_STATE_TO_PAY.getState() &&
                    goodSpu.getSalesType() == GoodSpuSalesTypeEnum.BLIND_BOX.getType();
            if (hideSku) {
                vo.setSkuId(null);
            } else {
                List<Map<String, Object>> skuPropListMap = skuPropService.getSkuPropListBySkuId(skuId);
                vo.setPropList(skuPropListMap);
            }
            if (!StringUtils.isEmpty(sku.getThumb()) && !hideSku) {
                vo.setThumb(sku.getThumb());
            } else {
                vo.setThumb(goodSpu.getThumb());
            }
            vo.setThumb(goodSpu.getThumb());
            vo.setSalesType(goodSpu.getSalesType());
            orders.add(vo);
        }
        orderVO.setOrders(orders);
    }

    /**
     * 分页查询订单
     */
    @Override
    public PageVO<OrderVO> pageOrderVO(final OrderQO orderQO) {
        List<OrderVO> listOrder = orderMapper.listOrder(orderQO);
        Integer totalSize = orderMapper.countOrder(orderQO);
        if (!CollectionUtils.isEmpty(listOrder)) {
            for (OrderVO orderVO : listOrder) {
                buildOrderVO(orderVO);
            }
        }
        PageVO<OrderVO> pageVO = new PageVO<>();
        pageVO.init(orderQO.getPage(), orderQO.getSize(), totalSize, listOrder);
        return pageVO;
    }

    /**
     * 分页查询售后订单
     */
    @Override
    public PageVO<OrderVO> pageAfterSaleOrderVO(final OrderQO orderQO) {
        List<OrderVO> listOrder = orderMapper.listAfterSaleOrder(orderQO);
        Integer totalSize = orderMapper.countAfterSaleOrder(orderQO);
        if (!CollectionUtils.isEmpty(listOrder)) {
            for (OrderVO orderVO : listOrder) {
                buildOrderVO(orderVO);
            }
        }
        PageVO<OrderVO> pageVO = new PageVO<>();
        pageVO.init(orderQO.getPage(), orderQO.getSize(), totalSize, listOrder);
        return pageVO;
    }

    /**
     * 处理订单
     * TODO 订单处理可能发生错误，可以做一些收集
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void process(String oid) {
        // 查询订单状态
        Order orderPO = order(oid);
        if (orderPO == null || PaymentTypeConst.PAY_WAIT != orderPO.getOrderState()) {
            log.debug("订单不存在或订单不是待支付状态：{}" + oid);
            return;
        }
        // 订单超时
        long timestamp = TimeUtil.timestamp();
        Integer ok = orderMapper.orderTimeout(oid, timestamp);
        if (ok == null || ok != 1) {
            log.warn("订单超时失败：{}" + oid);
            return;
        }
        log.debug("订单超时成功：{}" + oid);
        List<OrderDetail> listOrderDetail = listOrderDetail(oid);
        for (OrderDetail po : listOrderDetail) {
            String gid = po.getGoodsId();
            // 查询商品计数方式
            //GoodSale goodSale = goodSaleService.goodSale(gid);
            // 拍下减库存  目前都是拍下立减
            // 恢复商品数量
            ok = orderSkuMapper.goodRestore(gid, po.getCoin(), po.getNumber().toString());
            if (ok == null || ok != 1) {
                log.warn("恢复商品数量失败：{}" + oid);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return;
            }
            log.debug("恢复商品数量成功：{}" + oid);
            redisRepository.delObj(MallCacheHeader.goods_sku + gid);
        }
        // 删除缓存
        redisRepository.delObj(MallCacheHeader.GOOD_ORDER + oid);
    }

    /**
     * 订单详情列表
     */
    @Override
    public List<OrderDetail> listOrderDetail(final String oid) {
        try {
            Object obj = redisRepository.getObj(MallCacheHeader.GOOD_ORDER_DETAIL + oid);
            if (obj != null) {
                return JSON.parseArray(JSON.toJSONString(obj), OrderDetail.class);
            }
        } catch (Exception e) {
            // 缓存中获取的数据转换发生错误，重置缓存
            redisRepository.delObj(MallCacheHeader.GOOD_ORDER_DETAIL + oid);
        }
        List<OrderDetail> listOrderDetail = orderDetailService.listOrderDetail(oid);
        if (!CollectionUtils.isEmpty(listOrderDetail)) {
            redisRepository.setObj(MallCacheHeader.GOOD_ORDER_DETAIL + oid, listOrderDetail, 7, TimeUnit.HOURS);
        }
        return listOrderDetail;
    }

    //创建订单
    @Transactional
    @Override
    public String createOrder(String uid, OrderVo orderVo, Integer type) {
        //总价格
        BigDecimal all = BigDecimal.ZERO;
        List<MerchantGoodsVo> merchantGoodsVos = orderVo.getMerchantGoodsVos();
        //支付单
        Pay pay = new Pay();
        pay.setPayId(OrderUtil.getPayId());
        JSONArray a = new JSONArray();
        Map<String, Order> merchantOrder = new HashMap<>();
        //所有skuId
        List<OrderSkuVo> allSkuVo = new ArrayList<>();
        for (MerchantGoodsVo m : merchantGoodsVos) {
            //订单
            Order order = new Order();
            String oid = OrderUtil.getOid();
            order.setOid(oid);
            List<OrderSkuVo> orderSkuVos = m.getOrderSkuVos();
            //订单总价
            BigDecimal total = BigDecimal.ZERO;
            //快递模板id
            String templateId = "";
            //每家店对应商品数量
            Integer merchantGoodSize = 0;
            //每家店对应商品重量
            BigDecimal merchantGoodWeight = BigDecimal.ZERO;


            for (OrderSkuVo orderSkuVo : orderSkuVos) {
                SkuVo skuVo = goodSkuService.getSkuVoBySkuId(orderSkuVo.getSkuId());
                if (skuVo == null || skuVo.getStatus() != 1) {
                    //商品不存在或下架
                    throw new RuntimeException("商品不存在或下架");
                }
                if (orderSkuVo.getNum() < 1) {
                    //商品数量错误
                    throw new RuntimeException("商品数量错误");
                }
                int i = goodSkuService.delStock(skuVo.getSkuId(), orderSkuVo.getNum());
                if (i != 1) {
                    throw new RuntimeException("库存不足!!!");
                }

                //统计每家店对应商品数量
                merchantGoodSize = merchantGoodSize + orderSkuVo.getNum();
                //统计每家店对应商品重量
                //merchantGoodWeight = merchantGoodWeight.add(skuVo.getWeight().multiply(new BigDecimal(orderSkuVo.getNum())));
                templateId = skuVo.getTemplateId();
                OrderDetail orderDetail = new OrderDetail();
                int commodity = spuService.getCommodityBySkuId(orderSkuVo.getSkuId());
                if (commodity == 3) {
                    int saleType = spuService.getNftSalesType(orderSkuVo.getSkuId());
                    if (saleType == 2) {
                        while (!redisService.setNx("select" + skuVo.getCommodityPassId())) {

                        }
                        String serialNo = skuService.getSerialNo(skuVo.getCommodityPassId());
                        List<Long> array = JSON.parseArray(serialNo, Long.class);
                        if (array.size() < orderSkuVo.getNum()) {
                            throw new RuntimeException("库存不足!!!");
                        }
                        int index = 1;
                        List<Long> list = new ArrayList<>();
                        for (Long o : array) {
                            if (index <= orderSkuVo.getNum()) {
                                list.add(o);
                                index++;
                            } else {
                                break;
                            }
                        }
                        boolean remove = array.removeAll(list);
                        skuService.updateSerialNo(JSON.toJSONString(array), skuVo.getCommodityPassId());
                        redisService.del("select" + skuVo.getCommodityPassId());
                        orderDetail.setSerialNo(JSON.toJSONString(list));
                    }
                }
                orderDetail.setOid(order.getOid());
                orderDetail.setGoodsId(skuVo.getGoodsId());
                orderDetail.setSkuId(skuVo.getSkuId());
                orderDetail.setCoin(skuVo.getCoinName());
                orderDetail.setName(skuVo.getName());
                orderDetail.setNumber(orderSkuVo.getNum());
                orderDetail.setAmount(skuVo.getOriginalPrice());
                orderDetailService.save(orderDetail);
                all = all.add(skuVo.getOriginalPrice().multiply(new BigDecimal(orderSkuVo.getNum())));
                total = total.add(skuVo.getOriginalPrice().multiply(new BigDecimal(orderSkuVo.getNum())));
            }
            /*//邮费计算
            BigDecimal PostFee = BigDecimal.ZERO;
            if (orderVo.getDelivery() == 0) {

            } else {
                PostFee = distributionTemplateService.getPrice(templateId, orderVo.getProvince(), total, merchantGoodSize, merchantGoodWeight);
            }

            if (PostFee.compareTo(new BigDecimal("-1")) == 0) {
                throw new RuntimeException("当前地区不支持快递");
            }
            all = all.add(PostFee);
            allSkuVo.addAll(orderSkuVos);
            //计算促销
            BigDecimal price = marketingPromotionService.promotion(m.getMerchantId(), orderSkuVos, type, oid);
            all = all.subtract(price);*/
            order.setUid(uid);
            order.setPayId(pay.getPayId());
            order.setMerchantId(m.getMerchantId());
            order.setTotal(total);
            order.setOrderType(1);
            //order.setDelivery(orderVo.getDelivery());
            order.setDelivery(0);
            order.setUname(orderVo.getUname());
            order.setPhone(orderVo.getPhone());
            order.setAddress(orderVo.getAddress());
            order.setVNote(m.getVNote());
            //order.setAmount(merchantAll.subtract(mermantPromotion).subtract(mermantCoupon).add(PostFee));
            //order.setDiscountAmount(promotionAll.add(couponAll));
            order.setPostFee(BigDecimal.ZERO);
            order.setDiscountAmount(BigDecimal.ZERO);
            order.setAmount(total);
            order.setOrderState(7);
            a.add(oid);
            orderMapper.insert(order);
            merchantOrder.put(m.getMerchantId(), order);
        }
        //
       /* List<String> goodsIdCouponVos = orderVo.getGoodsIdCouponVos();
        Map<String, BigDecimal> merchantCoupon = new HashMap<>();
        try {
            merchantCoupon = marketingCouponService.getCoupon(uid, goodsIdCouponVos, allSkuVo, type);
        } catch (Exception e) {
            throw new RuntimeException("存在无效优惠券!!!");
        }
        Set<String> merchant = merchantCoupon.keySet();
        if (merchant.size() == 0) {
            merchant = merchantOrder.keySet();
        }
        for (String s : merchant) {
            Order order = merchantOrder.get(s);
            if (merchantCoupon.get(s) != null) {
                BigDecimal subtract = order.getAmount().subtract(merchantCoupon.get(s));
                order.setAmount(subtract.compareTo(BigDecimal.ZERO) == 1 ? subtract : BigDecimal.ZERO);
                order.setDiscountAmount(order.getDiscountAmount().add(merchantCoupon.get(s)));
                all = all.subtract(merchantCoupon.get(s));
                GoodsCoupon goodsCoupon = new GoodsCoupon();
                goodsCoupon.setCouponId("");
                goodsCoupon.setGoodsId("");
                goodsCoupon.setAmount(merchantCoupon.get(s));
                goodsCoupon.setOid(order.getOid());
                goodsCoupon.setUid(uid);
                goodsCouponService.save(goodsCoupon);
            }
            orderMapper.insert(order);
        }*/
        pay.setUid(uid);
        pay.setState(6);
        pay.setTotal(all);
        pay.setPaidAmount(BigDecimal.ZERO);
        pay.setUnpaidAmount(all);
        pay.setPayType(4);
        pay.setOidsJson(a.toJSONString());
        payService.save(pay);
        return pay.getPayId();
    }

   /* //创建订单
    @Transactional
    public String oldcreateOrder(String uid, OrderVo orderVo, Integer type) {
        //总价格
        BigDecimal all = BigDecimal.ZERO;
        //总共优惠
        BigDecimal couponAll = BigDecimal.ZERO;
        //总共促销
        BigDecimal promotionAll = BigDecimal.ZERO;
        //总共邮费
        BigDecimal postFeeAll = BigDecimal.ZERO;
        Pay pay = new Pay();
        pay.setPayId(OrderUtil.getPayId());
        JSONArray a = new JSONArray();
        List<MerchantGoodsVo> merchantGoodsVos = orderVo.getMerchantGoodsVos();
        for (MerchantGoodsVo m : merchantGoodsVos) {
            Order order = new Order();
            String oid = OrderUtil.getOid();
            order.setOid(oid);
            a.add(oid);
            //每家店的总价格
            BigDecimal merchantAll = BigDecimal.ZERO;
            //每个goods对应总价格
            Map<String, BigDecimal> goodsAll = new HashMap<>();
            //每个goods对应的商品数量
            Map<String, Integer> goodsSize = new HashMap<>();
            //每家店对应商品数量
            Integer merchantGoodSize = 0;
            //每家店对应商品重量
            BigDecimal merchantGoodWeight = BigDecimal.ZERO;
            //快递模板id
            String templateId = "";
            List<OrderSkuVo> orderSkuVos = m.getOrderSkuVos();
            for (OrderSkuVo orderSkuVo : orderSkuVos) {
                SkuVo skuVo = goodSkuService.getSkuVoBySkuId(orderSkuVo.getSkuId());
                if (skuVo == null || skuVo.getStatus() != 1) {
                    //商品不存在或下架
                    throw new RuntimeException("商品不存在或下架");
                }
                if (orderSkuVo.getNum() < 1) {
                    //商品数量错误
                    throw new RuntimeException("商品数量错误");
                }
                int i = goodSkuService.delStock(skuVo.getSkuId(), orderSkuVo.getNum());
                if (i != 1) {
                    throw new RuntimeException("库存不足!!!");
                }
                templateId = skuVo.getTemplateId();
                BigDecimal skuprice = skuVo.getOriginalPrice().multiply(new BigDecimal(orderSkuVo.getNum()));
                //统计总价格
                all = all.add(skuprice);
                //统计每家店价格
                merchantAll = merchantAll.add(skuprice);
                //统计每个goods对应总价格
                BigDecimal price = goodsAll.get(skuVo.getGoodsId());
                if (price == null) {
                    price = BigDecimal.ZERO;
                }
                price = price.add(skuprice);
                goodsAll.put(skuVo.getGoodsId(), price);
                //每个goods对应的总数量
                Integer gSize = goodsSize.get(skuVo.getGoodsId());
                if (gSize == null) {
                    gSize = 0;
                }
                gSize = gSize + orderSkuVo.getNum();
                goodsSize.put(skuVo.getGoodsId(), gSize);
                //统计每家店对应商品数量
                merchantGoodSize = merchantGoodSize + orderSkuVo.getNum();
                //统计每家店对应商品重量
                merchantGoodWeight = merchantGoodWeight.add(skuVo.getWeight().multiply(new BigDecimal(orderSkuVo.getNum())));
                //生成orderDetail
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOid(order.getOid());
                orderDetail.setGoodsId(skuVo.getGoodsId());
                orderDetail.setSkuId(skuVo.getSkuId());
                orderDetail.setCoin(skuVo.getCoinName());
                orderDetail.setName(skuVo.getName());
                orderDetail.setNumber(orderSkuVo.getNum());
                orderDetail.setAmount(skuVo.getOriginalPrice());
                orderDetailService.save(orderDetail);
            }
            //每家店的总促销价格
            Map<String,BigDecimal>merchantPromotion = new HashMap<>();
            //merchantPromotion = marketingPromotionMapper.promotion(orderSkuVos);

            //每家店的总优惠价格
            BigDecimal mermantCoupon = BigDecimal.ZERO;
            List<GoodsIdCouponVo> goodsIdCouponVos = m.getGoodsIdCouponVos();
            for (GoodsIdCouponVo goodsIdCouponVo : goodsIdCouponVos) {
                boolean result = marketingCouponService.checkEffective(uid, goodsIdCouponVo.getCouponId(), type);
                if (!result) {
                    throw new RuntimeException("存在无效优惠券!!!");
                }
                String goodsId = marketingCouponService.getGoodsId(goodsIdCouponVo.getCouponId());
                BigDecimal price = marketingCouponService.getPrice(goodsIdCouponVo.getCouponId(), goodsAll.get(goodsId), goodsSize.get(goodsId), type);
                boolean remove = goodsIds.remove(goodsId);
                mermantCoupon = mermantCoupon.add(price);
                GoodsCoupon goodsCoupon = new GoodsCoupon();
                goodsCoupon.setCouponId(goodsIdCouponVo.getCouponId());
                goodsCoupon.setGoodsId(goodsIdCouponVo.getGoodsId());
                goodsCoupon.setAmount(price);
                goodsCoupon.setOid(order.getOid());
                goodsCoupon.setUid(uid);
                goodsCouponService.save(goodsCoupon);
            }
            //快递费
            BigDecimal PostFee = BigDecimal.ZERO;
            if (orderVo.getDelivery() == 0) {

            } else {
                PostFee = distributionTemplateService.getPrice(templateId, orderVo.getProvince(), merchantAll, merchantGoodSize, merchantGoodWeight);
            }

            if (PostFee.compareTo(new BigDecimal("-1")) == 0) {
                throw new RuntimeException("当前地区不支持快递");
            }
            postFeeAll = postFeeAll.add(PostFee);
            order.setUid(uid);
            order.setPayId(pay.getPayId());
            order.setMerchantId(m.getMerchantId());
            order.setTotal(merchantAll);
            order.setOrderType(1);
            order.setDelivery(orderVo.getDelivery());
            order.setUname(orderVo.getUname());
            order.setPhone(orderVo.getPhone());
            order.setAddress(orderVo.getAddress());
            order.setVNote(m.getVNote());
            order.setAmount(merchantAll.subtract(mermantPromotion).subtract(mermantCoupon).add(PostFee));
            //order.setDiscountAmount(promotionAll.add(couponAll));
            order.setPostFee(PostFee);
            order.setOrderState(7);
            orderMapper.insert(order);
        }
        pay.setUid(uid);
        pay.setState(6);
        pay.setTotal(all);
        pay.setPaidAmount(BigDecimal.ZERO);
        pay.setUnpaidAmount(all.subtract(couponAll).subtract(promotionAll).add(postFeeAll));
        pay.setPayType(0);
        pay.setOidsJson(a.toJSONString());
        payService.save(pay);
        return pay.getPayId();
    }*/

    @Override
    @Transactional
    public void handle(Object oid) {
        Order order = orderMapper.getByOid(oid.toString());
        System.out.println("head++++++" + oid.toString());
        //是否走链
        User user = userService.getByUid(order.getUid());
        boolean ischain = true;
        List<OrderDetail> details = orderDetailService.getList(order.getOid());
        if (!ischain) {
            //不是直接提货
            if (order.getDelivery() == 0) {
                for (OrderDetail orderDetail : details) {
                    //打币
                    UserAsset coin = userAssetService.getCoin(order.getUid(), orderDetail.getCoin());
                    if (coin == null) {
                        coin = new UserAsset();
                        coin.setCoin(orderDetail.getCoin());
                        coin.setAmount(new BigDecimal(orderDetail.getNumber()));
                        coin.setUid(order.getUid());
                        coin.setType(1);
                        userAssetService.save(coin);
                    } else {
                        userAssetService.addCoin(coin.getId(), new BigDecimal(orderDetail.getNumber()));
                    }
                    //记录
                    UserAssetRecord userAssetRecord = new UserAssetRecord();
                    userAssetRecord.setUid(order.getUid());
                    userAssetRecord.setAmount(new BigDecimal(orderDetail.getNumber()));
                    userAssetRecord.setCoin(orderDetail.getCoin());
                    userAssetRecord.setFlowId(OrderUtil.getFlowId());
                    userAssetRecord.setType(12);
                    userAssetRecord.setStatus(2);
                    userAssetRecord.setNote(order.getOid());
                    userAssetRecordService.save(userAssetRecord);
                    //加销量
                    countService.addSale(orderDetail.getGoodsId(), orderDetail.getNumber());
                    goodSkuService.addSales(orderDetail.getSkuId(), orderDetail.getNumber());
                }
            } else {
                Collection<Delivery> list = new ArrayList<>();
                for (OrderDetail orderDetail : details) {
                    //打币
                    UserAsset coin = userAssetService.getCoin(order.getUid(), orderDetail.getCoin());
                    if (coin == null) {
                        coin = new UserAsset();
                        coin.setCoin(orderDetail.getCoin());
                        coin.setFrozen(new BigDecimal(orderDetail.getNumber()));
                        coin.setUid(order.getUid());
                        coin.setType(1);
                        userAssetService.save(coin);
                    } else {
                        userAssetService.addUserfrozenAsset(coin.getId(), new BigDecimal(orderDetail.getNumber()));
                    }
                    //购买
                    UserAssetRecord userAssetRecord = new UserAssetRecord();
                    userAssetRecord.setUid(order.getUid());
                    userAssetRecord.setAmount(new BigDecimal(orderDetail.getNumber()));
                    userAssetRecord.setCoin(orderDetail.getCoin());
                    userAssetRecord.setFlowId(OrderUtil.getFlowId());
                    userAssetRecord.setType(12);
                    userAssetRecord.setNote(order.getOid());
                    userAssetRecord.setStatus(2);
                    userAssetRecordService.save(userAssetRecord);
                    //提货
                    UserAssetRecord userAssetRecord2 = new UserAssetRecord();
                    userAssetRecord2.setUid(order.getUid());
                    userAssetRecord2.setAmount(new BigDecimal(orderDetail.getNumber()));
                    userAssetRecord2.setCoin(orderDetail.getCoin());
                    userAssetRecord2.setFlowId(OrderUtil.getFlowId());
                    userAssetRecord2.setType(18);
                    userAssetRecord2.setStatus(2);
                    userAssetRecord2.setNote(order.getOid());
                    userAssetRecordService.save(userAssetRecord2);
                    Delivery delivery = new Delivery();
                    delivery.setOrderDeliveryId(OrderUtil.getDeliveryId());
                    delivery.setUid(order.getUid());
                    delivery.setMerchantId(order.getMerchantId());
                    delivery.setGoodsId(orderDetail.getGoodsId());
                    delivery.setSkuId(orderDetail.getSkuId());
                    delivery.setCoin(orderDetail.getCoin());
                    delivery.setName(orderDetail.getName());
                    delivery.setNumber(orderDetail.getNumber());
                    delivery.setUname(order.getUname());
                    delivery.setPhone(order.getPhone());
                    delivery.setAddress(order.getAddress());
                    delivery.setNote(orderDetail.getNote());
                    delivery.setDeliveryState(0);
                    list.add(delivery);
                    //加销量
                    countService.addSale(orderDetail.getGoodsId(), orderDetail.getNumber());
                    goodSkuService.addSales(orderDetail.getSkuId(), orderDetail.getNumber());
                }
                deliveryService.saveBatch(list);
            }
        } else {
            Merchant m = merchantService.info(order.getMerchantId());
            //不是直接提货
            if (order.getDelivery() == 0) {
                for (OrderDetail orderDetail : details) {
                    SkuVo skuVo = skuService.getBySkuId(orderDetail.getSkuId());

                    log.error("skuVo+++" + skuVo.toString());
                    //String hash = paraChainUtil.evmTransfer(, null, user.getAddress(), , orderDetail.getCoin());
                    //String replace = orderDetail.getCoin().replace(MALLGlobalConfig.GOODS_NFT_PREFIX,"");
                    int commodity = spuService.getCommodityBySkuId(orderDetail.getSkuId());
                    if (commodity == 1) {
                        //打币
                        UserAsset coin = userAssetService.getCoin(order.getUid(), orderDetail.getCoin());
                        if (coin == null) {
                            coin = new UserAsset();
                            coin.setCoin(orderDetail.getCoin());
                            coin.setAmount(new BigDecimal(orderDetail.getNumber()));
                            coin.setUid(order.getUid());
                            coin.setType(1);
                            coin.setGoodsCoin(orderDetail.getCoin());
                            userAssetService.save(coin);
                        } else {
                            userAssetService.addCoin(coin.getId(), new BigDecimal(orderDetail.getNumber()));
                        }
                        String coinName = orderDetail.getCoin().replace(MALLGlobalConfig.GOODS_NFT_PREFIX, "");
                        String hash = chainUtil.evmTransfer(user.getAddress(), m.getTokenIssueAddr(), Long.valueOf(coinName), orderDetail.getNumber().longValue());
                        UserAssetRecord userAssetRecord = new UserAssetRecord();
                        userAssetRecord.setUid(order.getUid());
                        userAssetRecord.setAmount(new BigDecimal(orderDetail.getNumber()));
                        userAssetRecord.setCoin(orderDetail.getCoin());
                        userAssetRecord.setFlowId(OrderUtil.getFlowId());
                        userAssetRecord.setType(12);
                        userAssetRecord.setStatus(2);
                        userAssetRecord.setNote(order.getOid());
                        userAssetRecordService.save(userAssetRecord);
                        //加销量
                        countService.addSale(orderDetail.getGoodsId(), orderDetail.getNumber());
                        goodSkuService.addSales(orderDetail.getSkuId(), orderDetail.getNumber());
                        //转币
                        TranDto tranDto = new TranDto();
                        tranDto.setId(userAssetRecord.getId());
                        tranDto.setAmount(new BigDecimal(orderDetail.getNumber()));
                        tranDto.setCoin(coinName);
                        tranDto.setFromAddr(m.getNftAddr());
                        tranDto.setHash(hash);
                        tranDto.setToAddr(user.getAddress());
                        tranDto.setDelivery(order.getDelivery() == 1);
                        tranDto.setRecoAddr("");
                        tranDto.setPrice(orderDetail.getAmount());
                        tranDto.setUpdateTime(System.currentTimeMillis());
                        log.error(JSONObject.toJSONString(tranDto));
                        msgProducer.sendTTL(JSONObject.toJSONString(tranDto), QueueTTLTypeEnum.CONFIRM_WITHDRAW_TTL, 5 * 1000);
                    } else if (commodity == 2) {
                        //打币
                        UserAsset coin = userAssetService.getCoin(order.getUid(), orderDetail.getCoin());
                        if (coin == null) {
                            coin = new UserAsset();
                            coin.setCoin(orderDetail.getCoin());
                            coin.setAmount(new BigDecimal(orderDetail.getNumber()));
                            coin.setUid(order.getUid());
                            coin.setType(1);
                            coin.setGoodsCoin(orderDetail.getCoin());
                            userAssetService.save(coin);
                        } else {
                            userAssetService.addCoin(coin.getId(), new BigDecimal(orderDetail.getNumber()));
                        }
                        String coinName = orderDetail.getCoin().replace(MALLGlobalConfig.GOODS_NFT_PREFIX, "");
                        String hash = chainUtil.evmTransfer(user.getAddress(), m.getTokenIssueAddr(), Long.valueOf(coinName), orderDetail.getNumber().longValue());
                        UserAssetRecord userAssetRecord = new UserAssetRecord();
                        userAssetRecord.setUid(order.getUid());
                        userAssetRecord.setAmount(new BigDecimal(orderDetail.getNumber()));
                        userAssetRecord.setCoin(orderDetail.getCoin());
                        userAssetRecord.setFlowId(OrderUtil.getFlowId());
                        userAssetRecord.setType(12);
                        userAssetRecord.setStatus(2);
                        userAssetRecord.setNote(order.getOid());
                        userAssetRecordService.save(userAssetRecord);
                        //加销量
                        countService.addSale(orderDetail.getGoodsId(), orderDetail.getNumber());
                        goodSkuService.addSales(orderDetail.getSkuId(), orderDetail.getNumber());
                        //转币
                        TranDto tranDto = new TranDto();
                        tranDto.setId(userAssetRecord.getId());
                        tranDto.setAmount(new BigDecimal(orderDetail.getNumber()));
                        //tranDto.setCoin(aLong.toString());
                        tranDto.setFromAddr(m.getNftAddr());
                        tranDto.setHash(hash);
                        tranDto.setToAddr(user.getAddress());
                        tranDto.setDelivery(order.getDelivery() == 1);
                        tranDto.setRecoAddr("");
                        tranDto.setPrice(orderDetail.getAmount());
                        tranDto.setUpdateTime(System.currentTimeMillis());
                        log.error(JSONObject.toJSONString(tranDto));
                        msgProducer.sendTTL(JSONObject.toJSONString(tranDto), QueueTTLTypeEnum.CONFIRM_WITHDRAW_TTL, 5 * 1000);
                    } else if (commodity == 3) {
                        int saleType = spuService.getNftSalesType(orderDetail.getSkuId());
                        if (saleType == 1) {
                            //打币
                            UserAsset coin = userAssetService.getCoin(order.getUid(), orderDetail.getCoin());
                            if (coin == null) {
                                coin = new UserAsset();
                                coin.setCoin(orderDetail.getCoin());
                                coin.setAmount(new BigDecimal(orderDetail.getNumber()));
                                coin.setUid(order.getUid());
                                coin.setType(1);
                                coin.setGoodsCoin(orderDetail.getCoin());
                                userAssetService.save(coin);
                            } else {
                                userAssetService.addCoin(coin.getId(), new BigDecimal(orderDetail.getNumber()));
                            }
                            String coinName = orderDetail.getCoin().replace(MALLGlobalConfig.GOODS_NFT_PREFIX, "");
                            String hash = chainUtil.evmTransfer(user.getAddress(), m.getTokenIssueAddr(), Long.valueOf(coinName), orderDetail.getNumber().longValue());
                            UserAssetRecord userAssetRecord = new UserAssetRecord();
                            userAssetRecord.setUid(order.getUid());
                            userAssetRecord.setAmount(new BigDecimal(orderDetail.getNumber()));
                            userAssetRecord.setCoin(orderDetail.getCoin());
                            userAssetRecord.setFlowId(OrderUtil.getFlowId());
                            userAssetRecord.setType(12);
                            userAssetRecord.setStatus(2);
                            userAssetRecord.setNote(order.getOid());
                            userAssetRecordService.save(userAssetRecord);
                            //加销量
                            countService.addSale(orderDetail.getGoodsId(), orderDetail.getNumber());
                            goodSkuService.addSales(orderDetail.getSkuId(), orderDetail.getNumber());
                            //转币
                            TranDto tranDto = new TranDto();
                            tranDto.setId(userAssetRecord.getId());
                            tranDto.setAmount(new BigDecimal(orderDetail.getNumber()));
                            //tranDto.setCoin(aLong.toString());
                            tranDto.setFromAddr(m.getNftAddr());
                            tranDto.setHash(hash);
                            tranDto.setToAddr(user.getAddress());
                            tranDto.setDelivery(order.getDelivery() == 1);
                            tranDto.setRecoAddr("");
                            tranDto.setPrice(orderDetail.getAmount());
                            tranDto.setUpdateTime(System.currentTimeMillis());
                            log.error(JSONObject.toJSONString(tranDto));
                            msgProducer.sendTTL(JSONObject.toJSONString(tranDto), QueueTTLTypeEnum.CONFIRM_WITHDRAW_TTL, 5 * 1000);
                        } else {
                            String json = orderDetail.getSerialNo();
                            JSONArray array = JSON.parseArray(json);
                            for (Object o : array) {
                                //打币
                                UserAsset coin = userAssetService.getCoin(order.getUid(), o.toString());
                                if (coin == null) {
                                    coin = new UserAsset();
                                    coin.setCoin(o.toString());
                                    coin.setAmount(new BigDecimal(1));
                                    coin.setUid(order.getUid());
                                    coin.setType(1);
                                    coin.setGoodsCoin(orderDetail.getCoin());
                                    userAssetService.save(coin);
                                } else {
                                    userAssetService.addCoin(coin.getId(), new BigDecimal(orderDetail.getNumber()));
                                }
                                String hash = chainUtil.evmTransfer(user.getAddress(), m.getTokenIssueAddr(), Long.valueOf(o.toString()), 1);
                                UserAssetRecord userAssetRecord = new UserAssetRecord();
                                userAssetRecord.setUid(order.getUid());
                                userAssetRecord.setAmount(new BigDecimal(orderDetail.getNumber()));
                                userAssetRecord.setCoin(o.toString());
                                userAssetRecord.setFlowId(OrderUtil.getFlowId());
                                userAssetRecord.setType(12);
                                userAssetRecord.setStatus(2);
                                userAssetRecord.setNote(order.getOid());
                                userAssetRecordService.save(userAssetRecord);
                                //加销量
                                countService.addSale(orderDetail.getGoodsId(), 1);
                                goodSkuService.addSales(orderDetail.getSkuId(), 1);
                                //转币
                                TranDto tranDto = new TranDto();
                                tranDto.setId(userAssetRecord.getId());
                                tranDto.setAmount(new BigDecimal(orderDetail.getNumber()));
                                //tranDto.setCoin(aLong.toString());
                                tranDto.setFromAddr(m.getNftAddr());
                                tranDto.setHash(hash);
                                tranDto.setToAddr(user.getAddress());
                                tranDto.setDelivery(order.getDelivery() == 1);
                                tranDto.setRecoAddr("");
                                tranDto.setPrice(orderDetail.getAmount());
                                tranDto.setUpdateTime(System.currentTimeMillis());
                                log.error(JSONObject.toJSONString(tranDto));
                                msgProducer.sendTTL(JSONObject.toJSONString(tranDto), QueueTTLTypeEnum.CONFIRM_WITHDRAW_TTL, 5 * 1000);
                            }

                        }
                    }
                    //String hash = tranCoinAndNft(skuVo.getSkuId(),m.getTokenIssueAddr(),user.getAddress(),new BigDecimal(orderDetail.getNumber()),skuVo.getType(),orderDetail.getCoin());
                    //记录

                }
            } else {
                Collection<Delivery> list = new ArrayList<>();
                for (OrderDetail orderDetail : details) {
                    int commodity = spuService.getCommodityBySkuId(orderDetail.getSkuId());
                    if (commodity == 1) {
                        //打币
                        UserAsset coin = userAssetService.getCoin(order.getUid(), orderDetail.getCoin());
                        if (coin == null) {
                            coin = new UserAsset();
                            coin.setCoin(orderDetail.getCoin());
                            coin.setAmount(new BigDecimal(orderDetail.getNumber()));
                            coin.setUid(order.getUid());
                            coin.setType(1);
                            coin.setGoodsCoin(orderDetail.getCoin());
                            userAssetService.save(coin);
                        } else {
                            userAssetService.addCoin(coin.getId(), new BigDecimal(orderDetail.getNumber()));
                        }
                        String coinName = orderDetail.getCoin().replace(MALLGlobalConfig.GOODS_NFT_PREFIX, "");
                        String hash = chainUtil.evmTransfer(user.getAddress(), m.getTokenIssueAddr(), Long.valueOf(coinName), orderDetail.getNumber().longValue());
                        UserAssetRecord userAssetRecord = new UserAssetRecord();
                        userAssetRecord.setUid(order.getUid());
                        userAssetRecord.setAmount(new BigDecimal(orderDetail.getNumber()));
                        userAssetRecord.setCoin(orderDetail.getCoin());
                        userAssetRecord.setFlowId(OrderUtil.getFlowId());
                        userAssetRecord.setType(12);
                        userAssetRecord.setStatus(2);
                        userAssetRecord.setNote(order.getOid());
                        userAssetRecordService.save(userAssetRecord);
                        //加销量
                        countService.addSale(orderDetail.getGoodsId(), orderDetail.getNumber());
                        goodSkuService.addSales(orderDetail.getSkuId(), orderDetail.getNumber());
                        //转币
                        TranDto tranDto = new TranDto();
                        tranDto.setId(userAssetRecord.getId());
                        tranDto.setAmount(new BigDecimal(orderDetail.getNumber()));
                        //tranDto.setCoin(aLong.toString());
                        tranDto.setFromAddr(m.getNftAddr());
                        tranDto.setHash(hash);
                        tranDto.setToAddr(user.getAddress());
                        tranDto.setDelivery(order.getDelivery() == 1);
                        tranDto.setRecoAddr("");
                        tranDto.setPrice(orderDetail.getAmount());
                        tranDto.setUpdateTime(System.currentTimeMillis());
                        log.error(JSONObject.toJSONString(tranDto));
                        msgProducer.sendTTL(JSONObject.toJSONString(tranDto), QueueTTLTypeEnum.CONFIRM_WITHDRAW_TTL, 5 * 1000);
                        //提货
                        UserAssetRecord userAssetRecord2 = new UserAssetRecord();
                        userAssetRecord2.setUid(order.getUid());
                        userAssetRecord2.setAmount(new BigDecimal(orderDetail.getNumber()));
                        userAssetRecord2.setCoin(orderDetail.getCoin());
                        userAssetRecord2.setFlowId(OrderUtil.getFlowId());
                        userAssetRecord2.setType(18);
                        userAssetRecord2.setStatus(2);
                        userAssetRecord2.setNote(order.getOid());
                        userAssetRecordService.save(userAssetRecord2);
                        Delivery delivery = new Delivery();
                        delivery.setOrderDeliveryId(OrderUtil.getDeliveryId());
                        delivery.setUid(order.getUid());
                        delivery.setMerchantId(order.getMerchantId());
                        delivery.setGoodsId(orderDetail.getGoodsId());
                        delivery.setSkuId(orderDetail.getSkuId());
                        delivery.setCoin(orderDetail.getCoin());
                        delivery.setName(orderDetail.getName());
                        delivery.setNumber(orderDetail.getNumber());
                        delivery.setUname(order.getUname());
                        delivery.setPhone(order.getPhone());
                        delivery.setAddress(order.getAddress());
                        delivery.setNote(orderDetail.getNote());
                        delivery.setDeliveryState(0);
                        list.add(delivery);
                    } else if (commodity == 2) {
                        //打币
                        UserAsset coin = userAssetService.getCoin(order.getUid(), orderDetail.getCoin());
                        if (coin == null) {
                            coin = new UserAsset();
                            coin.setCoin(orderDetail.getCoin());
                            coin.setAmount(new BigDecimal(orderDetail.getNumber()));
                            coin.setUid(order.getUid());
                            coin.setType(1);
                            coin.setGoodsCoin(orderDetail.getCoin());
                            userAssetService.save(coin);
                        } else {
                            userAssetService.addCoin(coin.getId(), new BigDecimal(orderDetail.getNumber()));
                        }
                        String coinName = orderDetail.getCoin().replace(MALLGlobalConfig.GOODS_NFT_PREFIX, "");
                        String hash = chainUtil.evmTransfer(user.getAddress(), m.getTokenIssueAddr(), Long.valueOf(coinName), orderDetail.getNumber().longValue());
                        UserAssetRecord userAssetRecord = new UserAssetRecord();
                        userAssetRecord.setUid(order.getUid());
                        userAssetRecord.setAmount(new BigDecimal(orderDetail.getNumber()));
                        userAssetRecord.setCoin(orderDetail.getCoin());
                        userAssetRecord.setFlowId(OrderUtil.getFlowId());
                        userAssetRecord.setType(12);
                        userAssetRecord.setStatus(2);
                        userAssetRecord.setNote(order.getOid());
                        userAssetRecordService.save(userAssetRecord);
                        //加销量
                        countService.addSale(orderDetail.getGoodsId(), orderDetail.getNumber());
                        goodSkuService.addSales(orderDetail.getSkuId(), orderDetail.getNumber());
                        //转币
                        TranDto tranDto = new TranDto();
                        tranDto.setId(userAssetRecord.getId());
                        tranDto.setAmount(new BigDecimal(orderDetail.getNumber()));
                        //tranDto.setCoin(aLong.toString());
                        tranDto.setFromAddr(m.getNftAddr());
                        tranDto.setHash(hash);
                        tranDto.setToAddr(user.getAddress());
                        tranDto.setDelivery(order.getDelivery() == 1);
                        tranDto.setRecoAddr("");
                        tranDto.setPrice(orderDetail.getAmount());
                        tranDto.setUpdateTime(System.currentTimeMillis());
                        log.error(JSONObject.toJSONString(tranDto));
                        msgProducer.sendTTL(JSONObject.toJSONString(tranDto), QueueTTLTypeEnum.CONFIRM_WITHDRAW_TTL, 5 * 1000);
                        //提货
                        UserAssetRecord userAssetRecord2 = new UserAssetRecord();
                        userAssetRecord2.setUid(order.getUid());
                        userAssetRecord2.setAmount(new BigDecimal(orderDetail.getNumber()));
                        userAssetRecord2.setCoin(orderDetail.getCoin());
                        userAssetRecord2.setFlowId(OrderUtil.getFlowId());
                        userAssetRecord2.setType(18);
                        userAssetRecord2.setStatus(2);
                        userAssetRecord2.setNote(order.getOid());
                        userAssetRecordService.save(userAssetRecord2);
                        Delivery delivery = new Delivery();
                        delivery.setOrderDeliveryId(OrderUtil.getDeliveryId());
                        delivery.setUid(order.getUid());
                        delivery.setMerchantId(order.getMerchantId());
                        delivery.setGoodsId(orderDetail.getGoodsId());
                        delivery.setSkuId(orderDetail.getSkuId());
                        delivery.setCoin(orderDetail.getCoin());
                        delivery.setName(orderDetail.getName());
                        delivery.setNumber(orderDetail.getNumber());
                        delivery.setUname(order.getUname());
                        delivery.setPhone(order.getPhone());
                        delivery.setAddress(order.getAddress());
                        delivery.setNote(orderDetail.getNote());
                        delivery.setDeliveryState(0);
                        list.add(delivery);
                    } else if (commodity == 3) {
                        int saleType = spuService.getNftSalesType(orderDetail.getSkuId());
                        if (saleType == 1) {
                            //打币
                            UserAsset coin = userAssetService.getCoin(order.getUid(), orderDetail.getCoin());
                            if (coin == null) {
                                coin = new UserAsset();
                                coin.setCoin(orderDetail.getCoin());
                                coin.setAmount(new BigDecimal(orderDetail.getNumber()));
                                coin.setUid(order.getUid());
                                coin.setType(1);
                                coin.setGoodsCoin(orderDetail.getCoin());
                                userAssetService.save(coin);
                            } else {
                                userAssetService.addCoin(coin.getId(), new BigDecimal(orderDetail.getNumber()));
                            }
                            String coinName = orderDetail.getCoin().replace(MALLGlobalConfig.GOODS_NFT_PREFIX, "");
                            String hash = chainUtil.evmTransfer(user.getAddress(), m.getTokenIssueAddr(), Long.valueOf(coinName), orderDetail.getNumber().longValue());
                            UserAssetRecord userAssetRecord = new UserAssetRecord();
                            userAssetRecord.setUid(order.getUid());
                            userAssetRecord.setAmount(new BigDecimal(orderDetail.getNumber()));
                            userAssetRecord.setCoin(orderDetail.getCoin());
                            userAssetRecord.setFlowId(OrderUtil.getFlowId());
                            userAssetRecord.setType(12);
                            userAssetRecord.setStatus(2);
                            userAssetRecord.setNote(order.getOid());
                            userAssetRecordService.save(userAssetRecord);
                            //加销量
                            countService.addSale(orderDetail.getGoodsId(), orderDetail.getNumber());
                            goodSkuService.addSales(orderDetail.getSkuId(), orderDetail.getNumber());
                            //转币
                            TranDto tranDto = new TranDto();
                            tranDto.setId(userAssetRecord.getId());
                            tranDto.setAmount(new BigDecimal(orderDetail.getNumber()));
                            //tranDto.setCoin(aLong.toString());
                            tranDto.setFromAddr(m.getNftAddr());
                            tranDto.setHash(hash);
                            tranDto.setToAddr(user.getAddress());
                            tranDto.setDelivery(order.getDelivery() == 1);
                            tranDto.setRecoAddr("");
                            tranDto.setPrice(orderDetail.getAmount());
                            tranDto.setUpdateTime(System.currentTimeMillis());
                            log.error(JSONObject.toJSONString(tranDto));
                            msgProducer.sendTTL(JSONObject.toJSONString(tranDto), QueueTTLTypeEnum.CONFIRM_WITHDRAW_TTL, 5 * 1000);
                            //提货
                            UserAssetRecord userAssetRecord2 = new UserAssetRecord();
                            userAssetRecord2.setUid(order.getUid());
                            userAssetRecord2.setAmount(new BigDecimal(orderDetail.getNumber()));
                            userAssetRecord2.setCoin(orderDetail.getCoin());
                            userAssetRecord2.setFlowId(OrderUtil.getFlowId());
                            userAssetRecord2.setType(18);
                            userAssetRecord2.setStatus(2);
                            userAssetRecord2.setNote(order.getOid());
                            userAssetRecordService.save(userAssetRecord2);
                            Delivery delivery = new Delivery();
                            delivery.setOrderDeliveryId(OrderUtil.getDeliveryId());
                            delivery.setUid(order.getUid());
                            delivery.setMerchantId(order.getMerchantId());
                            delivery.setGoodsId(orderDetail.getGoodsId());
                            delivery.setSkuId(orderDetail.getSkuId());
                            delivery.setCoin(orderDetail.getCoin());
                            delivery.setName(orderDetail.getName());
                            delivery.setNumber(orderDetail.getNumber());
                            delivery.setUname(order.getUname());
                            delivery.setPhone(order.getPhone());
                            delivery.setAddress(order.getAddress());
                            delivery.setNote(orderDetail.getNote());
                            delivery.setDeliveryState(0);
                            list.add(delivery);
                        } else {
                            String json = orderDetail.getSerialNo();
                            JSONArray array = JSON.parseArray(json);
                            for (Object o : array) {
                                //打币
                                UserAsset coin = userAssetService.getCoin(order.getUid(), o.toString());
                                if (coin == null) {
                                    coin = new UserAsset();
                                    coin.setCoin(o.toString());
                                    coin.setAmount(new BigDecimal(1));
                                    coin.setUid(order.getUid());
                                    coin.setType(1);
                                    coin.setGoodsCoin(orderDetail.getCoin());
                                    userAssetService.save(coin);
                                } else {
                                    userAssetService.addCoin(coin.getId(), new BigDecimal(orderDetail.getNumber()));
                                }
                                String hash = chainUtil.evmTransfer(user.getAddress(), m.getTokenIssueAddr(), Long.valueOf(o.toString()), 1);
                                UserAssetRecord userAssetRecord = new UserAssetRecord();
                                userAssetRecord.setUid(order.getUid());
                                userAssetRecord.setAmount(new BigDecimal(orderDetail.getNumber()));
                                userAssetRecord.setCoin(o.toString());
                                userAssetRecord.setFlowId(OrderUtil.getFlowId());
                                userAssetRecord.setType(12);
                                userAssetRecord.setStatus(2);
                                userAssetRecord.setNote(order.getOid());
                                userAssetRecordService.save(userAssetRecord);
                                //加销量
                                countService.addSale(orderDetail.getGoodsId(), 1);
                                goodSkuService.addSales(orderDetail.getSkuId(), 1);
                                //转币
                                TranDto tranDto = new TranDto();
                                tranDto.setId(userAssetRecord.getId());
                                tranDto.setAmount(new BigDecimal(orderDetail.getNumber()));
                                //tranDto.setCoin(aLong.toString());
                                tranDto.setFromAddr(m.getNftAddr());
                                tranDto.setHash(hash);
                                tranDto.setToAddr(user.getAddress());
                                tranDto.setDelivery(order.getDelivery() == 1);
                                tranDto.setRecoAddr("");
                                tranDto.setPrice(orderDetail.getAmount());
                                tranDto.setUpdateTime(System.currentTimeMillis());
                                log.error(JSONObject.toJSONString(tranDto));
                                msgProducer.sendTTL(JSONObject.toJSONString(tranDto), QueueTTLTypeEnum.CONFIRM_WITHDRAW_TTL, 5 * 1000);
                                //提货
                                UserAssetRecord userAssetRecord2 = new UserAssetRecord();
                                userAssetRecord2.setUid(order.getUid());
                                userAssetRecord2.setAmount(new BigDecimal(orderDetail.getNumber()));
                                userAssetRecord2.setCoin(orderDetail.getCoin());
                                userAssetRecord2.setFlowId(OrderUtil.getFlowId());
                                userAssetRecord2.setType(18);
                                userAssetRecord2.setStatus(2);
                                userAssetRecord2.setNote(order.getOid());
                                userAssetRecordService.save(userAssetRecord2);
                            }
                            Delivery delivery = new Delivery();
                            delivery.setOrderDeliveryId(OrderUtil.getDeliveryId());
                            delivery.setUid(order.getUid());
                            delivery.setMerchantId(order.getMerchantId());
                            delivery.setGoodsId(orderDetail.getGoodsId());
                            delivery.setSkuId(orderDetail.getSkuId());
                            delivery.setCoin(orderDetail.getCoin());
                            delivery.setName(orderDetail.getName());
                            delivery.setNumber(orderDetail.getNumber());
                            delivery.setUname(order.getUname());
                            delivery.setPhone(order.getPhone());
                            delivery.setAddress(order.getAddress());
                            delivery.setNote(orderDetail.getNote());
                            delivery.setDeliveryState(0);
                            delivery.setSerialNo(orderDetail.getSerialNo());
                            list.add(delivery);

                        }
                    }
                    //String hash = tranCoinAndNft(skuVo.getSkuId(),m.getTokenIssueAddr(),user.getAddress(),new BigDecimal(orderDetail.getNumber()),skuVo.getType(),orderDetail.getCoin());
                    //记录
                    deliveryService.saveBatch(list);
                }

            }
        }


    }

    @Override
    @Transactional
    public void close(Object oid) {
        Order order = orderMapper.getByOid(oid.toString());
        if (order == null) {
            log.error(oid.toString());
            return;
        }
        /**
         * 校验关单前的订单状态:待支付
         */
        checkOrderStateBeforeClose(order);
        order.setOrderState(2);
        int update = orderMapper.updateById(order);
        if (update == 0) {
            throw new RuntimeException("update order fail");
        }
        List<OrderDetail> list = orderDetailService.getList(oid.toString());
        for (OrderDetail orderDetail : list) {
            //加库存
            int updateSku = goodSkuService.addStock(orderDetail.getSkuId(), orderDetail.getNumber());
            if (updateSku == 0) {
                throw new RuntimeException("update sku stock fail");
            }
            String no = orderDetail.getSerialNo();
            List<Long> noList = JSON.parseArray(no, Long.class);
            SkuVo skuVo = goodSkuService.getSkuVoBySkuId(orderDetail.getSkuId());
            String serialNo = skuService.getSerialNo(skuVo.getCommodityPassId());
            if (!StringUtil.isNullOrEmpty(serialNo)) {
                List<Long> serialNoList = JSON.parseArray(serialNo, Long.class);
                serialNoList.addAll(noList);
                Collections.sort(serialNoList);
                int updateSerialNo = skuService.updateSerialNo(JSON.toJSONString(serialNoList), skuVo.getCommodityPassId());
                if (updateSerialNo == 0) {
                    throw new RuntimeException("update sku SerialNo fail");
                }
            }
        }
    }

    /**
     * 关闭订单前校验订单是否为“待支付”
     *
     * @param order
     */
    private void checkOrderStateBeforeClose(Order order) {
        if (order.getOrderState() != OrderStateEnum.ORDER_STATE_TO_PAY.getState()) {
            throw new RuntimeException("close order fail, order:" + order.toString());
        }
    }

    @Override
    @Transactional
    public int applyReturn(String uid, String oid) {
        List<OrderDetail> list = orderDetailService.getList(oid);
        for (OrderDetail orderDetail : list) {
            //冻结
            int i = userAssetService.frozenUserAssets(uid, orderDetail.getCoin(), orderDetail.getNumber());
            if (i != 1) {
                throw new RuntimeException("asset_not_enough");
            }
        }
        return orderMapper.applyReturn(uid, oid, System.currentTimeMillis());
    }

    @Override
    @Transactional
    public int revokeReturn(String uid, String oid) {
        refundMapper.revokeReturn(oid, System.currentTimeMillis());
        //解冻资产
        List<OrderDetail> list = orderDetailService.getList(oid);
        for (OrderDetail orderDetail : list) {
            int i = userAssetService.unfrozenUserAsset(uid, orderDetail.getNumber(), orderDetail.getCoin());
            if (i != 1) {
                throw new RuntimeException("frozen_asset_not_enough");
            }
        }

        return orderMapper.revokeReturn(uid, oid, System.currentTimeMillis());
    }

    @Override
    public ReturnMoneyDetail getReturnMoneyDetail(String oid) {
        ReturnMoneyDetail returnMoneyDetail = orderMapper.getReturnMoneyDetail(oid);
        if (returnMoneyDetail == null) {
            return null;
        }
        List<SkuVo> skuVos = new ArrayList<>();
        List<OrderDetail> list = orderDetailService.getList(oid);
        for (OrderDetail orderDetail : list) {
            SkuVo skuVoBySkuId = skuService.getBySkuId(orderDetail.getSkuId());
            skuVos.add(skuVoBySkuId);
        }
        returnMoneyDetail.setList(skuVos);
        return returnMoneyDetail;
    }

    @Override
    public Integer getCountByUidAndOid(String uid, String orderId) {
        QueryWrapper<Order> q = new QueryWrapper<>();
        q.eq("uid", uid);
        q.eq("oid", orderId);
        return count(q);
    }

    @Override
    @Transactional
    public String createPreSaleOrder(String uid, PreSaleOrderVo preSaleOrderVo) {
        SkuVo skuVo = goodSkuService.getSkuVoBySkuId(preSaleOrderVo.getSkuId());
        PreSale preSale = preSaleService.getByGoodsId(skuVo.getGoodsId());
        int i = goodSkuService.delStock(preSaleOrderVo.getSkuId(), preSaleOrderVo.getNumber());
        if (i != 1) {
            throw new RuntimeException("库存不足!!!");
        }
        JSONArray a = new JSONArray();
        Pay pay = new Pay();
        pay.setPayId(OrderUtil.getPayId());
        Order order = new Order();
        order.setOid(OrderUtil.getOid());
        a.add(order.getOid());
        order.setUid(uid);
        order.setPayId(pay.getPayId());
        order.setMerchantId(skuVo.getMerchantId());
        order.setTotal(skuVo.getOriginalPrice().multiply(new BigDecimal(preSaleOrderVo.getNumber())));
        order.setOrderType(2);
        order.setPostFee(BigDecimal.ZERO);
        order.setDiscountAmount(skuVo.getOriginalPrice());
        if (preSale.getDepositType() == 1) {
            order.setAmount(skuVo.getOriginalPrice().multiply(preSale.getDeposit().multiply(new BigDecimal(preSaleOrderVo.getNumber()))).setScale(2, RoundingMode.HALF_UP));
        } else {
            order.setAmount(preSale.getDeposit().multiply(new BigDecimal(preSaleOrderVo.getNumber())).setScale(2, RoundingMode.HALF_UP));
        }

        order.setOrderState(4);
        save(order);
        //订单详情
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOid(order.getOid());
        orderDetail.setAmount(skuVo.getOriginalPrice());
        orderDetail.setGoodsId(skuVo.getGoodsId());
        orderDetail.setSkuId(skuVo.getSkuId());
        orderDetail.setName(skuVo.getName());
        orderDetail.setCoin(skuVo.getCoinName());
        orderDetail.setNumber(preSaleOrderVo.getNumber());
        orderDetailService.save(orderDetail);
        pay.setUid(uid);
        pay.setState(4);
        pay.setTotal(order.getAmount());
        pay.setUnpaidAmount(order.getAmount());
        pay.setPaidAmount(BigDecimal.ZERO);
        pay.setPayType(4);
        pay.setOidsJson(a.toJSONString());
        payService.save(pay);
        return pay.getPayId();
    }

    @Override
    @Transactional
    public String createNftOrder(String uid, List<NftOrderPo> nftOrderPos) {
        BigDecimal amount = BigDecimal.ZERO;
        //merchant-goodIds
        Map<String, List<String>> shopGoodsList = new HashMap<>();
        //goodIds-number
        Map<String, Integer> goodsIdNumber = new HashMap<>();
        //goodsId-amount
        Map<String, BigDecimal> goodIdsAmount = new HashMap<>();
        //支付单
        Pay pay = new Pay();
        pay.setPayId(OrderUtil.getPayId());
        for (NftOrderPo nftOrderPo : nftOrderPos) {
            //商家归类
            GoodsVo byGoodId = ispuService.getByGoodId(nftOrderPo.getGoodsId());
            List<String> list = shopGoodsList.get(byGoodId.getMerchantId());
            if (list == null) {
                list = new ArrayList<>();
                list.add(nftOrderPo.getGoodsId());
            } else {
                list.add(nftOrderPo.getGoodsId());

            }
            shopGoodsList.put(byGoodId.getMerchantId(), list);
            goodsIdNumber.put(nftOrderPo.getGoodsId(), nftOrderPo.getNumber());
        }
        Set<String> strings = shopGoodsList.keySet();
        for (String merchantId : strings) {
            Order order = new Order();
            order.setOid(OrderUtil.getOid());
            order.setUid(uid);
            order.setPayId(pay.getPayId());
            order.setMerchantId(merchantId);
            //order.setTotal(skuVo.getOriginalPrice().multiply(new BigDecimal(preSaleOrderVo.getNumber())));
            BigDecimal orderAmount = BigDecimal.ZERO;
            order.setOrderType(2);
            List<String> list = shopGoodsList.get(merchantId);
            for (String goodsId : list) {
                orderAmount = orderAmount.add(goodIdsAmount.get(goodsId));
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setNumber(goodsIdNumber.get(goodsId));
                Nft byGoodsId = nftService.getByGoodsId(goodsId);
                orderDetail.setCoin(byGoodsId.getTokenId());
            }

        }
        //减库存
       /* Nft byGoodsId = nftService.getByGoodsId(nftOrderPo.getGoodsId());
        if(byGoodsId == null){
            throw new RuntimeException("GOODS_NOT_EXIST");
        }
        int i = nftService.delStock(byGoodsId.getId(),nftOrderPo.getNumber(),byGoodsId.getUpdateTime(),System.currentTimeMillis());
        if(i != 1){
            throw new RuntimeException("STOCK_NOT_ENOUGH");
        }*/
        return null;
    }

    /**
     * 盲盒下单
     *
     * @param uid     当前用户uid
     * @param type    type(2.APP 3.PC 4.微信小程序)
     * @param orderVo
     * @return
     */
    @Override
    public String blindBoxCreateOrder(String uid, Integer type, OrderBlindBoxVo orderVo) {
        /**
         * 1.根据算法，获取本次下单的对应的盲盒sku信息(sku基本信息+快递模板id),生成订单详情order_detail
         */
        long rStart = System.currentTimeMillis();
        SkuVo skuVo = orderBindBoxService.genRandomSku(orderVo.getGoodsId());
        long rEnd = System.currentTimeMillis();
        log.info("计算库存耗时：" + (rEnd - rStart));

        long odStart = System.currentTimeMillis();
        String oid = OrderUtil.getOid();
        OrderDetail orderDetail = saveOrderDetail(skuVo, oid);
        long odEnd = System.currentTimeMillis();
        log.info("保存订单详情耗时：" + (odEnd - odStart));

        /**
         * 2.记录本次下单的sku的数量和规格信息，计算邮费(一幕沒有邮费)
         */
        long teStart = System.currentTimeMillis();

        BigDecimal postFee = BigDecimal.ZERO;
//        if (orderVo.getDelivery().equals(OrderBlindBoxVo.DELIVERY_IMMEDIATELY)) {
//            postFee = sumPostFee(skuVo, orderVo, orderDetail);
//        }

        /**
         * (一幕沒有优惠券和促销活动)
         * 3.计算本次下单可享受的促销优惠：优惠券+促销活动(一幕沒有优惠券和促销活动)
         */
        BigDecimal promotionDiscountAmount = BigDecimal.ZERO;
//        List<OrderSkuVo> orderSkuVoList = new ArrayList<>();
//        OrderSkuVo orderSkuVo = new OrderSkuVo();
//        orderSkuVo.setSkuId(skuVo.getSkuId());
//        orderSkuVo.setNum(orderDetail.getNumber());
//        orderSkuVoList.add(orderSkuVo);
//        BigDecimal promotionDiscountAmount = sumPromotionDiscount(skuVo, orderSkuVoList, type, oid);

        /**
         * 优惠券
         */
        BigDecimal couponDiscountAmount = BigDecimal.ZERO;

//        BigDecimal couponDiscountAmount = sumCouponDiscount(uid, type, orderVo.getGoodsIdCouponIdList(), orderSkuVoList, skuVo.getMerchantId(), oid);

        /**
         * (一幕沒有积分抵扣)
         * 4.最终支付时，扣除用于抵扣的积分并生成积分抵扣记录
         */
        String payId = OrderUtil.getPayId();
        BigDecimal skuAmount = skuVo.getBlindBoxprice().multiply(GoodMainConst.BLIND_BOX_ORDER_SKU_NUM_BIGDECIMAL);
        BigDecimal discountAmount = promotionDiscountAmount.add(couponDiscountAmount);
        BigDecimal payableAmount = BigDecimal.ZERO;
        payableAmount = payableAmount.add(skuAmount).add(postFee).subtract(discountAmount);
        payableAmount = payableAmount.compareTo(BigDecimal.ZERO) == CommonConst.BIEDICIMAL_LEFT_LESS ? BigDecimal.ZERO : payableAmount;
        BigDecimal integralDeductionNum = BigDecimal.ZERO;
//        BigDecimal integralDeductionNum = saveIntegralRecord(payableAmount, orderVo, uid, payId);
        long teEnd = System.currentTimeMillis();
        log.info("中间计算耗时：" + (teEnd - teStart));
        /**
         * 5.生成支付单order_pay和订单order_info
         */
        long oiStart = System.currentTimeMillis();
        saveOrderInfo(payId, oid, uid, skuVo.getMerchantId(), skuAmount, discountAmount, postFee, integralDeductionNum, orderVo);
        long oiEnd = System.currentTimeMillis();
        log.info("保存订单耗时：" + (oiEnd - oiStart));

        long opStart = System.currentTimeMillis();
        saveOrderPay(payId, oid, orderVo.getCoin(), integralDeductionNum, uid, payableAmount);
        long opEnd = System.currentTimeMillis();
        log.info("保存支付单耗时：" + (opEnd - opStart));
        return payId;
    }

    /**
     * 生成订单信息       order_info
     *
     * @param payId
     * @param oid
     * @param uid
     * @param merchantId
     * @param skuAmount            商品总价
     * @param discountAmount       促销活动优惠金额 +　优惠券优惠金额
     * @param postFee              运费
     * @param integralDeductionNum 积分抵扣的金额
     * @param orderVo
     */
    private void saveOrderInfo(String payId, String oid, String uid, String merchantId, BigDecimal skuAmount,
                               BigDecimal discountAmount, BigDecimal postFee, BigDecimal integralDeductionNum, OrderBlindBoxVo orderVo) {
        Order order = new Order();
        order.setOid(oid);
        order.setUid(uid);
        order.setPayId(payId);
        order.setMerchantId(merchantId);
        order.setTotal(skuAmount);
        order.setOrderType(OrderTypeEnum.GENERAL.getType());
        order.setDelivery(orderVo.getDelivery());
        order.setUname(orderVo.getUname());
        order.setPhone(orderVo.getPhone());
        order.setAddress(orderVo.getAddress());
        order.setVNote(orderVo.getVNote());
        order.setPostFee(postFee);
        order.setDiscountAmount(discountAmount);

        BigDecimal amount = skuAmount.add(postFee).subtract(discountAmount).subtract(integralDeductionNum);
        amount = amount.compareTo(BigDecimal.ZERO) == CommonConst.BIEDICIMAL_LEFT_LESS ? BigDecimal.ZERO : amount;
        order.setAmount(amount);
        order.setOrderState(OrderStateEnum.ORDER_STATE_TO_PAY.getState());
        orderMapper.insert(order);
    }

    /**
     * 生成支付单信息
     *
     * @param payId
     * @param oid
     * @param coin                 用于抵扣的积分名称
     * @param integralDeductionNum 用于抵扣的积分数量
     * @param uid
     * @param payableAmount        剩余未支付的金额
     */
    private void saveOrderPay(String payId, String oid, String coin, BigDecimal integralDeductionNum, String uid, BigDecimal payableAmount) {
        Pay pay = new Pay();
        pay.setPayId(payId);
        /**
         * 一幕不存在积分抵扣
         *         pay.setCoin(coin);
         *         pay.setIntegralDeduction(integralDeductionNum);
         */
        pay.setUid(uid);
        pay.setState(OrderPayStateEnum.PAY_STATE_TO_PAY.getState());
        pay.setTotal(payableAmount);
        pay.setPaidAmount(BigDecimal.ZERO);
        pay.setUnpaidAmount(payableAmount);
        pay.setPayType(OrderPayTypeEnum.INTEGRAL.getType());
        JSONArray oidsJsonArray = new JSONArray();
        oidsJsonArray.add(oid);
        pay.setOidsJson(oidsJsonArray.toJSONString());
        payService.save(pay);
    }

    /**
     * 最终支付时，扣除用于抵扣的积分并生成积分抵扣记录
     *
     * @param payableAmount 订单待付金额 = sku总价（单价*数量） + 运费 - 促销活动优惠金额 - 优惠券优惠金额
     * @param orderVo
     * @param uid
     * @param payId
     * @return 用于抵扣的积分数量
     */
    private BigDecimal saveIntegralRecord(BigDecimal payableAmount, OrderBlindBoxVo orderVo, String uid, String payId) {
        BigDecimal result = BigDecimal.ZERO;
        if (payableAmount.compareTo(BigDecimal.ZERO) == CommonConst.BIEDICIMAL_EQUAL_RESULT) {
            return result;
        }
        boolean coinAvilable = StringUtils.isNotBlank(orderVo.getCoin()) && orderVo.getCoinNumber() != null
                && orderVo.getCoinNumber().compareTo(BigDecimal.ZERO) == CommonConst.BIEDICIMAL_LEFT_GREATER;
        if (coinAvilable) {
            BigDecimal price = merchantService.getPrice(orderVo.getCoin());
            if (price == null || price.compareTo(BigDecimal.ZERO) != CommonConst.BIEDICIMAL_LEFT_GREATER) {
                throw new RuntimeException("COIN_NOT_USEFUL");
            }
            /**
             * 余额全部用积分抵扣需要的积分数量
             */
            BigDecimal avilableNum = payableAmount.divide(price, 2, RoundingMode.UP);
            result = avilableNum.compareTo(orderVo.getCoinNumber()) == CommonConst.BIEDICIMAL_LEFT_GREATER ? orderVo.getCoinNumber() : avilableNum;
            payableAmount = payableAmount.subtract(orderVo.getCoinNumber().multiply(price).setScale(2, RoundingMode.DOWN));
            payableAmount = payableAmount.compareTo(BigDecimal.ZERO) == CommonConst.BIEDICIMAL_LEFT_GREATER ? payableAmount : BigDecimal.ZERO;
            saveUserAssetRecord(uid, orderVo, result, payId);
        }
        return result;
    }

    /**
     * 生成积分抵扣记录
     *
     * @param uid
     * @param orderVo
     * @param avilableNum 可用于抵扣的积分数量
     */
    private void saveUserAssetRecord(String uid, OrderBlindBoxVo orderVo, BigDecimal avilableNum, String payId) {
        //扣除积分
        UserAsset coin = userAssetService.getCoin(uid, orderVo.getCoin());
        int i = userAssetService.useToFrozen(coin.getId(), avilableNum, coin.getUpdateTime(), System.currentTimeMillis());
        if (i == 1) {
            //生成积分抵扣记录
            UserAssetRecord assetRecord = new UserAssetRecord();
            assetRecord.setFlowId(OrderUtil.getFlowId());
            assetRecord.setUid(uid);
            assetRecord.setCoin(orderVo.getCoin());
            assetRecord.setType(AssetRecordTypeEnum.INTEGRAL_DEDUCTION.getType());
            assetRecord.setAmount(avilableNum);
            assetRecord.setStatus(3);
            assetRecord.setOtherSide("平台");
            assetRecord.setHash("");
            assetRecord.setNote(payId);
            userAssetRecordService.save(assetRecord);
        } else {
            throw new RuntimeException("COIN_NOT_ENOUGH");
        }
    }

    /**
     * 优惠券使用
     *
     * @param uid
     * @param type
     * @param goodsIdCouponIdList
     * @param orderSkuVoList
     * @param merchantId
     * @param oid
     */
    private BigDecimal sumCouponDiscount(String uid, Integer type, List<String> goodsIdCouponIdList, List<OrderSkuVo> orderSkuVoList, String merchantId, String oid) {
        BigDecimal result = BigDecimal.ZERO;
        if (CollectionUtils.isEmpty(goodsIdCouponIdList)) {
            return result;
        }

        Map<String, BigDecimal> merchantCoupon;
        try {
            merchantCoupon = marketingCouponService.getCoupon(uid, goodsIdCouponIdList, orderSkuVoList, type);
        } catch (Exception e) {
            throw new RuntimeException("存在无效优惠券!!!");
        }
        Set<String> merchantIdSet = merchantCoupon.keySet();
        if (CollectionUtils.isEmpty(merchantIdSet)) {
            merchantIdSet.add(merchantId);
        }
        for (String merchId : merchantIdSet) {
            if (merchantCoupon.get(merchId) != null) {
                result = merchantCoupon.get(merchId);
                GoodsCoupon goodsCoupon = new GoodsCoupon();
                goodsCoupon.setCouponId("");
                goodsCoupon.setGoodsId("");
                goodsCoupon.setAmount(result);
                goodsCoupon.setOid(oid);
                goodsCoupon.setUid(uid);
                goodsCouponService.save(goodsCoupon);
            }
        }
        return result;
    }

    /**
     * 计算本次下单可享受的促销优惠金额：优惠券+促销活动
     *
     * @param skuVo
     * @param orderSkuVoList
     * @param type
     * @param oid
     * @return 可优惠的金额
     */
    private BigDecimal sumPromotionDiscount(SkuVo skuVo, List<OrderSkuVo> orderSkuVoList, Integer type, String oid) {
        return marketingPromotionService.promotion(skuVo.getMerchantId(), orderSkuVoList, type, oid);
    }

    /**
     * 计算邮费
     *
     * @param skuVo
     * @param orderVo
     * @param orderDetail
     * @return
     */
    private BigDecimal sumPostFee(SkuVo skuVo, OrderBlindBoxVo orderVo, OrderDetail orderDetail) {
        BigDecimal merchantGoodWeight = skuVo.getWeight().multiply(GoodMainConst.BLIND_BOX_ORDER_SKU_NUM_BIGDECIMAL);
        BigDecimal result = distributionTemplateService.getPrice(skuVo.getTemplateId(), orderVo.getProvince(), BigDecimal.ZERO, orderDetail.getNumber(), merchantGoodWeight);
        if (result.compareTo(CommonConst.NEGATIVE_ONE) == CommonConst.BIEDICIMAL_EQUAL_RESULT) {
            throw new RuntimeException("当前地区不支持快递");
        }
        return result;
    }

    /**
     * 生成订单详情order_detail
     *
     * @param skuVo
     * @param oid
     */
    private OrderDetail saveOrderDetail(SkuVo skuVo, String oid) {
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOid(oid);
        orderDetail.setGoodsId(skuVo.getGoodsId());
        orderDetail.setSkuId(skuVo.getSkuId());
        orderDetail.setCoin(skuVo.getCoinName());
        orderDetail.setName(skuVo.getName());
        orderDetail.setNumber(GoodMainConst.BLIND_BOX_ORDER_SKU_NUM);
        orderDetail.setAmount(skuVo.getBlindBoxprice());
        orderDetailService.save(orderDetail);
        return orderDetail;
    }
}
