package com.buy507.mall.portal.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URI;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConfig;
import com.alipay.api.internal.util.AlipaySignature;
import com.buy507.mall.model.*;
import com.buy507.mall.portal.domain.*;
import com.buy507.mall.portal.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.buy507.mall.common.api.CommonResult;
import com.buy507.mall.common.util.MD5Util;
import com.buy507.mall.mapper.DmsMemberTradeRecordMapper;
import com.buy507.mall.mapper.DmsOfflinePaymentRecordMapper;
import com.buy507.mall.mapper.DmsSellerBankAccountMapper;
import com.buy507.mall.mapper.OmsCartItemMapper;
import com.buy507.mall.mapper.OmsExpressCompanyMapper;
import com.buy507.mall.mapper.OmsOrderItemMapper;
import com.buy507.mall.mapper.OmsOrderMapper;
import com.buy507.mall.mapper.OmsOrderOperateHistoryMapper;
import com.buy507.mall.mapper.OmsOrderSettingMapper;
import com.buy507.mall.mapper.PmsProductMapper;
import com.buy507.mall.mapper.PmsSkuStockMapper;
import com.buy507.mall.mapper.UmsMemberMapper;
import com.buy507.mall.mapper.UmsMemberReceiveAddressMapper;
import com.buy507.mall.portal.component.CancelOrderSender;
import com.buy507.mall.portal.component.DistributeSender;
import com.buy507.mall.portal.component.RedisLock;
import com.buy507.mall.portal.dao.PortalOrderDao;
import com.buy507.mall.portal.pay.wxpay.MyConfig;
import com.buy507.mall.portal.pay.wxpay.WXPay;
import com.buy507.mall.portal.pay.wxpay.WXPayUtil;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;

/**
 * 前台订单管理Service
 */
@Service
public class OmsPortalOrderServiceImpl implements OmsPortalOrderService {
	
	private static Logger LOGGER = LoggerFactory.getLogger(OmsPortalOrderServiceImpl.class);
	
    @Autowired
    private UmsMemberService memberService;
    
    @Autowired
    private OmsOrderMapper orderMapper;
    
    @Autowired
    private RedisService redisService;
    
    @Value("${redis.key.prefix.orderId}")
    private String REDIS_KEY_PREFIX_ORDER_ID;
    
    @Autowired
    private PortalOrderDao portalOrderDao;
    
    @Autowired
    private OmsOrderSettingMapper orderSettingMapper;
    
    @Autowired
    private OmsOrderItemMapper orderItemMapper;
    
    @Autowired
    private CancelOrderSender cancelOrderSender;
    
    @Autowired
    private PmsProductMapper productMapper;
    
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    
    @Autowired
    private UmsMemberReceiveAddressMapper memberReceiveAddressMapper;
    
    @Autowired
    private OmsCartItemMapper cartItemMapper;
    
    @Autowired
    private DmsSellerBankAccountMapper sellerBankAccountMapper;
    
    @Autowired
    private DmsOfflinePaymentRecordMapper offlinePaymentRecordMapper;
    
    @Autowired
    private OmsExpressCompanyMapper expressCompanyMapper;
    
    @Autowired
	private PortalCommonService commonService;
    
    @Autowired
    private UmsMemberMapper memberMapper;
    
    @Autowired
    private OmsOrderOperateHistoryMapper orderOperateHistoryMapper;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private ExecutorService executorService;
    
    @Autowired
    private DistributeSender distributeSender;
    
    @Autowired
    private DmsMemberTradeRecordMapper memberTradeRecordMapper;
    
    @Autowired
    private RedisLock redisLock;

	@Autowired
	private AlipayService alipayService;

	@Autowired
	private MemberCommissionService memberCommissionService;
    
    @Value("${kuaidi100.url}")
    private String KUAIDI100_URL;
    
    @Value("${kuaidi100.customer}")
    private String KUAIDI100_CUSTOMER;
    
    @Value("${kuaidi100.key}")
    private String KUAIDI100_KEY;
    
    @Value("${wechat.pay.payCallBackUrl}")
	private String WECHAT_PAY_PAY_CALLBACK_URL;
	
	@Value("${wechat.pay.key}")
	private String WECHAT_PAY_KEY;
	
	@Value("${wechat.appId}")
	private String WECHAT_APPID;
	
	@Value("${wechat.pay.mchId}")
	private String WECHAT_PAY_MCHID;
    
    @Override
	public List<OrderResult> getMemberOrderList(Integer orderStatus, Integer pageSize, Integer pageNum) {
		UmsMember loginMember = memberService.getCurrentMember();
		PageHelper.startPage(pageNum, pageSize);
		OmsOrderExample orderExample = new OmsOrderExample();
		OmsOrderExample.Criteria criteria = orderExample.createCriteria();
		criteria.andMemberIdEqualTo(loginMember.getId());
		//删除状态：0->未删除；1->已删除
		criteria.andDeleteStatusEqualTo(0);
		
		
		//查询订单状态条件：0->待付款; 1->待发货; 2->待收货; 3->已完成; 4->已关闭; 6->全部; 7->待评价
		//待付款
		if(orderStatus == 0) {
			criteria.andStatusEqualTo(0);
		}
		
		//待发货
		if(orderStatus == 1) {
			criteria.andStatusEqualTo(1);
		}
		
		//待收货
		if(orderStatus == 2) {
			criteria.andStatusEqualTo(2);
		}
		
		//已完成
		if(orderStatus == 3) {
			criteria.andStatusEqualTo(orderStatus);
		}
		
		//已关闭
		if(orderStatus == 4) {
			criteria.andStatusEqualTo(orderStatus);
		}
		
		//待评价
		if(orderStatus == 7) {
			criteria.andStatusEqualTo(3); //已完成
			//确认收货状态：0->未确认；1->已确认
			criteria.andConfirmStatusEqualTo(1); //已确认
			criteria.andCommentTimeIsNull(); //评价时间为空
		}
		
		orderExample.setOrderByClause("create_time desc");
		
		List<OmsOrder> orderList = orderMapper.selectByExample(orderExample); 
		OrderResult orderResult = null;
		List<OrderResult> orderResultList = new ArrayList<>();
		OmsOrderItemExample orderItemExample = null;
		
		List<OmsOrderItem> orderItemList = null;
		List<OrderItemResult> orderItemResultList = null;
		OrderItemResult orderItemResult = null;
		for(OmsOrder order : orderList) {
			orderResult = new OrderResult();
			orderResult.setOrderId(order.getId());
			orderResult.setOrderSn(order.getOrderSn());
			orderResult.setCreateTime(order.getCreateTime());
			orderResult.setPayAmount(order.getPayAmount());
			orderResult.setOrderStatus(order.getStatus());
			orderResult.setDeliveryType(order.getDeliveryType());
			if(order.getStatus() == 0) {
				orderResult.setOrderStatusName("待付款");
				if(order.getPayType() != null && order.getPayType() == 3) {
					orderResult.setOrderStatusName("已付款待审核");
				}
			}
			if(order.getStatus() == 1) {
				orderResult.setOrderStatusName("待发货");
			}
			if(order.getStatus() == 2) {
				// 提货方式：0->自提；1->物流
				if(order.getDeliveryType() == 0) {
					orderResult.setOrderStatusName("待提货");
				} else {
					orderResult.setOrderStatusName("待收货");
				}
			}
			if(order.getStatus() == 3) {
				orderResult.setOrderStatusName("交易完成");
				if(order.getCommentTime() == null) {
					orderResult.setCommentStatus(0); //未评价
				} else {
					orderResult.setCommentStatus(1); //已评价
				}
			}
			if(order.getStatus() == 4) {
				orderResult.setOrderStatusName("交易关闭");
				orderResult.setOrderStatus(4);
			}
			
			//支付类型: 0->未支付；1->支付宝；2->微信; 3->线下支付; 4->积分支付
			if(order.getPayType() != null) {
				orderResult.setPayType(order.getPayType());
				if(order.getPayType() == 0) {
					orderResult.setPayTypeName("未支付");
				} else if(order.getPayType() == 1) {
					orderResult.setPayTypeName("支付宝支付");
				} else if(order.getPayType() == 2) {
					orderResult.setPayTypeName("微信支付");
				} else if(order.getPayType() == 3) {
					orderResult.setPayTypeName("线下支付");
				} else {
					orderResult.setPayTypeName("积分支付");
				}
			} else {
				orderResult.setPayType(0);
				orderResult.setPayTypeName("未支付");
			}
			
			orderItemExample = new OmsOrderItemExample();
			orderItemExample.createCriteria().andOrderIdEqualTo(order.getId());
			orderItemList = orderItemMapper.selectByExample(orderItemExample);
			orderResult.setProductsNum(orderItemList.size());
			
			orderItemResultList = new ArrayList<>();
			for(OmsOrderItem orderItem : orderItemList) {
				orderItemResult = new OrderItemResult();
				orderItemResult.setOrderId(order.getId());
				orderItemResult.setOrderSn(order.getOrderSn());
				orderItemResult.setProductBrand(orderItem.getProductBrand());
				orderItemResult.setProductId(orderItem.getProductId());
				orderItemResult.setProductName(orderItem.getProductName());
				orderItemResult.setProductPic(orderItem.getProductPic());
				orderItemResult.setProductPrice(orderItem.getProductPrice());
				orderItemResult.setProductQuantity(orderItem.getProductQuantity());
				orderItemResult.setSp1(orderItem.getSp1());
				orderItemResult.setSp2(orderItem.getSp2());
				orderItemResult.setSp3(orderItem.getSp3());
				orderItemResultList.add(orderItemResult);
			}
			
			orderResult.setOrderItem(orderItemResultList);
			orderResultList.add(orderResult);
		}
		
		return orderResultList;

	}

