/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.finance.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.common.cache.ParamCache;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.modules.api.request.OrderCommonSaveRequest;
import org.springblade.modules.api.request.OrderConsignRandomRequest;
import org.springblade.modules.api.request.OrderGoodsSaveRequest;
import org.springblade.modules.api.request.OrderTakeRequest;
import org.springblade.modules.api.response.ConsignResponse;
import org.springblade.modules.finance.entity.Order;
import org.springblade.modules.finance.entity.OrderConsign;
import org.springblade.modules.finance.entity.OrderGoods;
import org.springblade.modules.finance.entity.OrderGrant;
import org.springblade.modules.finance.mapper.OrderConsignMapper;
import org.springblade.modules.finance.mapper.OrderGrantMapper;
import org.springblade.modules.finance.mapper.OrderMapper;
import org.springblade.modules.finance.service.IOrderService;
import org.springblade.modules.finance.vo.OrderVO;
import org.springblade.modules.platform.entity.UserScores;
import org.springblade.modules.platform.entity.UserTicket;
import org.springblade.modules.platform.mapper.UserScoresMapper;
import org.springblade.modules.platform.service.IUserTicketService;
import org.springblade.modules.shopping.entity.*;
import org.springblade.modules.shopping.mapper.*;
import org.springblade.modules.shopping.wrapper.ConsignWrapper;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserApp;
import org.springblade.modules.system.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 订单表 服务实现类
 *
 * @author BladeX
 * @since 2022-02-13
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

	private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private GoodsMapper goodsMapper;

	@Autowired
	private GoodsSpecsMapper goodsSpecsMapper;

	@Autowired
	private SpecItemsMapper specItemsMapper;

	@Autowired
	private ConsignMapper consignMapper;

	@Autowired
	private OrderConsignMapper orderConsignMapper;

	@Autowired
	private ConsignConfigMapper consignConfigMapper;

	@Autowired
	private OrderGrantMapper orderGrantMapper;

	@Autowired
	private UserScoresMapper userScoresMapper;

	@Autowired
	private IUserTicketService userTicketService;

	@Autowired
	private BladeLogger logger;

	@Resource
	private BladeRedis bladeRedis;

	@Override
	public IPage<OrderVO> selectOrderPage(IPage<OrderVO> page, OrderVO order) {
		return page.setRecords(baseMapper.selectOrderPage(page, order));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public  String commonOrderInsert(OrderCommonSaveRequest request, String tenantId) {
		UserApp userApp = new UserApp();
		UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId,request.getUserId()));
		if (query == null){
			throw new ServiceException("请重新登录！");
		}
		if (query.getState() != 1){
			throw new ServiceException("登录账号已冻结！");
		}
		User user = userMapper.selectById(query.getUserId());
		//生成订单号
		String outTradeNo = CommonUtil.genTimeID();
		Order order = new Order();
		order.setTenantId(tenantId);
		if(user != null){
			order.setUserName(request.getReceivingName());
		}
		order.setOutTradeNo(outTradeNo);
		order.setUserId(query.getUserId());
		order.setOrderType(1);//普通订单
		order.setPayFlag(1); //待付款
		order.setPayFee(request.getPayFee());
		order.setUserAddress(request.getUserAddress());
		order.setTelPhone(request.getTelPhone());
		order.setDistributeMode(request.getDistributeMode());
		order.setDeliveryStaff(request.getDeliveryStaff());
		order.setReceivingName(request.getReceivingName());
		order.setWlPrice(request.getWlPrice());
		Double totalFee = 0.0;
		Double totalTicket = 0.0;
		List<OrderGoodsSaveRequest> goodsList = request.getGoodsList();
		if (goodsList == null || goodsList.size() == 0){
			return "";
		}
		for (OrderGoodsSaveRequest item: goodsList) {
			Goods goods = goodsMapper.selectById(item.getGoodsId());
			if (goods == null){
				throw new ServiceException("商品不存在！");
			}
			if (goods.getIsSale() == 1){
				throw new ServiceException("该商品未上架！");
			}
			if (goods.getGoodsStock() == 0){
				throw new ServiceException("该商品库存不足！");
			}
			OrderGoods orderGoods = new OrderGoods();
			orderGoods.setGoodsImg(goods.getGoodsImg());
			Double goodsPrice = goods.getGoodsPrice();
			Double ticketNum = goods.getTicketNum();
			GoodsSpecs goodsSpecs = goodsSpecsMapper.selectById(item.getGoodsSpecIds());
			if (goodsSpecs != null){
				//获取商品规格数据
				orderGoods.setGoodsPrice(goodsSpecs.getSpecPrice());
				goodsPrice = goodsSpecs.getSpecPrice();
				ticketNum = goodsSpecs.getTicketNum();
				SpecItems specItems = specItemsMapper.selectById(goodsSpecs.getSpecIds());
				if (specItems != null){
					orderGoods.setGoodsSpecNames(specItems.getItemName());
					if(orderGoods.getGoodsImg() != null){
						orderGoods.setGoodsImg(specItems.getItemImg());
					}
				}
			}else{
				//获取商品规格数据
				orderGoods.setGoodsPrice(goods.getGoodsPrice());
				ticketNum = goods.getGoodsPrice();
				orderGoods.setGoodsSpecNames(goods.getGoodsName());
				orderGoods.setGoodsImg(goods.getGoodsImg());
			}
			orderGoods.setOutTradeNo(outTradeNo);
			orderGoods.setGoodsImg(goods.getGoodsImg());
			orderGoods.setGoodsName(goods.getGoodsName());
			orderGoods.setGoodsNum(item.getGoodsNum());
			orderGoods.setGoodsSpecIds(item.getGoodsSpecIds());
			orderGoods.setTicketVal(goods.getTicketNum());
			Double specPrice = NumberUtil.toDouble(NumberUtil.mul(goodsPrice, item.getGoodsNum()));
			totalFee = NumberUtil.add(totalFee, specPrice);
			Double specTicket = NumberUtil.toDouble(NumberUtil.mul(ticketNum, item.getGoodsNum()));
			totalTicket = NumberUtil.add(totalTicket, specTicket);
			boolean flg = orderGoods.insert();
			if (!flg){
				throw new ServiceException("操作失败！");
			}
		};
		order.setTotalFee(totalFee);
		order.setTotalTicket(totalTicket);
		int i = baseMapper.insert(order);
		if (i != 1){
			throw new ServiceException("操作失败！");
		}
		return outTradeNo;

	}

	@Override
	public boolean consignSelfTake(OrderTakeRequest request) {
		Consign consign = consignMapper.selectById(request.getConsignId());
		if(consign != null
			&& Objects.equals(consign.getConsignUserId(), request.getUserId())
			&& consign.getOrderId() != null){
			Order order = baseMapper.selectById(consign.getOrderId());
			if (order != null){
				Order param = new Order();
				param.setId(order.getId());
				param.setPayFlag(3); //待收货
				param.setSendTime(DateUtil.now());
				int i = baseMapper.updateById(order);
				return i == 1;
			}
		}
		return false;
	}

	/**
	 * 1 生成订单
	 * 2 调用确认接口----统一收单接口
	 * 3 你收到支付宝的回调----去打款（商户给用户打款.）、
	 * 4 打款完成----去改变 （订单表---单个抢购订单状态--完成--寄售中）
	 * 4.1 去改变（ 预授单表）  ---1 单----stauts --2
	 *   ------------------------5 单--- num --5 -1 4
	 * 5 返回数给前端app  ---同时告诉app  用户是需要再次做预授
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String consignOrderInsert(OrderConsignRandomRequest request, UserApp userApp, String tenantId) {
		/************************************用户寄售单处理-开始**************************************/
		//优先获取用户寄售单
		Consign consign = consignMapper.randomConsign(request.getConsignConfigId(), request.getUserId());
		boolean flag = true;
		//循环获取用户订单，判断当前订单是否已经抢到了，如果抢到了那么就换一单
		while (flag){
			//判断用户寄售单是否为空
			if(ObjectUtil.isNotNull(consign)){
				//通过寄售id获取redis是否为空
				Object o = bladeRedis.get(String.valueOf(consign.getId()));
				if(ObjectUtil.isNull(o)){//判断redis中是否有其他人在使用
					//将当前订单号放入redis中，防止其他用户抢到同一单号
					bladeRedis.setEx(String.valueOf(consign.getId()), Integer.parseInt("1"), 30L);
					flag = false;//跳出循环，使用当前单号来进行订单创建
				}else{//如果存在则重新获取订单进行创建
					consign = consignMapper.randomConsign(request.getConsignConfigId(),request.getUserId());
				}
			}else{//如果用户寄售单为空那么跳出当前循环重新获取平台单
				flag = false;
			}
		}
		/************************************用户寄售单处理-结束**************************************/
		/************************************平台单单处理-开始**************************************/
		if(ObjectUtil.isNull(consign)){//当没有获取到用户寄售单时进入品台单获取流程
			consign = consignMapper.platformConsign(request.getConsignConfigId(), request.getConsignId());
			//数据量判断
			if (ObjectUtil.isNull(consign)){
				throw new ServiceException("亲，好物已抢完欢迎再来！");
			}
		}
		/************************************平台单单处理-结束**************************************/
		//为交割的寄售商品没有选择提货
		if (consign.getIsDelivery() == 0){
			throw new ServiceException("寄售商品未交割！");
		}
		//扣除用户绿色积分 添加明细
		//寄售金额 * 3% =  绿色积分的
		Double score = NumberUtil.mul(consign.getConsignPrice(), Double.valueOf(0.03));
		Double ratioTicket = NumberUtil.roundDown(score , 2).doubleValue();
		//用户当前积分数必须 大于 抢购的3%的积分数
		if(userApp.getTicket() < ratioTicket){
			throw new ServiceException("亲，您的绿色积分达不到进货条件！");
		}
		//查询商品信息
		Goods goods = goodsMapper.selectById(consign.getGoodsId());
		if (ObjectUtil.isNull(goods)){
			throw new ServiceException("商品不存在！");
		}
		User user = userMapper.selectById(request.getUserId());
		String outTradeNo = CommonUtil.genTimeID();
		boolean flg = createOrder(userApp, user,request,consign,tenantId,goods,score,ratioTicket,outTradeNo);
		if (flg){
			return outTradeNo;
		}
		return "";
	}

	/**
	 * 1、创建订单
	 * 2、创建订单详情
	 * 3、创建寄售订单
	 * 4、修改用户积分
	 * 5、添加积分明细
	 * @return boolean
	 */
	private boolean createOrder(UserApp userApp,
								User user,
								OrderConsignRandomRequest request,
								Consign consign,
								String tenantId,
								Goods goods,
								Double score,
								Double ratioTicket,
								String outTradeNo){
		//创建订单号
		Order order = new Order();
		order.setTenantId(tenantId);
		if(user != null){
			order.setUserName(user.getName());
		}
		order.setOutTradeNo(outTradeNo);
		order.setUserId(request.getUserId());
		order.setOrderType(3);//寄售订单
		order.setPayFlag(4); //寄售订单 变为已完成
		order.setPayFee(consign.getConsignPrice());
		order.setTotalFee(consign.getConsignPrice());
		order.setUserAddress(request.getUserAddress());
		order.setTelPhone(request.getTelPhone());
		order.setDistributeMode(2);//默认物流配送
		order.setDeliveryStaff("物流配送");
		order.setReceivingName(request.getReceivingName());
		order.setOrderState(1); //支付订单状态 发起中
		int i = baseMapper.insert(order);
		if (i == 1){
			//订单详情数据
			OrderGoods orderGoods = new OrderGoods();
			orderGoods.setOutTradeNo(outTradeNo);
			orderGoods.setGoodsImg(goods.getGoodsImg());
			orderGoods.setGoodsName(goods.getGoodsName());
			orderGoods.setGoodsNum(1);
			orderGoods.setGoodsPrice(consign.getConsignPrice());
			orderGoods.setTicketVal(consign.getConsignPrice());
			boolean flg = orderGoods.insert();
			if (!flg){
				throw new ServiceException("操作失败！");
			}
			//创建寄售订单数据
			OrderConsign orderConsign = new OrderConsign();
			orderConsign.setTotalNum(1);//默认寄售数量为1
			/**
			 * 抢到用户单
			 * 1、更新用户单状态
			 * 2、创建新的用户单
			 */
			Consign updateConsign = new Consign();
			if(consign.getConsignFor() == 2){
				updateConsign.setId(consign.getId());
				updateConsign.setConsignState(2); //待付款
				updateConsign.setConsignType(request.getConsignType());//修改寄售类型（寄售方式）
				updateConsign.setNowStock(0); //当前库存为0
			}else if(consign.getConsignFor() == 1){
				/**
				 * 抢到平台单
				 * 	1、变为待确认状态
				 * 	2、剩余数量为大于1时 寄售状态为还是寄售中 等于1是为已完成
				 * 	3、传新的用户单
				 */
				updateConsign.setId(consign.getId());
				updateConsign.setConsignType(request.getConsignType());
				if (consign.getNowStock() == 1){
					updateConsign.setNowStock(0);
				}else{
					updateConsign.setNowStock(consign.getNowStock() - 1);
				}
				orderConsign.setIsConfirm(5);
			}
			int c =  consignMapper.updateById(updateConsign);
			if (c != 1){
				throw new ServiceException("亲！请重新抢单");
			}
			orderConsign.setConsignId(consign.getId()); //寄售ID
			orderConsign.setOutTradeNo(outTradeNo);
			orderConsign.setGoodsId(consign.getGoodsId());
			orderConsign.setGoodsName(goods.getGoodsName());
			orderConsign.setConsignType(request.getConsignType());
			orderConsign.setPayUserId(request.getUserId()); //支付人
			if(request.getConsignType() == 1){
				orderConsign.setConsignDays(0);
			}else if(request.getConsignType() == 2){
				orderConsign.setConsignDays(consign.getConsignDays());
			}else{
				throw new ServiceException("请求参数错误！");
			}
			orderConsign.setConsignUserId(consign.getConsignUserId());
			orderConsign.setTotalPrice(consign.getConsignPrice());
			orderConsign.setConsignPrice(consign.getConsignPrice());
			int j = orderConsignMapper.insert(orderConsign);
			if(j != 1){
				throw new ServiceException("抢单失败！");
			}
			//更新用户绿色积分并添加明细
			if(user != null){
				Double ticket = NumberUtil.sub(userApp.getTicket() - score).doubleValue();
				//用户减去绿色积分（酒票）
				UserApp param = new UserApp();
				param.setId(userApp.getId());
				param.setTicket(ticket);
				flg = param.updateById();
				if (flg){
					//添加积分明细（酒票） 寄售扣除3%的手续费
					UserTicket userTicket = new UserTicket();
					userTicket.setDataSrc(2);//酒票转让
					userTicket.setServesRatio(0.03);
					userTicket.setTicket(ratioTicket);
					userTicket.setUserId(userApp.getUserId());
					userTicket.setUserTicket(userApp.getTicket());
					userTicket.setTicketType(2);//支出
					userTicket.setCreateTime(DateUtil.now());
					userTicket.setDataId(consign.getId()); //寄售ID
					userTicket.setDataRemarks("进货扣除");
					userTicket.setLastTicket(ticket); //最后酒票数
					userTicketService.save(userTicket);
				}
			}
			//每完成一次进货（+20信誉分）
			UserScores userScores = new UserScores();
			userScores.setUserId(userApp.getUserId());//进货
			int consignScore = Integer.parseInt(ParamCache.getValue(CommonConstant.SCORE_CONSIGN_EVERY_TIME));
			String dataRemarks = "完成进货";
			if (userApp.getCreditScore() >= 500){
				consignScore = Integer.parseInt(ParamCache.getValue(CommonConstant.SCORE_CONSIGN_OVER));
				userScores.setScore(consignScore);
				dataRemarks = "完成进货（500信誉分以上或含有500信誉分）";
			}
			userScores.setScore(consignScore);
			userScores.setDataSrc("2");
			userScores.setDataId(consign.getId()); //进货仓单
			userScores.setDataType(1);
			userScores.setDataRemarks(dataRemarks);
			userScoresMapper.insert(userScores);
			UserApp userAppUpdate = new UserApp();
			userAppUpdate.setId(userApp.getId());
			userAppUpdate.setCreditScore(userApp.getCreditScore() + consignScore);
			userAppUpdate.updateById();
		}
		return true;
	}

	@Override
	public ConsignResponse consignGrant(UserApp query, Long consignConfigId, String orderNo) {
		ConsignResponse response = new ConsignResponse();
		//已抢次数 （可抢订单数/日）
		Integer count = orderConsignMapper.selectUserCount(query.getUserId(), consignConfigId);
		log.info("用户【" + query.getUserId() + "】在场次【" + consignConfigId + "】已抢购次数为：" + count);
		OrderGrant orderGrant = orderGrantMapper.selectOne(Wrappers.<OrderGrant>lambdaQuery().eq(OrderGrant::getOrderNo, orderNo));
		log.info("用户【" + query.getUserId() + "】授权数据:" + orderGrant);
		//是特殊账号的不判断的抢购次数
		log.info("用户【" + query.getUserId() + "】为普通用户，判断信誉积分数据");
		if (query.getEnableAuth() != 2){
			double k = (double)query.getCreditScore() / 100; //可抢次数
			int scoreCount = NumberUtil.roundDown(k, 2).intValue();
			int consignCount = Integer.parseInt(ParamCache.getValue(CommonConstant.DEFAULT_CONDIGN_COUNT));
			//最多只能抢次数
			if (scoreCount > consignCount){
				scoreCount = consignCount;
			}
			log.info("用户【" + query.getUserId() + "】为信誉分可抢次数为：" + scoreCount);
			int num = scoreCount - count;
			if (num <= 0){
				response.setStatus(3);//已抢购完成
				response.setNum(0);
				return response;
			}
		}
		if (orderGrant != null){
			//已解冻 则该账单已支付完成
			if (orderGrant.getStatus() == 2){
				response.setStatus(1);//未授权
				response.setNum(0); //剩余已授权的次数
				return response;
			}
			List<Order> list = baseMapper.selectList(Wrappers.<Order>lambdaQuery().in(Order::getGrantNo, orderNo));
			log.info("用户【" + query.getUserId() + "】授权订单号【" + orderNo +"】已授权的关联的订单数为：" + list.size());
			log.info("用户【" + query.getUserId() + "】授权订单号【" + orderNo +"】的数量：" + orderGrant.getNum());
			//如果剩余次数为大于等于1
			// 订单表
			if(list.size() < orderGrant.getNum()){
				response.setStatus(2);//已授权
				response.setNum(orderGrant.getNowNum()); //剩余已授权的次数
				return response;
			}
		}
		response.setStatus(1);//未授权
		response.setNum(0); //剩余已授权的次数
		return response;
	}

	@Override
	public boolean payCommonSuccess(Order queryOrder, String payCode) {
		String outTradeNo = queryOrder.getOutTradeNo();
		if(queryOrder.getPayFlag() == 2){
			log.info("订单已支付成功，不能重复发起支付！订单号：" + outTradeNo);
			return false;
		}
		//更新订单
		Order order = new Order();
		order.setId(queryOrder.getId());
		order.setPayFlag(2); //待发货
		if(queryOrder.getOrderType() == 3){
			order.setPayFlag(4); //已完成
		}
		order.setOrderState(2);//已付款
		order.setPayTime(DateUtil.now()); //支付时间
		order.setPayCode(payCode); //支付方式
		int i = baseMapper.update(order,Wrappers.<Order>lambdaQuery().eq(Order::getOutTradeNo, outTradeNo));
		if (i != 1){
			logger.error("订单异常", "订单回调失败！订单号：" + outTradeNo);
			return false;
		}
		if (queryOrder.getOrderType() == 1 && queryOrder.getPayFlag() == 1){
			//更新用户数据
			UserApp userApp = new UserApp();
			UserApp queryUserApp = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId,queryOrder.getUserId()));
			if (queryUserApp == null){
				logger.error("订单异常", "获取用户信息失败！订单号：" + outTradeNo);
				return false;
			}
			userApp.setId(queryUserApp.getId());
			Double ticket = NumberUtil.add(queryUserApp.getTicket(), queryOrder.getTotalTicket());
			userApp.setTicket(ticket);
			boolean flg = userApp.updateById();
			if (!flg){
				logger.error("订单异常", "更新用户信息失败！订单号：" + outTradeNo);
				return false;
			}
			UserTicket userTicket = new UserTicket();
			userTicket.setDataSrc(1);//1.订单
			userTicket.setServesRatio(0D);
			userTicket.setTicket(queryOrder.getTotalTicket());
			userTicket.setUserId(queryUserApp.getUserId());
			userTicket.setUserTicket(queryUserApp.getTicket());
			userTicket.setTicketType(1);//收入
			userTicket.setCreateTime(DateUtil.now());
			userTicket.setDataId(queryOrder.getId()); //订单号
			userTicket.setDataRemarks("赠送积分");
			userTicket.setLastTicket(ticket); //最后酒票数
			flg = userTicketService.save(userTicket);
			if (!flg){
				logger.error("订单异常", "用户绿色积分新增错误！订单号：" + outTradeNo);
				return false;
			}
		}
		return true;
	}

	@Override
	public boolean payConsignSuccess(Order queryOrder) {
		String outTradeNo = queryOrder.getOutTradeNo();
		//寄售订单
		if(queryOrder.getOrderType() == 3){
			//选择寄售方式为寄售则生成新的寄售
			OrderConsign query = orderConsignMapper.selectOne(Wrappers.<OrderConsign>lambdaQuery().eq(OrderConsign::getOutTradeNo, outTradeNo));
			if(query == null ){
				logger.error("订单异常", "无订单数据！订单号：" + outTradeNo);
				return false;
			}
			//查询所抢的寄售订单
			Consign queryConsign = consignMapper.selectById(query.getConsignId());
			if(ObjectUtil.isNull(queryConsign)){ //后台的数据为0或者寄售的
				logger.error("订单异常", "寄售无数据！订单号：" + outTradeNo);
				return false;
			}
			//新建寄售单
			ConsignConfig consignConfig = consignConfigMapper.selectById(queryConsign.getConsignConfigId());
			Date startDate = cn.hutool.core.date.DateUtil.offsetDay(consignConfig.getStartTime(), 1);
			Date endDate = cn.hutool.core.date.DateUtil.offsetDay(consignConfig.getEndTime(), 1);
			Consign consign = new Consign();
			consign.setOrderId(queryOrder.getId()); //保存来源的订单ID
			consign.setConsignFor(2);//寄售订单
			consign.setConsignConfigId(queryConsign.getConsignConfigId());
			consign.setConsignDays(query.getConsignDays());
			consign.setConsignUserId(query.getPayUserId());//支付人变为寄售人
			consign.setConsignType(0);//无
			consign.setTotalNum(1);
			consign.setNowStock(1);
			consign.setIsDelivery(1); //是否交割 否
			consign.setIsSale(2); //是否上架 是（自动上架）
			consign.setDeliveryPrice(0d);//默认为0，需要后台设置交割价
			consign.setGoodsId(query.getGoodsId());
			consign.setGoodsName(query.getGoodsName());
			consign.setTitle(query.getGoodsName());
			Double consignPrice = ConsignWrapper.build().consignPrice(query.getConsignPrice(), query.getConsignDays());
			consign.setObtainPrice(query.getConsignPrice()); //取得价为抢购别人的价格
			consign.setConsignPrice(consignPrice);//抢购价
			consign.setStartTime(startDate);
			consign.setEndTime(endDate);
			consign.setSaleDays(0);
			int j = consignMapper.insert(consign);
			if(j != 1){
				logger.error("订单异常", "订单变为寄售失败！订单号：" + outTradeNo);
				throw new ServiceException("亲！请重新抢单");
			}
			//更新寄售状态为已售出
			if(queryConsign.getNowStock() == 0){
				Consign updateConsign = new Consign();
				updateConsign.setId(query.getConsignId());
				updateConsign.setConsignState(3);//已售出
				int k =	consignMapper.updateById(updateConsign);
				if(k != 1){
					logger.error("订单异常", "更新寄售状态！订单号：" + outTradeNo);
					throw new ServiceException("亲！请重新抢单");
				}
			}
		}
		return true;
	}

	@Override
	public boolean orderEnd(Long orderId, Long userId) {
		Order order = baseMapper.selectById(orderId);
		//必须是支付状态为待收货
		if (order.getPayFlag() != 3){
			throw new ServiceException("请等待商家发货!");
		}
		Order param = new Order();
		param.setId(orderId);
		param.setPayFlag(4); //已完成
		param.setRecordTime(DateUtil.now());
		int i = baseMapper.updateById(param);
		return i == 1;
	}




}