	@Override
	public OrderResult getMemberOrderDetailInfo(Long orderId) {
		UmsMember loginMember = memberService.getCurrentMember();
		
		OrderResult orderResult = new OrderResult();
		OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
		//删除状态：0->未删除；1->已删除
		if(order != null && order.getMemberId().equals(loginMember.getId()) && order.getDeleteStatus() == 0) {
			orderResult.setOrderId(order.getId());
			orderResult.setOrderSn(order.getOrderSn());
			orderResult.setCreateTime(order.getCreateTime());
			orderResult.setPayAmount(order.getPayAmount());
			orderResult.setOrderStatus(order.getStatus());
			orderResult.setDeliveryType(order.getDeliveryType());
			if(order.getStatus() == 0) {
				orderResult.setOrderStatusName("待付款");
				if(order.getPayType() != null && order.getPayType() == 3) {
					orderResult.setOrderStatusName("已付款待审核");
				}
			}
			if(order.getStatus() == 1) {
				orderResult.setOrderStatusName("待发货");
			}
			if(order.getStatus() == 2) {
				// 提货方式：0->自提；1->物流
				if(order.getDeliveryType() == 0) {
					orderResult.setOrderStatusName("待提货");
				} else {
					orderResult.setOrderStatusName("待收货");
				}
			}
			if(order.getStatus() == 3) {
				orderResult.setOrderStatusName("交易完成");
				if(order.getCommentTime() == null) {
					orderResult.setCommentStatus(0); //未评价
				} else {
					orderResult.setCommentStatus(1); //已评价
				}
			}
			if(order.getStatus() == 4) {
				orderResult.setOrderStatusName("交易关闭");
				orderResult.setOrderStatus(4);
			}
			
			orderResult.setFreightAmount(order.getFreightAmount());
			orderResult.setNote(order.getNote());
			orderResult.setDeliveryCompany(order.getDeliveryCompany());
			orderResult.setDeliverySn(order.getDeliverySn());
			orderResult.setPaymentTime(order.getPaymentTime());
			//支付类型: 0->未支付；1->支付宝；2->微信; 3->线下支付; 4->积分支付
			if(order.getPayType() != null) {
				orderResult.setPayType(order.getPayType());
				if(order.getPayType() == 0) {
					orderResult.setPayTypeName("未支付");
				} else if(order.getPayType() == 1) {
					orderResult.setPayTypeName("支付宝支付");
				} else if(order.getPayType() == 2) {
					orderResult.setPayTypeName("微信支付");
				} else if(order.getPayType() == 3) {
					orderResult.setPayTypeName("线下支付");
					DmsOfflinePaymentRecord paymentRecord = offlinePaymentRecordMapper.selectOneByOrderId(orderId);
					DmsSellerBankAccount bankAccount = sellerBankAccountMapper.selectOneById(paymentRecord.getSellerBankAccountId());
					OfflinePaymentRecordResult recordResult = new OfflinePaymentRecordResult();
					BeanUtils.copyProperties(paymentRecord, recordResult);
					BeanUtils.copyProperties(bankAccount, recordResult);
					
					if(recordResult.getConfirmStatus() == 1) {
						recordResult.setConfirmStatusName("已审核");
					} else {
						recordResult.setConfirmStatusName("未审核");
					}
					orderResult.setPaymentRecord(recordResult);
				} else {
					orderResult.setPayTypeName("积分支付");
				}
			} else {
				orderResult.setPayType(0);
				orderResult.setPayTypeName("未支付");
			}
			
			orderResult.setDeliveryTime(order.getDeliveryTime());
			orderResult.setReceiveTime(order.getReceiveTime());
			orderResult.setCommentTime(order.getCommentTime());
			
			//0->不开发票；1->电子发票；2->纸质发票
			if(order.getBillType() != null) {
				orderResult.setBillType(order.getBillType());
				if(order.getBillType() == 1) {
					orderResult.setBillTypeName("电子发票");
				} else if(order.getBillType() == 2) {
					orderResult.setBillTypeName("纸质发票");
				} else {
					orderResult.setBillTypeName("不开发票");
				}
			} else {
				orderResult.setBillType(0);
				orderResult.setBillTypeName("不开发票");
			}
			
			orderResult.setBillHeader(order.getBillHeader());
			orderResult.setBillContent(order.getBillContent());
			orderResult.setReceiverName(order.getReceiverName());
			orderResult.setReceiverPhone(order.getReceiverPhone());
			orderResult.setReceiverProvince(order.getReceiverProvince());
			orderResult.setReceiverCity(order.getReceiverCity());
			orderResult.setReceiverRegion(order.getReceiverRegion());
			orderResult.setReceiverDetailAddress(order.getReceiverDetailAddress());
			
			OmsOrderItemExample example = new OmsOrderItemExample();
			example.createCriteria().andOrderIdEqualTo(orderId);
			List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(example);
			
			OrderItemResult orderItemResult = null;
			orderResult.setProductsNum(orderItemList.size());
			List<OrderItemResult> orderItemResultList = new ArrayList<>();
			for(OmsOrderItem orderItem : orderItemList) {
				orderItemResult = new OrderItemResult();
				orderItemResult.setOrderId(order.getId());
				orderItemResult.setOrderSn(order.getOrderSn());
				orderItemResult.setProductBrand(orderItem.getProductBrand());
				orderItemResult.setProductId(orderItem.getProductId());
				orderItemResult.setProductName(orderItem.getProductName());
				orderItemResult.setProductPic(orderItem.getProductPic());
				orderItemResult.setProductPrice(orderItem.getProductPrice());
				orderItemResult.setProductQuantity(orderItem.getProductQuantity());
				orderItemResult.setSp1(orderItem.getSp1());
				orderItemResult.setSp2(orderItem.getSp2());
				orderItemResult.setSp3(orderItem.getSp3());
				orderItemResultList.add(orderItemResult);
			}
			
			orderResult.setOrderItem(orderItemResultList);
		}
		
		return orderResult;
	}

	@Transactional
    @Override
    public CommonResult createCartOrder(CartOrderParam orderParam) {
    	
        List<OmsOrderItem> orderItemList = new ArrayList<>();
        //获取购物车信息
        UmsMember member = memberMapper.selectByPrimaryKey(memberService.getCurrentMember().getId());
        OmsCartItemExample example = new OmsCartItemExample();
        example.createCriteria().andMemberIdEqualTo(member.getId());
        
        List<OmsCartItem> cartItemList = cartItemMapper.selectByExample(example);
        
        if(orderParam.getDeliveryType() == null || (orderParam.getDeliveryType() != 0 && orderParam.getDeliveryType() != 1) ) {
			return CommonResult.validateFailed("提货方式不能为空");
		}
        
        if(orderParam.getMemberReceiveAddressId() == null) {
			return CommonResult.validateFailed("会员收货地址不能为空");
		}
		
		UmsMemberReceiveAddress address = memberReceiveAddressMapper.selectOneById(orderParam.getMemberReceiveAddressId());
        if(address == null) {
        	return CommonResult.validateFailed("未查询到会员收货地址");
        }
        
        if(cartItemList.isEmpty()) {
        	return CommonResult.failed("请先选择商品");
        }
        
        BigDecimal zero = new BigDecimal(0);
        if(orderParam.getIntegration() == null) {
        	orderParam.setIntegration(zero);
        }
        
        PmsSkuStock skuStock = null;
        PmsProduct product = null;
        for (OmsCartItem cartItem : cartItemList) {
        	
        	//判断是否参与分销结算，如果不参与，不能在购物车生成订单
        	product = productMapper.selectByPrimaryKey(cartItem.getProductId());
        	if(product.getDistributionFlag().equals(0)) { //分销标志（0->不参与；1->参与）
        		return CommonResult.failed("服务器繁忙，请稍后再试");
        	}
        	//查询库存信息
        	skuStock = skuStockMapper.selectByPrimaryKey(cartItem.getProductSkuId());
        	//判断购物车中商品是否都有库存 (真实库存 = 库存 - 锁定库存)
            if ((skuStock.getStock() - skuStock.getLockStock()) < cartItem.getQuantity()) {
            	return CommonResult.failed("库存不足，无法下单");
            }
        }
        
        //先判断积分是否大于0，大于0表示使用了积分支付
        //flag 等于1表示使用积分支付   判断用户积分是否充足
        //flag = -1,表示integration小于0；flag = 0,表示integration等于0；flag = 1,表示integration大于0；
        int integerationFlag = orderParam.getIntegration().compareTo(new BigDecimal(0));
		
		if(integerationFlag == 1) {
			int flag = member.getBalance().compareTo(orderParam.getIntegration());
			//flag = -1,表示balance小于integration；flag = 0,表示balance等于integration；flag = 1,表示balance大于integration；
			if(flag == -1) {
				return CommonResult.validateFailed("森态积分不足，无法抵扣");
			}
		}
        
        for (OmsCartItem cartItem : cartItemList) {
        	
        	while(true) {
				long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
				if(redisLock.lock(String.valueOf(cartItem.getProductId()), String.valueOf(time))) {
					//查询库存信息
		        	skuStock = skuStockMapper.selectByPrimaryKey(cartItem.getProductSkuId());
		        	//判断购物车中商品是否都有库存 (真实库存 = 库存 - 锁定库存)
		            if ((skuStock.getStock() - skuStock.getLockStock()) < cartItem.getQuantity()) {
		            	redisLock.unlock(String.valueOf(cartItem.getProductId()), String.valueOf(time));
		            	throw new RuntimeException("库存不足，无法下单");
		            }
		            
		            //更新库存
		            skuStock.setLockStock(skuStock.getLockStock() + cartItem.getQuantity());
		            skuStockMapper.updateByPrimaryKey(skuStock);
		            
		            redisLock.unlock(String.valueOf(cartItem.getProductId()), String.valueOf(time));
					break;
				}
        	}
        }
        
        BigDecimal totalAmount = new BigDecimal(0);
        for (OmsCartItem cartItem : cartItemList) {
        	
            //生成下单商品信息
            OmsOrderItem orderItem = new OmsOrderItem();
            orderItem.setProductId(cartItem.getProductId());
            orderItem.setProductPic(cartItem.getProductPic());
            orderItem.setProductName(cartItem.getProductName());
            //orderItem.setProductAttr(cartPromotionItem.getProductAttr());
            orderItem.setProductBrand(cartItem.getProductBrand());
            orderItem.setProductSn(cartItem.getProductSn());
            orderItem.setProductPrice(cartItem.getPrice());
            orderItem.setProductQuantity(cartItem.getQuantity());
            orderItem.setProductSkuId(cartItem.getProductSkuId());
            orderItem.setProductSkuCode(cartItem.getProductSkuCode());
            orderItem.setProductCategoryId(cartItem.getProductCategoryId());
            orderItem.setSp1(cartItem.getSp1());
            orderItem.setSp2(cartItem.getSp2());
            orderItem.setSp3(cartItem.getSp3());
            orderItem.setPromotionName("无优惠");
            orderItem.setPromotionAmount(zero);
            orderItem.setGiftIntegration(0);
            orderItem.setGiftGrowth(0);
            orderItem.setCouponAmount(zero);
            orderItem.setIntegrationAmount(zero);
            orderItem.setRealAmount(zero);
            
            orderItemList.add(orderItem);
            
            //单个商品的总价 = 商品单价 * 商品数量
            totalAmount = totalAmount.add(cartItem.getPrice().multiply(new BigDecimal(cartItem.getQuantity())));
        }
        
        //生成订单信息
        OmsOrder order = new OmsOrder();
        order.setTotalAmount(totalAmount); // 订单总金额
        if(integerationFlag == 1) {
			int flag = orderParam.getIntegration().compareTo(totalAmount);
			BigDecimal integeration = new BigDecimal(0);
			//flag = -1,表示integration小于totalAmount；flag = 0,表示integration等于totalAmount；flag = 1,表示integration大于totalAmount；
			//如果传入的积分小于实际支付金额，用实际支付金额减去抵扣积分。
			//如果传入的积分等于或者大于实际支付金额，表示全额抵扣
			if(flag == -1) {
				order.setPayAmount(totalAmount.subtract(orderParam.getIntegration())); //实际支付金额
				order.setIntegrationAmount(orderParam.getIntegration());
				integeration = orderParam.getIntegration();
			} else {
				order.setPayAmount(zero);
				order.setIntegrationAmount(totalAmount);
				integeration = totalAmount;
			}
			
			//冻结用户余额
			while(true) {
				long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
				if(redisLock.lock(String.valueOf(member.getId()), String.valueOf(time))) {
					member = memberMapper.selectByPrimaryKey(member.getId());
					//flag = -1,表示balance小于integeration；flag = 0,表示balance等于integeration；flag = 1,表示balance大于integeration；
					flag = member.getBalance().compareTo(integeration);
					if(flag == -1) {
						throw new RuntimeException("森态积分不足，无法抵扣");
					}
					member.setBalance(member.getBalance().subtract(integeration)); //修改余额值
					member.setFreeze(member.getFreeze().add(integeration)); //修改冻结值
					memberMapper.updateByPrimaryKey(member);
					redisLock.unlock(String.valueOf(member.getId()), String.valueOf(time));
					break;
				}
			}
			
		} else {
	        order.setPayAmount(totalAmount); //实际支付金额
	        order.setIntegrationAmount(zero);
		}
        
        Date date = new Date();
        order.setMemberId(member.getId());
        order.setCreateTime(date);
        order.setModifyTime(date);
        order.setMemberUsername(member.getUsername());
        order.setFreightAmount(zero); //运费
        order.setPromotionAmount(zero); //促销优化金额（促销价、满减、阶梯价）
        order.setCouponAmount(zero);
        order.setDiscountAmount(zero);
        order.setPayType(0); //支付方式：0->未支付；1->支付宝；2->微信
        order.setSourceType(1); //订单来源：0->PC订单；1->app订单
        order.setDeliveryType(orderParam.getDeliveryType()); //提货方式：0->自提；1->物流
        
        //生成订单号
        order.setOrderSn(generateOrderSn(order));
        //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        order.setStatus(0);
        //订单类型：0->正常订单；1->秒杀订单
        order.setOrderType(0);
        
        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
        order.setAutoConfirmDay(orderSetting.getConfirmOvertime());
        order.setIntegration(0);
        order.setGrowth(0);
        
        //收货人信息：姓名、电话、邮编、地址
        order.setReceiverName(address.getName());
        order.setReceiverPhone(address.getPhoneNumber());
        order.setReceiverPostCode(address.getPostCode());
        order.setReceiverProvince(address.getProvince());
        order.setReceiverCity(address.getCity());
        order.setReceiverRegion(address.getRegion());
        order.setReceiverDetailAddress(address.getDetailAddress());
        order.setNote(orderParam.getNote() == null ? null : orderParam.getNote());
        
        //确认收货状态：0->未确认；1->已确认
        order.setConfirmStatus(0);
        //删除状态：0->未删除；1->已删除
        order.setDeleteStatus(0);
        order.setUseIntegration(0);
        order.setPromotionInfo("无优惠");
        order.setSettlementStatus(0); //分销结算状态（0->未结算；1->已结算；2->不结算）
        
        orderMapper.insert(order);
        
        for (OmsOrderItem orderItem : orderItemList) {
            orderItem.setOrderId(order.getId());
            orderItem.setOrderSn(order.getOrderSn());
            orderItemMapper.insert(orderItem);
        }
        
        //删除购物车中的下单商品
        for (OmsCartItem cartItem : cartItemList) {
        	cartItemMapper.deleteByPrimaryKey(cartItem.getId());
        }
        
        //超时未支付，自动取消订单
        //分钟转换成毫秒
        long delayTimes = orderSetting.getNormalOrderOvertime() * 60 * 1000;
        cancelOrderSender.sendMessage(order.getId(), delayTimes);
        
        Map<String, Object> result = new HashMap<>();
        result.put("orderId", order.getId());
        result.put("totalAmount", order.getPayAmount());
        return CommonResult.success(result, "下单成功");
    }
    
    /**
     * 直接购买，根据提交信息生成订单
     */
	@Transactional
	@Override
	public CommonResult createOrder(OrderParam orderParam) {
		
		if(orderParam.getSkuId() == null) {
			return CommonResult.validateFailed("商品SKU不能为空");
		}
		
		if(orderParam.getDeliveryType() == null || (orderParam.getDeliveryType() != 0 && orderParam.getDeliveryType() != 1) ) {
			return CommonResult.validateFailed("提货方式不能为空");
		}
		
		if(orderParam.getMemberReceiveAddressId() == null) {
			return CommonResult.validateFailed("会员收货地址不能为空");
		}
		
		UmsMemberReceiveAddress address = memberReceiveAddressMapper.selectOneById(orderParam.getMemberReceiveAddressId());
        if(address == null) {
        	return CommonResult.validateFailed("未查询到会员收货地址");
        }
		
		if(orderParam.getQuantity() == null) {
			return CommonResult.validateFailed("商品数量不能为空");
		}
		
		if(orderParam.getQuantity() <= 0) {
			return CommonResult.validateFailed("商品数量错误");
		}
		
		PmsSkuStock skuStock = skuStockMapper.selectByPrimaryKey(orderParam.getSkuId());
		if(skuStock == null) {
			return CommonResult.validateFailed("未查询到商品信息");
		}
		
		//判断商品是否都有库存 (库存 - 锁定库存 = 真实库存)
        if ((skuStock.getStock() - skuStock.getLockStock()) < orderParam.getQuantity()) {
            return CommonResult.validateFailed("库存不足，无法下单");
        }
		
		//根据商品id查询商品信息
		PmsProduct product = productMapper.selectByPrimaryKey(skuStock.getProductId());
		
		Map<String, Object> result = new HashMap<>();
		if(product != null) {
			
			UmsMember member = memberMapper.selectByPrimaryKey(memberService.getCurrentMember().getId());
			
	        BigDecimal discount = commonService.getDiscount(member.getId());
	        BigDecimal price = new BigDecimal(skuStock.getPrice().doubleValue());
	    	if(discount != null) {
	    		price = skuStock.getPrice().multiply(discount).setScale(2, BigDecimal.ROUND_HALF_UP);
	    	}
	        
	        BigDecimal totalAmount = new BigDecimal(0);
	        BigDecimal zero = new BigDecimal(0);
	        totalAmount = price.multiply(new BigDecimal(orderParam.getQuantity()));
	        
	        if(orderParam.getIntegration() == null) {
	        	orderParam.setIntegration(zero);
	        }
	        
	        //先判断积分是否大于0，大于0表示使用了积分支付
	        //flag 等于1表示使用积分支付   判断用户积分是否充足
	        //flag = -1,表示integration小于0；flag = 0,表示integration等于0；flag = 1,表示integration大于0；
	        int integerationFlag = orderParam.getIntegration().compareTo(new BigDecimal(0));
			
			if(integerationFlag == 1) {
				int flag = member.getBalance().compareTo(orderParam.getIntegration());
				//flag = -1,表示balance小于integration；flag = 0,表示balance等于integration；flag = 1,表示balance大于integration；
				if(flag == -1) {
					return CommonResult.validateFailed("森态积分不足，无法抵扣");
				}
			}
			
			while(true) {
				long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
				if(redisLock.lock(String.valueOf(skuStock.getProductId()), String.valueOf(time))) {
					
					//重新查询获取最新的数据
					skuStock = skuStockMapper.selectByPrimaryKey(orderParam.getSkuId());
					
					//判断购物车中商品是否都有库存 (库存 - 锁定库存 = 真实库存)
			        if ((skuStock.getStock() - skuStock.getLockStock()) < orderParam.getQuantity()) {
			            return CommonResult.validateFailed("库存不足，无法下单");
			        }
			        
			        skuStock.setLockStock(skuStock.getLockStock() + orderParam.getQuantity());
			        skuStockMapper.updateByPrimaryKey(skuStock);
			        redisLock.unlock(String.valueOf(skuStock.getProductId()), String.valueOf(time));
			        break;
				}
			}
			
			//生成订单信息
	        OmsOrder order = new OmsOrder();
	        order.setTotalAmount(totalAmount); // 订单总金额
			if(integerationFlag == 1) {
				int flag = orderParam.getIntegration().compareTo(totalAmount);
				BigDecimal integeration = new BigDecimal(0);
				//flag = -1,表示integration小于totalAmount；flag = 0,表示integration等于totalAmount；flag = 1,表示integration大于totalAmount；
				//如果传入的积分小于实际支付金额，用实际支付金额减去抵扣积分。
				//如果传入的积分等于或者大于实际支付金额，表示全额抵扣
				if(flag == -1) {
					order.setPayAmount(totalAmount.subtract(orderParam.getIntegration())); //实际支付金额
					order.setIntegrationAmount(orderParam.getIntegration());
					integeration = orderParam.getIntegration();
				} else {
					order.setPayAmount(zero);
					order.setIntegrationAmount(totalAmount);
					integeration = totalAmount;
				}
				
				//冻结用户余额
				while(true) {
					long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
					if(redisLock.lock(String.valueOf(member.getId()), String.valueOf(time))) {
						member = memberMapper.selectByPrimaryKey(member.getId());
						//flag = -1,表示balance小于integeration；flag = 0,表示balance等于integeration；flag = 1,表示balance大于integeration；
						flag = member.getBalance().compareTo(integeration);
						if(flag == -1) {
							throw new RuntimeException("森态积分不足，无法抵扣");
						}
						member.setBalance(member.getBalance().subtract(integeration)); //修改余额值
						member.setFreeze(member.getFreeze().add(integeration)); //修改冻结值
						memberMapper.updateByPrimaryKey(member);
						redisLock.unlock(String.valueOf(member.getId()), String.valueOf(time));
						break;
					}
				}
				
			} else {
		        order.setPayAmount(totalAmount); //实际支付金额
		        order.setIntegrationAmount(zero);
			}
	        
	        Date date = new Date();
	        order.setMemberId(member.getId());
	        order.setCreateTime(date);
	        order.setModifyTime(date);
	        order.setMemberUsername(member.getUsername());
	        order.setFreightAmount(zero); //运费
	        order.setPromotionAmount(zero); //促销优化金额（促销价、满减、阶梯价）
	        order.setCouponAmount(zero);
	        order.setDiscountAmount(zero);
	        order.setPayType(0); //支付方式：0->未支付；1->支付宝；2->微信
	        order.setSourceType(1); //订单来源：0->PC订单；1->app订单
	        order.setDeliveryType(orderParam.getDeliveryType()); //提货方式：0->自提；1->物流
	        
	        //生成订单号
	        order.setOrderSn(generateOrderSn(order));
	        //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
	        order.setStatus(0);
	        //订单类型：0->正常订单；1->秒杀订单
	        order.setOrderType(0);
	        
	        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
	        order.setAutoConfirmDay(orderSetting.getConfirmOvertime());
	        order.setIntegration(0);
	        order.setGrowth(0);
	        
	        //收货人信息：姓名、电话、邮编、地址
	        order.setReceiverName(address.getName());
	        order.setReceiverPhone(address.getPhoneNumber());
	        order.setReceiverPostCode(address.getPostCode());
	        order.setReceiverProvince(address.getProvince());
	        order.setReceiverCity(address.getCity());
	        order.setReceiverRegion(address.getRegion());
	        order.setReceiverDetailAddress(address.getDetailAddress());
	        
	        order.setNote(orderParam.getNote() == null ? null : orderParam.getNote());
	        
	        //确认收货状态：0->未确认；1->已确认
	        order.setConfirmStatus(0);
	        //删除状态：0->未删除；1->已删除
	        order.setDeleteStatus(0);
	        order.setUseIntegration(0);
	        order.setPromotionInfo("无优惠");
	        order.setSettlementStatus(0); //分销结算状态（0->未结算；1->已结算；2->不结算）
	        
	        orderMapper.insert(order);
	        
	        //生成订单商品信息
	        OmsOrderItem orderItem = new OmsOrderItem();
	        orderItem.setOrderId(order.getId());
	        orderItem.setOrderSn(order.getOrderSn());
	        orderItem.setProductId(product.getId());
	        orderItem.setProductPic(skuStock.getPic());
	        orderItem.setProductName(product.getName());
	        //orderItem.setProductAttr(cartPromotionItem.getProductAttr());
	        orderItem.setProductBrand(product.getBrandName());
	        orderItem.setProductSn(product.getProductSn());
	        orderItem.setProductPrice(price);
	        orderItem.setProductQuantity(orderParam.getQuantity());
	        orderItem.setProductSkuId(skuStock.getId());
	        orderItem.setProductSkuCode(skuStock.getSkuCode());
	        orderItem.setProductCategoryId(product.getProductCategoryId());
	        orderItem.setSp1(skuStock.getSp1());
	        orderItem.setSp2(skuStock.getSp2());
	        orderItem.setSp3(skuStock.getSp3());
	        orderItem.setPromotionName("无优惠");
	        orderItem.setPromotionAmount(new BigDecimal(0));
	        orderItem.setGiftIntegration(0);
	        orderItem.setGiftGrowth(0);
	        orderItem.setCouponAmount(new BigDecimal(0));
	        orderItem.setIntegrationAmount(new BigDecimal(0));
	        orderItem.setRealAmount(new BigDecimal(0));
	        
	        orderItemMapper.insert(orderItem);
	        
	        //超时未支付，自动取消订单
	        //分钟转换成毫秒
	        long delayTimes = orderSetting.getNormalOrderOvertime() * 60 * 1000;
	        cancelOrderSender.sendMessage(order.getId(), delayTimes);
	        
	        result.put("orderId", order.getId());
	        result.put("totalAmount", order.getPayAmount());
		}
		
        return CommonResult.success(result, "下单成功");
	}
    
	@Transactional
    @Override
    public CommonResult cancelTimeOutOrder() {
        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
        //查询超时、未支付的订单及订单详情
        List<OmsOrderDetail> timeOutOrders = portalOrderDao.getTimeOutOrders(orderSetting.getNormalOrderOvertime());
        if (CollectionUtils.isEmpty(timeOutOrders)) {
            return CommonResult.failed("暂无超时订单");
        }
        //修改订单状态为交易取消
        List<Long> ids = new ArrayList<>();
        for (OmsOrderDetail timeOutOrder : timeOutOrders) {
            ids.add(timeOutOrder.getId());
        }
        portalOrderDao.updateOrderStatus(ids, 4);
        for (OmsOrderDetail timeOutOrder : timeOutOrders) {
            //解除订单商品库存锁定
            portalOrderDao.releaseSkuStockLock(timeOutOrder.getOrderItemList());
        }
        return CommonResult.success(null);
    }

	@Transactional
    @Override
    public CommonResult cancelOrder(Long orderId) {
    	OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
    	if(order == null) {
    		return CommonResult.validateFailed("未查询到订单信息");
    	}
    	
    	boolean cancelFlag = false;
    	UmsMember member = null;
    	if(memberService.getCurrentMember() != null) {
    		member = memberMapper.selectByPrimaryKey(memberService.getCurrentMember().getId());
        	if(member != null) {
        		if(!order.getMemberId().equals(member.getId())) {
            		return CommonResult.validateFailed("未查询到订单信息");
            	}
        	}
    	} else {
    		member = memberMapper.selectByPrimaryKey(order.getMemberId());
    		cancelFlag = true;
    	}
    	
    	//未支付 and 未删除
    	if(order.getStatus() == 0 && order.getDeleteStatus() == 0) {
    		Date date = new Date();
    		//修改订单状态为取消
    		//订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
    		order.setStatus(4);
    		order.setModifyTime(date);
    		orderMapper.updateByPrimaryKey(order);
    		
    		//如果使用余额支付，取消订单需要退还余额
    		BigDecimal zero = new BigDecimal(0);
    		int flag = order.getIntegrationAmount().compareTo(zero);
    		//flag = -1,表示IntegrationAmount小于zero；flag = 0,表示IntegrationAmount等于zero；flag = 1,表示IntegrationAmount大于zero；
    		if(flag == 1) {
    			while(true) {
					long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
					if(redisLock.lock(String.valueOf(member.getId()), String.valueOf(time))) {
						member = memberMapper.selectByPrimaryKey(member.getId());
						member.setBalance(member.getBalance().add(order.getIntegrationAmount())); //修改余额值
						member.setFreeze(member.getFreeze().subtract(order.getIntegrationAmount())); //修改冻结值
						memberMapper.updateByPrimaryKey(member);
						redisLock.unlock(String.valueOf(member.getId()), String.valueOf(time));
						break;
					}
				}
    		}
    		
    		//写入订单历史操作日志
			OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(orderId);
            history.setCreateTime(date);
            if(cancelFlag) {
            	history.setOperateMan("自动程序");
            } else {
            	history.setOperateMan("会员");
            }
            
            //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
            history.setOrderStatus(4);
            history.setNote("取消订单");
            orderOperateHistoryMapper.insert(history);
    		
    		executorService.execute(new Runnable() {
				@Override
				public void run() {
					OmsOrderItemExample example = new OmsOrderItemExample();
					example.createCriteria().andOrderIdEqualTo(orderId);
					List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(example);
		    		PmsSkuStock skuStock = null;
		    		for(OmsOrderItem orderItem : orderItemList) {
		    			while(true) {
		    				long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
		    				if(redisLock.lock(String.valueOf(orderItem.getProductId()), String.valueOf(time))) {
		    					skuStock = skuStockMapper.selectByPrimaryKey(orderItem.getProductSkuId());
		    	    			skuStock.setLockStock(skuStock.getLockStock() - orderItem.getProductQuantity());
		    	    			skuStockMapper.updateByPrimaryKey(skuStock);
		    	    			redisLock.unlock(String.valueOf(orderItem.getProductId()), String.valueOf(time));
		    	    			break;
		    				}
		    			}
		    		}
				}
			});
    		
    	}
    	return CommonResult.success(null);
    }

    /**
     * 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
     */
    private String generateOrderSn(OmsOrder order) {
        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = REDIS_KEY_PREFIX_ORDER_ID + date;
        Long increment = redisService.increment(key, 1);
        sb.append(date);
        sb.append(String.format("%02d", order.getSourceType()));
        sb.append(String.format("%02d", order.getPayType()));
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 6) {
            sb.append(String.format("%06d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }

	@Override
	public SellerBankAccountResult getSellerBankAccount() {
		SellerBankAccountResult accountResult = new SellerBankAccountResult();
		BeanUtils.copyProperties(sellerBankAccountMapper.selectOneById(1), accountResult);
		return accountResult;
	}

	@Transactional
	@Override
	public CommonResult payment(OfflinePaymentParam paymentParam) {
		
		if(paymentParam.getOrderId() == null) {
			return CommonResult.validateFailed("订单编号不能为空");
		}
		
		if(StringUtils.isEmpty(paymentParam.getPaymentAccountName())) {
			return CommonResult.validateFailed("支付银行账户名不能为空");
		}
		if(StringUtils.isEmpty(paymentParam.getPaymentBankName())) {
			return CommonResult.validateFailed("支付银行名称不能为空");
		}
		if(StringUtils.isEmpty(paymentParam.getPaymentBankCardNum())) {
			return CommonResult.validateFailed("支付银行卡号不能为空");
		}
		
		OmsOrder order = orderMapper.selectByPrimaryKey(paymentParam.getOrderId());
		if(order == null) {
			return CommonResult.validateFailed("未查询到订单信息");
		}
		
		UmsMember currentMember = memberService.getCurrentMember();
    	if(!order.getMemberId().equals(currentMember.getId())) {
    		return CommonResult.validateFailed("未查询到订单信息");
    	}
		
		// 支付方式：0->未支付；1->支付宝；2->微信；3->线下支付；4->余额支付
		// 支付方式为0才允许支付
		if(order.getPayType() != 0) {
			return CommonResult.validateFailed("订单已支付");
		}
		Date date = new Date();
		DmsOfflinePaymentRecord paymentRecord = new DmsOfflinePaymentRecord();
		paymentRecord.setSellerBankAccountId(1);
		paymentRecord.setMemberId(order.getMemberId());
		paymentRecord.setOrderId(order.getId());
		paymentRecord.setOrderSn(order.getOrderSn());
		paymentRecord.setPayAmount(order.getPayAmount());
		paymentRecord.setPaymentAccountName(paymentParam.getPaymentAccountName());
		paymentRecord.setPaymentBankName(paymentParam.getPaymentBankName());
		paymentRecord.setPaymentBankCardNum(paymentParam.getPaymentBankCardNum());
		//确认状态：0->未确认；1->已确认
		paymentRecord.setConfirmStatus(0);
		paymentRecord.setConfirmTime(null);
		paymentRecord.setCreateTime(date);
		
		order.setPayType(3); //线下支付
		order.setModifyTime(date);
		offlinePaymentRecordMapper.insert(paymentRecord);
		orderMapper.updateByPrimaryKey(order);
		
		return CommonResult.success(null);
	}

	@Transactional
	@Override
	public CommonResult deleteOrder(Long orderId) {
		OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
    	if(order == null) {
    		return CommonResult.validateFailed("未查询到订单信息");
    	}
    	UmsMember currentMember = memberService.getCurrentMember();
    	if(!order.getMemberId().equals(currentMember.getId())) {
    		return CommonResult.validateFailed("未查询到订单信息");
    	}
    	
    	if(order.getStatus() == 3 || order.getStatus() == 4 || order.getStatus() == 5) {
    		//删除状态：0->未删除；1->已删除
    		order.setDeleteStatus(1);
    		order.setModifyTime(new Date());
    		orderMapper.updateByPrimaryKey(order);
    	}
    	
    	return CommonResult.success(null);
	}

	@Transactional
	@Override
	public CommonResult getLogistics(Long orderId) {
		LogisticsResult result = new LogisticsResult();
		OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
    	if(order == null) {
    		return CommonResult.validateFailed("未查询到订单信息");
    	}
    	UmsMember currentMember = memberService.getCurrentMember();
    	if(!order.getMemberId().equals(currentMember.getId())) {
    		return CommonResult.validateFailed("未查询到订单信息");
    	}
		
		if(!StringUtils.isEmpty(order.getDeliverySn())) {
			OmsExpressCompany company = expressCompanyMapper.selectOneByName(order.getDeliveryCompany());
			if(company != null) {
				Map<String, String> param = new HashMap<>();
				param.put("com", company.getCode());
				param.put("num", order.getDeliverySn());
				
			    String paramJson = new Gson().toJson(param);
			    
			    String sign = MD5Util.MD5Encode(paramJson + KUAIDI100_KEY + KUAIDI100_CUSTOMER, "utf-8").toUpperCase();
			    HashMap<String, String> params = new HashMap<>();
			    params.put("param", paramJson);
			    params.put("sign", sign);
			    params.put("customer", KUAIDI100_CUSTOMER);
			    
			    String url = KUAIDI100_URL + "?param=" + paramJson + "&sign=" + sign + "&customer=" + KUAIDI100_CUSTOMER;
			    URI uri = UriComponentsBuilder.fromHttpUrl(url).build().encode(Charset.forName("UTF-8")).toUri();
			    ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
			    Map<String, Object> object = new Gson().fromJson(response.getBody(), HashMap.class);
			    if("ok".equals(String.valueOf(object.get("message")))) {
			    	//快递单当前状态，包括0在途，1揽收，2疑难，3签收，4退签，5派件，6退回等7个状态
			    	String state = String.valueOf(object.get("state"));
			    	result.setData(object.get("data"));
			    	result.setState(state);
			    	if("0".equals(state)) {
			    		result.setStateName("在途");
			    	} else if("1".equals(state)) {
			    		result.setStateName("揽收");
			    	} else if("2".equals(state)) {
			    		result.setStateName("疑难");
			    	} else if("3".equals(state)) {
			    		result.setStateName("签收");
			    	} else if("4".equals(state)) {
			    		result.setStateName("退签");
			    	} else if("5".equals(state)) {
			    		result.setStateName("派件");
			    	} else {
			    		result.setStateName("退回");
			    	}
			    	return CommonResult.success(result);
			    } else {
			    	return CommonResult.failed(String.valueOf(object.get("message")));
			    }
			}
		}
		return CommonResult.failed("请耐心等待商家发货");
	}

	@Transactional
	@Override
	public CommonResult confirmReceiving(Long orderId) {
		
		OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
    	if(order == null) {
    		return CommonResult.validateFailed("未查询到订单信息");
    	}
    	UmsMember currentMember = memberService.getCurrentMember();
    	if(!order.getMemberId().equals(currentMember.getId())) {
    		return CommonResult.validateFailed("未查询到订单信息");
    	}
    	
    	//提货方式：0->自提；1->物流
    	if(order.getDeliveryType() == 1) {
    		//确认收货状态：0->未确认；1->已确认
        	order.setConfirmStatus(1); //已确认
        	
        	//订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        	order.setStatus(3); //已完成
        	Date date = new Date();
        	order.setReceiveTime(date);
        	order.setModifyTime(date);
        	orderMapper.updateByPrimaryKey(order);
        	
        	//写入订单历史操作日志
			OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(orderId);
            history.setCreateTime(date);
            history.setOperateMan("会员");
            
            //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
            history.setOrderStatus(3);
            history.setNote("完成确认收货");
            orderOperateHistoryMapper.insert(history);

			/**
			 * 开始计算会员提成比例
			 */
			memberCommissionService.computeCommission(order, currentMember);
        	
    	}
    	
		return CommonResult.success(null, "确认收货成功");
	}

	@Override
	public CommonResult balancePayment(Long orderId) {
		
		OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
    	if(order == null) {
    		return CommonResult.validateFailed("未查询到订单信息");
    	}
    	UmsMember currentMember = memberService.getCurrentMember();
    	if(!order.getMemberId().equals(currentMember.getId())) {
    		return CommonResult.validateFailed("未查询到订单信息");
    	}
    	
    	// 支付方式：0->未支付；1->支付宝；2->微信；3->线下支付；4->余额支付
		// 支付方式为0才允许支付
		if(order.getPayType() != 0) {
			return CommonResult.validateFailed("订单已支付");
		}
		
		UmsMember member = memberMapper.selectByPrimaryKey(currentMember.getId());
		
		//如果实际支付金额等于0表示积分支付
		//如果不是使用积分支付，返回错误信息
		BigDecimal zero = new BigDecimal(0);
		int flag = order.getPayAmount().compareTo(zero);
		//flag = -1,表示PayAmount小于zero；flag = 0,表示PayAmount等于zero；flag = 1,表示PayAmount大于zero；
		if(flag == 0) {
			
			//写入会员交易记录表
			DmsMemberTradeRecord tradeRecord = new DmsMemberTradeRecord();
			tradeRecord.setMemberId(member.getId());
			tradeRecord.setItemType(ItemType.IntegralShopping); //积分购物
			tradeRecord.setNote("积分抵扣");
			tradeRecord.setTitle("积分抵扣");
			tradeRecord.setValue(order.getIntegrationAmount());
			tradeRecord.setType(1); //收支类型：0->收入；1->支出
			tradeRecord.setCreateTime(new Date());
			memberTradeRecordMapper.insert(tradeRecord);
			
			while(true) {
				long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
				if(redisLock.lock(String.valueOf(member.getId()), String.valueOf(time))) {
					member = memberMapper.selectByPrimaryKey(member.getId());
					member.setFreeze(member.getFreeze().add(order.getIntegrationAmount())); //修改冻结金额,增加冻结资金
					memberMapper.updateByPrimaryKey(member);
					redisLock.unlock(String.valueOf(member.getId()), String.valueOf(time));
					break;
				}
			}
			
		} else {
			return CommonResult.validateFailed("无效订单");
		}
		
		Date date = new Date();
		
		//支付方式：0->未支付；1->支付宝；2->微信；3->线下支付；4->余额支付
		order.setPayType(4);
		
		//提货方式：0->自提；1->物流
		if(order.getDeliveryType() == 0) {
			//订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
			order.setStatus(2);
		} else {
			//订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
			order.setStatus(1);
		}
		
		order.setModifyTime(date);
		order.setPaymentTime(date);
		orderMapper.updateByPrimaryKey(order);
    	
    	//修改商品库存信息需要加锁，影响前台响应，所以用线程来处理
    	executorService.execute(new Runnable() {
			
			@Override
			public void run() {
				//库存变动
				//查询订单商品项
				OmsOrderItemExample example = new OmsOrderItemExample();
				example.createCriteria().andOrderIdEqualTo(order.getId());
				List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(example);
				PmsSkuStock skuStock = null;
				PmsProduct product = null;
				for(OmsOrderItem orderItem : orderItemList) {
					while(true) {
						long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
						if(redisLock.lock(orderItem.getProductId().toString(), String.valueOf(time))) {
							skuStock = skuStockMapper.selectByPrimaryKey(orderItem.getProductSkuId());
							if(skuStock != null) {
								skuStock.setLockStock(skuStock.getLockStock() - orderItem.getProductQuantity());
								skuStock.setStock(skuStock.getStock() - orderItem.getProductQuantity());
								skuStock.setSale((skuStock.getSale() == null ? 0 : skuStock.getSale()) + orderItem.getProductQuantity());
								skuStockMapper.updateByPrimaryKey(skuStock);
							}
							
							product = productMapper.selectByPrimaryKey(orderItem.getProductId());
							if(product != null) {
								product.setStock(product.getStock() - orderItem.getProductQuantity());
								product.setSale((product.getSale() == null ? 0 : product.getSale()) + orderItem.getProductQuantity());
								productMapper.updateByPrimaryKey(product);
							}
							redisLock.unlock(orderItem.getProductId().toString(), String.valueOf(time));
							break;
						}
					}
				}
			}
		});
    	
        boolean distributionFlag = true;
    	OmsOrderItemExample example = new OmsOrderItemExample();
		example.createCriteria().andOrderIdEqualTo(order.getId());
		List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(example);
		PmsProduct product = null;
		for(OmsOrderItem orderItem : orderItemList) {
			product = productMapper.selectByPrimaryKey(orderItem.getProductId());
			if(product.getDistributionFlag().equals(0)) { //分销标志（0->不参与；1->参与）
				distributionFlag = false;
			}
		}
    	
		//分销处理
		if(distributionFlag) {
			distributeSender.sendMessage(order.getId());
		}
    	
		return CommonResult.success(null, "支付成功");
	}

	/**
     * 微信预支付
     * @param orderId
     * @return
     */
	@Override
	public CommonResult<Map<String, String>> wxPrePay(Long orderId) {
		
		OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
    	if(order == null || order.getDeleteStatus().equals(1)) {
    		return CommonResult.validateFailed("未查询到订单信息");
    	}
    	UmsMember currentMember = memberService.getCurrentMember();
    	if(!order.getMemberId().equals(currentMember.getId())) {
    		return CommonResult.validateFailed("未查询到订单信息");
    	}
    	
    	Map<String, String> resultMap = new HashMap<>();
    	// 支付方式：0->未支付；1->支付宝；2->微信；3->线下支付；4->余额支付
		// 支付方式为0才允许支付
		if(order.getPayType() == 0) {
			
			//如果实际支付金额大于0，调用微信预支付接口
			BigDecimal zero = new BigDecimal(0);
			int flag = order.getPayAmount().compareTo(zero);
			//flag = -1,表示PayAmount小于zero；flag = 0,表示PayAmount等于zero；flag = 1,表示PayAmount大于zero；
			if(flag == 1) {
				
				try {
					WxPayTradeDto tradeDto = new WxPayTradeDto();
					tradeDto.setBody("森态空气");
					tradeDto.setOutTradeNo(order.getOrderSn());
					Double totalFree = order.getPayAmount().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;  
					tradeDto.setTotalFee(String.valueOf(totalFree.intValue()));
					tradeDto.setOpenId(currentMember.getUsername());
					resultMap = wxPay(tradeDto, WECHAT_PAY_PAY_CALLBACK_URL);
					resultMap.put("orderId", String.valueOf(order.getId()));
					
					return CommonResult.success(resultMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
			
			
		} else {
			return CommonResult.validateFailed("订单状态无效");
		}
		return CommonResult.failed("调用微信支付失败");
		
	}



	@Override
	public String toAlipayWeb(Long orderId) {

		OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
		// 支付方式为1才允许支付
		if(order != null && order.getPayType() == 1) {

			//如果实际支付金额大于0，调用支付接口
			//flag = -1,表示PayAmount小于zero；flag = 0,表示PayAmount等于zero；flag = 1,表示PayAmount大于zero；
			if (order.getPayAmount().compareTo(BigDecimal.ZERO) == 1) {

					AlipayPayTradeDto tradeDto = new AlipayPayTradeDto();
					tradeDto.setSubject("订单号:"+order.getOrderSn());
					tradeDto.setOutTradeNo(order.getOrderSn());
					Double totalFree = order.getPayAmount().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
					tradeDto.setTotalFee(String.valueOf(totalFree.intValue()));

					return alipayService.createPayment(tradeDto);

			}
		}
		return  null;
	}


	private Map<String, String> wxPay(WxPayTradeDto tradeDto, String notifyUrl) throws Exception {
        MyConfig config = new MyConfig(WECHAT_APPID, WECHAT_PAY_MCHID, WECHAT_PAY_KEY);
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<>();
        data.put("appid", config.getAppID());
        data.put("mch_id", config.getMchID());
        data.put("body", tradeDto.getBody());
        data.put("out_trade_no", tradeDto.getOutTradeNo());
        //data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", tradeDto.getTotalFee());
        data.put("spbill_create_ip", "127.0.0.1");
        data.put("notify_url", notifyUrl);
        data.put("trade_type", "JSAPI");
        data.put("openid", tradeDto.getOpenId());
        data.put("nonce_str", WXPayUtil.generateNonceStr());
        String sign = WXPayUtil.generateSignature(data, config.getKey());
        data.put("sign", sign);

        Map<String, String> resp = wxpay.unifiedOrder(data);
        if ("SUCCESS".equals(resp.get("return_code"))) {
            //再次签名
            /** 重要的事情说三遍  小程序支付 所有的字段必须大写 驼峰模式 严格按照小程序支付文档
             * https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3#
             **/
            Map<String, String> reData = new HashMap<>();
            reData.put("appId", config.getAppID());
            reData.put("nonceStr", resp.get("nonce_str"));
            String newPackage = "prepay_id=" + resp.get("prepay_id");
            reData.put("package", newPackage);
            reData.put("signType", "MD5");
            reData.put("timeStamp", String.valueOf(WXPayUtil.getCurrentTimestamp()));

            Map<String, String> result = new HashMap<>();
            String newSign = WXPayUtil.generateSignature(reData, config.getKey());
            result.put("paySign", newSign);
            result.put("package", newPackage);
            result.put("appid", config.getAppID());
            result.put("nonceStr", reData.get("nonceStr"));
            result.put("timeStamp", reData.get("timeStamp"));
            return result;
        } else {
            throw new RuntimeException(resp.get("return_msg"));
        }

    }

	/**
	 * 微信支付成功回调方法
	 * @param request
	 * @param response
	 */
	@Override
	public void wxPayCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		LOGGER.info("================================================开始处理微信小程序发送的支付成功异步通知");
		 
		InputStream inputStream = request.getInputStream();
        //获取请求输入流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1){
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        inputStream.close();
        
        Map<String, String> map = WXPayUtil.xmlToMap(new String(outputStream.toByteArray()));
        LOGGER.info("【小程序支付回调】 回调数据： \n" + map);
        String resXml = "";
        String returnCode = (String) map.get("return_code");
        if ("SUCCESS".equalsIgnoreCase(returnCode)) {
            String resultCode = (String) map.get("result_code");
            if("SUCCESS".equals(resultCode)){
            	
            	//验证签名
            	boolean signatureFlag = WXPayUtil.isSignatureValid(map, WECHAT_PAY_KEY);
            	if(signatureFlag) {
            		String orderSn = map.get("out_trade_no");
            		OmsOrderExample example = new OmsOrderExample();
            		example.createCriteria().andOrderSnEqualTo(orderSn);
            		List<OmsOrder> list = orderMapper.selectByExample(example);
            		if(list != null && list.size() > 0) {
            			OmsOrder order = list.get(0);
            			//订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
            			if(order != null && order.getStatus() == 0) {

							Date date = new Date();
							//提货方式：0->自提；1->物流
							if(order.getDeliveryType() == 0) {
								order.setStatus(2); //已发货
							} else {
								order.setStatus(1); //待发货
							}
							//支付方式：0->未支付；1->支付宝；2->微信；3->线下支付
							order.setPayType(2); //微信
							order.setModifyTime(date);
							order.setPaymentTime(date);
							orderMapper.updateByPrimaryKey(order);

							BigDecimal zero = new BigDecimal(0);
							int flag = order.getIntegrationAmount().compareTo(zero);
							UmsMember member = memberMapper.selectByPrimaryKey(order.getMemberId());

							//flag = -1,表示IntegrationAmount小于zero；flag = 0,表示IntegrationAmount等于zero；flag = 1,表示IntegrationAmount大于zero；
							if(flag == 1) {

								//写入会员交易记录表
								DmsMemberTradeRecord tradeRecord = new DmsMemberTradeRecord();
								tradeRecord.setMemberId(member.getId());
								tradeRecord.setItemType(ItemType.IntegralShopping); //积分购物
								tradeRecord.setNote("积分抵扣");
								tradeRecord.setTitle("积分抵扣");
								tradeRecord.setValue(order.getIntegrationAmount());
								tradeRecord.setType(1); //收支类型：0->收入；1->支出
								tradeRecord.setCreateTime(date);
								memberTradeRecordMapper.insert(tradeRecord);

								while(true) {
									long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
									if(redisLock.lock(String.valueOf(member.getId()), String.valueOf(time))) {
										member = memberMapper.selectByPrimaryKey(member.getId());
										member.setFreeze(member.getFreeze().subtract(order.getIntegrationAmount())); //修改冻结值
										memberMapper.updateByPrimaryKey(member);
										redisLock.unlock(String.valueOf(member.getId()), String.valueOf(time));
										break;
									}
								}

							}

            				//修改商品库存信息需要加锁，影响前台响应，所以用线程来处理
            				executorService.execute(new Runnable() {
            					
            					@Override
            					public void run() {
            						//库存变动
            						//查询订单商品项
            						OmsOrderItemExample example = new OmsOrderItemExample();
            						example.createCriteria().andOrderIdEqualTo(order.getId());
            						
            						List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(example);
            						PmsSkuStock skuStock = null;
            						PmsProduct product = null;
            						for(OmsOrderItem orderItem : orderItemList) {
            							while(true) {
            								long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
            								if(redisLock.lock(orderItem.getProductId().toString(), String.valueOf(time))) {
            									skuStock = skuStockMapper.selectByPrimaryKey(orderItem.getProductSkuId());
            									if(skuStock != null) {
            										skuStock.setLockStock(skuStock.getLockStock() - orderItem.getProductQuantity());
            										skuStock.setStock(skuStock.getStock() - orderItem.getProductQuantity());
            										skuStock.setSale((skuStock.getSale() == null ? 0 : skuStock.getSale()) + orderItem.getProductQuantity());
            										skuStockMapper.updateByPrimaryKey(skuStock);
            									}
            									
            									product = productMapper.selectByPrimaryKey(orderItem.getProductId());
            									if(product != null) {
            										product.setStock(product.getStock() - orderItem.getProductQuantity());
            										product.setSale((product.getSale() == null ? 0 : product.getSale()) + orderItem.getProductQuantity());
            										productMapper.updateByPrimaryKey(product);
            									}
            									redisLock.unlock(orderItem.getProductId().toString(), String.valueOf(time));
            									break;
            								}
            							}
            						}
            					}
            				});
            				
            				boolean distributionFlag = true;
            		    	OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
            		    	orderItemExample.createCriteria().andOrderIdEqualTo(order.getId());
            				List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
            				PmsProduct product = null;
            				for(OmsOrderItem orderItem : orderItemList) {
            					product = productMapper.selectByPrimaryKey(orderItem.getProductId());
            					if(product.getDistributionFlag().equals(0)) { //分销标志（0->不参与；1->参与）
            						distributionFlag = false;
            					}
            				}
            		    	
            				//分销处理
            				if(distributionFlag) {
            					distributeSender.sendMessage(order.getId());
            				}
            				
            			}
            		}
            		//支付成功
                    resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            	} else {
            		LOGGER.info("签名验证失败");
            	}
               
            }else{
                resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]></return_msg></xml>";
                LOGGER.info("支付失败:"+resXml);
            }
        }else{
            resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]></return_msg></xml>";
            LOGGER.info("【订单支付失败】");
        }
        
        LOGGER.info("【小程序支付回调响应】 响应内容：\n"+resXml);
        response.getWriter().print(resXml);
		
	}


	@Value("${alipay.alipayPublicKey}")
	private String alipayPublicKey;

	@Value("${alipay.charset}")
	private String charset;

	@Value("${alipay.signType}")
	private String signType;

	@Value("${becomeVipAmount}")
	private String becomeVipAmount;


	@Override
	public void alipayCallback(Map<String, String> params) {
		LOGGER.info("============开始处理支付宝的支付异步通知 接收到参数 {}", JSONUtil.toJsonStr(params));
		// 验证签名
		boolean verifyResult;
		try {
			verifyResult = AlipaySignature.rsaCheckV1(params, alipayPublicKey, charset, signType);

			if (verifyResult) {
				// 签名验证通过
				String tradeStatus = params.get("trade_status");
				String outTradeNo = params.get("out_trade_no");
				if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
					// 处理支付成功的业务逻辑
					OmsOrderExample example = new OmsOrderExample();
					example.createCriteria().andOrderSnEqualTo(outTradeNo);
					List<OmsOrder> list = orderMapper.selectByExample(example);
					if(list != null && list.size() > 0) {
						OmsOrder order = list.get(0);
						//订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
						if (order != null && order.getStatus() == 0) {
							//  更新订单状态
							this.updateOderAndMemberInfo(order);
						}
					}
				}
			}

		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
	}

	private void updateOderAndMemberInfo(OmsOrder order) {

		Date date = new Date();
		//提货方式：0->自提；1->物流
		if(order.getDeliveryType() == 0) {
			order.setStatus(2); //已发货
		} else {
			order.setStatus(1); //待发货
		}
		//支付方式：0->未支付；1->支付宝；2->微信；3->线下支付
		order.setPayType(1);
		order.setModifyTime(date);
		order.setPaymentTime(date);
		orderMapper.updateByPrimaryKey(order);

		//新增用户位普通用户，订单支付成功后满一定金额，成为vip普通会员

		UmsMember member = memberMapper.selectByPrimaryKey(order.getMemberId());
		//普通用户
		if(member.getMemberLevel().equals(MemberLevel.Member) ){
			/**
			 * 当前订单金额 大于等于 vip门槛金额
			 */
			if(order.getPayAmount().compareTo(new BigDecimal(becomeVipAmount)) >= 0 ){
				member.setMemberLevel(MemberLevel.Consumer);
				memberMapper.updateByPrimaryKey(member);
			}
//			else {
//				/**
//				 * 	订单统计累计
//				 */
//				OmsOrderExample example = new OmsOrderExample();
//				example.createCriteria().andMemberIdEqualTo(order.getMemberId()).andStatusEqualTo(3);
//				List<OmsOrder> list = orderMapper.selectByExample(example);
//				if(list != null && !list.isEmpty()){
//					BigDecimal totalAmount = list.stream().map(OmsOrder::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
//					totalAmount = totalAmount.add(order.getPayAmount());
//					if(totalAmount.compareTo(vipAmount) >= 0 ){
//						member.setMemberLevel(MemberLevel.Partner);
//						memberMapper.updateByPrimaryKey(member);
//					}
//				}
//			}
		}

	}


}
