package cn.superdesk.uniorder.service.order.receive.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.superdesk.uniorder.common.enums.common.*;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import cn.superdesk.uniorder.common.numerical.AnStringUtils;
import cn.superdesk.uniorder.common.pagination.PageQueryParam;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderExample;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderGoods;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderUpdate;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterprise;
import cn.superdesk.uniorder.dao.mapper.base.*;
import cn.superdesk.uniorder.dto.param.operation.UnifiedOrderIssuesFlowingParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskappservices.flashdeliver.FlashDeliverOrderGoodsReceiveParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskappservices.flashdeliver.FlashDeliverOrderPatchUnifiedOrderFieldOutVirt;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskappservices.flashdeliver.FlashDeliverOrderReceiveParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskappservices.flashdeliver.FlashDeliverOrderStatusUpdateReceiveParam;
import cn.superdesk.uniorder.event.CommonEventPublisher;
import cn.superdesk.uniorder.service.order.base.CommonMergeOrderCreditProcessService;
import cn.superdesk.uniorder.service.order.base.CommonMergeOrderGoodsProcessService;
import cn.superdesk.uniorder.service.order.base.CommonOrderIncidentalExpensesProcessService;
import cn.superdesk.uniorder.service.order.base.CommonOrderProcessService;
import cn.superdesk.uniorder.service.order.receive.ReceiveFlashDeliverOrderService;
import cn.superdesk.uniorder.service.organisation.SysEnterpriseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: kafka 服务之窗 楼闪送
 * @Author: linjinyu
 * @CreateDate: 2020/12/9 下午1:35
 * @UpdateUser: linjinyu
 * @UpdateDate: 2020/12/9 下午1:35
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class ReceiveFlashDeliverOrderServiceImpl implements ReceiveFlashDeliverOrderService {

	@Autowired
	private UnifiedOrderMapper                   unifiedOrderMapper;
	@Autowired
	private UnifiedOrderMapperEx                 unifiedOrderMapperEx;
	@Autowired
	private UnifiedOrderMapperExSupplierDimOrder unifiedOrderMapperExSupplier;
	@Autowired
	private UnifiedOrderGoodsMapper              unifiedOrderGoodsMapper;
	@Autowired
	private UnifiedOrderGoodsMapperEx            unifiedOrderGoodsMapperEx;


	/****************************************** 楼闪送专用 目前是这样 20200706 ******************************************/
	@Autowired
	private UnifiedOrderUpdateMapper   unifiedOrderUpdateMapper;
	@Autowired
	private UnifiedOrderUpdateMapperEx unifiedOrderUpdateMapperEx;

	/****************************************** 楼闪送专用 目前是这样 20200706 ******************************************/

	@Autowired
	private CommonOrderProcessService                   commonOrderProcessService;
	@Autowired
	private CommonMergeOrderGoodsProcessService         commonOrderGoodsMergeProcessService;
	@Autowired
	private CommonMergeOrderCreditProcessService        commonOrderCreditMergeProcessService;
	//	@Autowired
//	private CommonOrderTransportProcessService   commonOrderTransportProcessService;
	@Autowired
	private CommonOrderIncidentalExpensesProcessService commonOrderIncidentalExpensesProcessService;

	/****************************************** 组织架构 start ******************************************/

	@Autowired
	private SysEnterpriseService sysEnterpriseService;

	@Autowired
	private CommonEventPublisher commonEventPublisher;


	public UnifiedOrderIssuesFlowingParam kafkaFlashdeliverOrderReceive(FlashDeliverOrderReceiveParam receiveParam) {

		UnifiedOrderIssuesFlowingParam callback = new UnifiedOrderIssuesFlowingParam();
		callback.setUid(receiveParam.getUid());
		callback.setProcessResult(CommonProcessResultEnum.正常.getKey());
		callback.setProcessReport("");

		// 如果这个单的价格为 0 为过来还有什么意义呢?
		if (null == receiveParam.getOrderAmount() && receiveParam.getOrderAmount().compareTo(BigDecimal.ZERO) == 0) {
			// TODO 记录 问题单
			callback.setProcessResult(CommonProcessResultEnum.异常_数据本身缺失.getKey());
			callback.setProcessReport("订单金额为空");
			return callback;
		}

		// 如果 这个单 没有商品 直接 返回
		if (AnCollectionUtils.isEmpty(receiveParam.getGoodsList())) {
			// TODO 记录 问题单
			callback.setProcessResult(CommonProcessResultEnum.异常_数据本身缺失.getKey());
			callback.setProcessReport("订单商品为空");
			return callback;
		}


		// 处理订单
		UnifiedOrder unifiedOrderEntity = new UnifiedOrder();
		convertFlashdeliverOrderReceiveParam2Entity(receiveParam, unifiedOrderEntity);


		// 处理订单 商品
		BigDecimal costAmount = new BigDecimal(0);

		List<UnifiedOrderGoods>                  processUnifiedOrderGoodsList           = new ArrayList<>();
		List<FlashDeliverOrderGoodsReceiveParam> flashdeliverOrderReceiveParamGoodsList = receiveParam.getGoodsList();

		for (FlashDeliverOrderGoodsReceiveParam flashdeliverOrderGoodsReceiveParam : flashdeliverOrderReceiveParamGoodsList) {

			UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();

			convertFlashdeliverOrderGoodsReceiveParam2Entity(flashdeliverOrderGoodsReceiveParam, unifiedOrderGoods);

			unifiedOrderGoods.setOrderSn(unifiedOrderEntity.getOrderSn());

			processUnifiedOrderGoodsList.add(unifiedOrderGoods);

		}

		/****************************************** 运费要重构 业务逻辑修改 mark by linjinyu at 20201215 start ******************************************/
		commonOrderIncidentalExpensesProcessService.flashdeliverOrderGoodsProcess(receiveParam, processUnifiedOrderGoodsList);
		/****************************************** 运费要重构 业务逻辑修改 mark by linjinyu at 20201215   end ******************************************/

		/****************************************** TODO 再核算 20210126 拆单 子单 订单金额有可能是不包含运费 start ******************************************/
		commonOrderIncidentalExpensesProcessService.flashdeliverOrderAmountProcess(unifiedOrderEntity, processUnifiedOrderGoodsList);
		/****************************************** TODO 再核算 20210126 拆单 子单 订单金额有可能是不包含运费   end ******************************************/

		// 状态 -1:已关闭,0:待付款,1:待发货,2:待收货,3:已完成
		UnifiedOrder checkExistUnifiedOrder = unifiedOrderMapperEx.findByOrderSn(unifiedOrderEntity.getOrderSn());

		// 不存在就好办了
		if (checkExistUnifiedOrder == null) {

			// 没有商品 不保存订单数据
			if (AnCollectionUtils.isNotEmpty(processUnifiedOrderGoodsList)) {

				// 保存订单数据
				commonOrderProcessService.attachInsert(unifiedOrderEntity);

				for (UnifiedOrderGoods unifiedOrderGoods : processUnifiedOrderGoodsList) {
					unifiedOrderGoodsMapper.insert(unifiedOrderGoods);
				}
			}

		} else {

			unifiedOrderEntity.setId(checkExistUnifiedOrder.getId());//要先set id 在更新

			unifiedOrderEntity.setUpdateTime(DateUtil.date());

			unifiedOrderEntity.setAccountingStateCustomer(checkExistUnifiedOrder.getAccountingStateCustomer());
			unifiedOrderEntity.setAccountingStateSupplier(checkExistUnifiedOrder.getAccountingStateSupplier());

			commonOrderProcessService.attachUpdate(unifiedOrderEntity);


			// 重构 by linjinyu 20200915 start
			commonOrderGoodsMergeProcessService.processUnifiedOrderGoodsBykafkaPushOrderReceive(unifiedOrderEntity, processUnifiedOrderGoodsList, 1);
			// 重构 by linjinyu 20200915   end

		}

		/****************************************** 分润 先屏蔽 start ******************************************/
//		commonEventPublisher.triggerUnifiedOrderProfitCalculationEvent(unifiedOrderEntity);
		/****************************************** 分润 先屏蔽 start ******************************************/


		log.info("##################### kafkaFlashdeliverOrderMergeReceive end #####################");

		return callback;
	}

	private void convertFlashdeliverOrderReceiveParam2Entity(FlashDeliverOrderReceiveParam flashdeliverOrderReceiveParam, UnifiedOrder unifiedOrderEntity) {

		unifiedOrderEntity.setOrderType(CommonOrderTypeEnum.订单.getKey());

		// TODO 设定 订单来源
//		unifiedOrder.setServiceNo(UnifiedServiceEnum.getServiceNo(postOfficeOrderReceiveParam.getOrderType()));
//		unifiedOrder.setServiceName(UnifiedServiceEnum.getServiceName(postOfficeOrderReceiveParam.getOrderType()));
		unifiedOrderEntity.setServiceNo(flashdeliverOrderReceiveParam.getServiceNo());
		unifiedOrderEntity.setServiceName(flashdeliverOrderReceiveParam.getServiceName());

//		unifiedOrder.setOrderId(flashdeliverOrderReceiveParam.getOrderId());// TODO 标记 缺字段
		unifiedOrderEntity.setOrderSn(flashdeliverOrderReceiveParam.getOrderSn());
		unifiedOrderEntity.setOrderSnOutTrade(flashdeliverOrderReceiveParam.getOrderSn());

		unifiedOrderEntity.setAmount(flashdeliverOrderReceiveParam.getOrderAmount());
//		unifiedOrder.setSellingAmount(flashdeliverOrderReceiveParam.getSellingAmount());
		unifiedOrderEntity.setCostAmount(flashdeliverOrderReceiveParam.getCostAmount());

		// 商品-销售总金额
		unifiedOrderEntity.setGoodsAmount(BigDecimal.ZERO);
		// 商品-成本总金额
		unifiedOrderEntity.setGoodsCostAmount(BigDecimal.ZERO);

		unifiedOrderEntity.setTransportAmount(flashdeliverOrderReceiveParam.getTransportAmountVirt());
		unifiedOrderEntity.setTransportMerchantAssumeAmount(flashdeliverOrderReceiveParam.getTransportAmountSale());

//		private BigDecimal packingAmount;//打包费 统一订单待补充字段
//		private BigDecimal saleDeliveryAmount;//商户配送费		 统一订单待补充字段
//		private BigDecimal deliveryPersonAmount;//配送员配送费 统一订单待补充字段

//		unifiedOrder.setExpress(flashdeliverOrderReceiveParam.getDispatchType());
		unifiedOrderEntity.setExpressCompany(flashdeliverOrderReceiveParam.getDispatchName());
		unifiedOrderEntity.setExpressSn(flashdeliverOrderReceiveParam.getExpressSn());

		/**************************************** 取传入 start ****************************************/

		unifiedOrderEntity.setPayType(flashdeliverOrderReceiveParam.getPayType());
		unifiedOrderEntity.setPayTypeName(flashdeliverOrderReceiveParam.getPayTypeName());

		unifiedOrderEntity.setPayState(flashdeliverOrderReceiveParam.getPayState());
		unifiedOrderEntity.setPayStateName(flashdeliverOrderReceiveParam.getPayStateName());

		unifiedOrderEntity.setOrderState(flashdeliverOrderReceiveParam.getOrderState());
//		unifiedOrder.setOrderStateName(SuperDeskMallOrderStatusEnum.getDesc(postOfficeOrderReceiveParam.getOrderState()));//		是定义还是 传过来呢？先当是传过来吧
		unifiedOrderEntity.setOrderStateName(flashdeliverOrderReceiveParam.getOrderStateName());

		/**************************************** 取传入 start ****************************************/



		// 业务系统 直接 告诉我 是那种
//		unifiedOrder.setCompletState(UnifiedOrderCompletStateUtils.convertBySuperDeskMallOrderStatus(postOfficeOrderReceiveParam.getOrderState(), postOfficeOrderReceiveParam.getDeleted()));
		unifiedOrderEntity.setCompletState(flashdeliverOrderReceiveParam.getCompletState());


		unifiedOrderEntity.setCreateTime(flashdeliverOrderReceiveParam.getCreateTime());
		unifiedOrderEntity.setCreateUserId(1L);
		unifiedOrderEntity.setPayTime(flashdeliverOrderReceiveParam.getPayTime());
		unifiedOrderEntity.setSendTime(flashdeliverOrderReceiveParam.getSendTime());
		unifiedOrderEntity.setFinishTime(flashdeliverOrderReceiveParam.getFinishTime());

		unifiedOrderEntity.setSaleId(flashdeliverOrderReceiveParam.getSaleId());
		unifiedOrderEntity.setSaleName(flashdeliverOrderReceiveParam.getSaleName());


		unifiedOrderEntity.setProjectId(flashdeliverOrderReceiveParam.getPurchaseOrgId());
		unifiedOrderEntity.setProjectName(flashdeliverOrderReceiveParam.getPurchaseOrgName());


		/****************************************** TODO 游客企业逻辑 mark by linjinyu at 20210708 start ******************************************/


		// TODO 待修复数据 mark by linjinyu at 20210708
//		正在显示第 0-24 行 (共 65420 行, 查询花费 0.0258 秒。)
//		SELECT * FROM `unified_order` WHERE service_no = 'LNSS' AND `purchase_virt_id` IS NULL

//		正在显示第 42250-42267 行 (共 42268 行, 查询花费 0.4649 秒。)
//		SELECT * FROM `unified_order` WHERE service_no = 'LNSS' AND `purchase_virt_id` IS NULL AND `purchase_virt_name` IS NOT NULL

//		正在显示第 0-24 行 (共 43 行, 查询花费 0.4614 秒。)
//		SELECT * FROM `unified_order` WHERE service_no = 'LNSS' AND `purchase_virt_id` IS NULL AND `purchase_virt_name` !=''

//		【后端开发中-楼闪送游客订单同步到统一订单加上虚拟企业】 https://www.tapd.cn/33003868/prong/stories/view/1133003868001002481

		if (null == flashdeliverOrderReceiveParam.getPurchaseVirtId()) {

			SysEnterprise touchObj = sysEnterpriseService.touchByOutOrgId(flashdeliverOrderReceiveParam.getPurchaseOrgId());
			unifiedOrderEntity.setPurchaseVirtId(touchObj.getEnterpriseId());
			unifiedOrderEntity.setPurchaseVirtName(touchObj.getEnterpriseName());

		} else {
			unifiedOrderEntity.setPurchaseVirtId(flashdeliverOrderReceiveParam.getPurchaseVirtId());
			unifiedOrderEntity.setPurchaseVirtName(flashdeliverOrderReceiveParam.getPurchaseVirtName());
		}

		/****************************************** TODO 游客企业逻辑 mark by linjinyu at 20210708   end ******************************************/

		unifiedOrderEntity.setPurchaseUserId(flashdeliverOrderReceiveParam.getPurchaseUserId());
		unifiedOrderEntity.setPurchaseUserName(flashdeliverOrderReceiveParam.getPurchaseUserName());
		unifiedOrderEntity.setPurchasePhone(flashdeliverOrderReceiveParam.getPurchasePhone());


		unifiedOrderEntity.setRecAddress(flashdeliverOrderReceiveParam.getRecAddress());
		unifiedOrderEntity.setRecUserId(flashdeliverOrderReceiveParam.getRecUserId());
		unifiedOrderEntity.setRecUserName(flashdeliverOrderReceiveParam.getRecUserName());
		unifiedOrderEntity.setRecUserPhone(flashdeliverOrderReceiveParam.getRecUserPhone());

		// TODO 写死
		unifiedOrderEntity.setSettlementType(2);
		// TODO 写死
		unifiedOrderEntity.setSourceChannel(1);
		// TODO 写死
		unifiedOrderEntity.setAppraiseState(2);

//		Map<String, String> otherParams = new HashMap<>();
//		otherParams.put("sendTime", AnDateHelper.parseDateToStrFormat(flashdeliverOrderReceiveParam.getSendTime(), AnDateHelper.DATE_TIME_STRING));
//		unifiedOrder.setOtherParams(otherParams.toString());


//		unifiedOrder.setRemarks();

		unifiedOrderEntity.setOrderLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
		unifiedOrderEntity.setOrderLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

		unifiedOrderEntity.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
		unifiedOrderEntity.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());

		unifiedOrderEntity.setUpdateTime(DateUtil.date());
		unifiedOrderEntity.setUpdateUserId(1L);

		unifiedOrderEntity.setUserType("2");
		unifiedOrderEntity.setUserName("系统");

	}

	private void convertFlashdeliverOrderGoodsReceiveParam2Entity(FlashDeliverOrderGoodsReceiveParam flashdeliverOrderGoodsReceiveParam, UnifiedOrderGoods unifiedOrderGoods) {

		unifiedOrderGoods.setGoodsId(flashdeliverOrderGoodsReceiveParam.getGoodsId());
		unifiedOrderGoods.setOutSnapshotOrderGoodsId(flashdeliverOrderGoodsReceiveParam.getOutSnapshotOrderGoodsId());

		unifiedOrderGoods.setGoodsType(CommonOrderGoodsTypeEnum.商品.getKey());
		unifiedOrderGoods.setDirection(CommonDirectionEnum.正向.getKey());

		unifiedOrderGoods.setGoodsLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
		unifiedOrderGoods.setGoodsLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

		unifiedOrderGoods.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
		unifiedOrderGoods.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());

		unifiedOrderGoods.setGoodsName(flashdeliverOrderGoodsReceiveParam.getGoodsName());


		unifiedOrderGoods.setGoodsParams(flashdeliverOrderGoodsReceiveParam.getGoodsParams());

		unifiedOrderGoods.setUnit(StrUtil.isBlank(flashdeliverOrderGoodsReceiveParam.getUnit()) ? CommonOrderGoodsUnitEnum.项.getDesc() : flashdeliverOrderGoodsReceiveParam.getUnit());

		// 销售价 单价
		unifiedOrderGoods.setPrice(flashdeliverOrderGoodsReceiveParam.getSellingPrice());
		// 成本价 单价
		unifiedOrderGoods.setCostPrice(flashdeliverOrderGoodsReceiveParam.getCostPrice());
		// 数量
		unifiedOrderGoods.setQuantity(flashdeliverOrderGoodsReceiveParam.getQuantity());


		/************************************** update by linjinjy 20200904 20200723_林志鹏_税率,退款格式.docx **************************************/
		unifiedOrderGoods.setFiscalCode(flashdeliverOrderGoodsReceiveParam.getTaxCode());
		unifiedOrderGoods.setTaxCode(flashdeliverOrderGoodsReceiveParam.getTaxCode());
		unifiedOrderGoods.setTaxRate(flashdeliverOrderGoodsReceiveParam.getTaxRateVirt());

		// 商户税率
		unifiedOrderGoods.setMerchTaxId(0L);
		unifiedOrderGoods.setMerchTaxCode(flashdeliverOrderGoodsReceiveParam.getTaxCode());
		unifiedOrderGoods.setMerchTaxRate(flashdeliverOrderGoodsReceiveParam.getTaxRateSale());

		// 平台税率
		unifiedOrderGoods.setOperationTaxId(0L);
		unifiedOrderGoods.setOperationTaxCode(flashdeliverOrderGoodsReceiveParam.getTaxCode());
		unifiedOrderGoods.setOperationTaxRate(flashdeliverOrderGoodsReceiveParam.getTaxRateVirt());
		/************************************** update by linjinjy 20200904 20200723_林志鹏_税率,退款格式.docx **************************************/

		/****************************************** 三级分类 20200904 by linjinyu 20200904_林志鹏_三极分类 ******************************************/
		unifiedOrderGoods.setCateIdLv1(flashdeliverOrderGoodsReceiveParam.getCateIdLv1());
		unifiedOrderGoods.setCateIdLv2(flashdeliverOrderGoodsReceiveParam.getCateIdLv2());
		unifiedOrderGoods.setCateIdLv3(flashdeliverOrderGoodsReceiveParam.getCateIdLv3());
		unifiedOrderGoods.setCateNameLv1(flashdeliverOrderGoodsReceiveParam.getCateNameLv1());
		unifiedOrderGoods.setCateNameLv2(flashdeliverOrderGoodsReceiveParam.getCateNameLv2());
		unifiedOrderGoods.setCateNameLv3(flashdeliverOrderGoodsReceiveParam.getCateNameLv3());
		/****************************************** 三级分类 20200904 by linjinyu 20200904_林志鹏_三极分类 ******************************************/

		unifiedOrderGoods.setCreateUserId(1L);
		unifiedOrderGoods.setCreateTime(DateUtil.date());
		unifiedOrderGoods.setUpdateUserId(1L);
		unifiedOrderGoods.setUpdateTime(DateUtil.date());
	}

	public void kafkaFlashDeliverOrderReceiveStateUpdate(FlashDeliverOrderStatusUpdateReceiveParam flashdeliverOrderStatusUpdateReceiveParam) {


		String orderSn = flashdeliverOrderStatusUpdateReceiveParam.getOrderSn();

		if (orderSn == null) {
			return;
		}

		UnifiedOrderUpdate unifiedOrderUpdateLog = new UnifiedOrderUpdate();

		unifiedOrderUpdateLog.setCreateTime(DateUtil.date());
		unifiedOrderUpdateLog.setOrderSn(orderSn);

		UnifiedOrder unifiedOrderFromDB = unifiedOrderMapperEx.findByOrderSn(orderSn);

		if (ObjectUtil.isNull(unifiedOrderFromDB)) {
			log.error("楼闪送订单 orderSn {} 更新状态失败, 没有找到对映的订单数据", orderSn);
			return;
		}

		UnifiedOrder unifiedOrder4Update = new UnifiedOrder();
		unifiedOrder4Update.setId(unifiedOrderFromDB.getId());

		if (flashdeliverOrderStatusUpdateReceiveParam.getPayState() != null) {
			unifiedOrderUpdateLog.setPayState(flashdeliverOrderStatusUpdateReceiveParam.getPayState());
			unifiedOrder4Update.setPayState(flashdeliverOrderStatusUpdateReceiveParam.getPayState());
		}

		// TODO 未确认 linjinyu 订单状态 start
		if (flashdeliverOrderStatusUpdateReceiveParam.getOrderState() != null) {
			unifiedOrderUpdateLog.setOrderState(flashdeliverOrderStatusUpdateReceiveParam.getOrderState());
			unifiedOrder4Update.setOrderState(flashdeliverOrderStatusUpdateReceiveParam.getOrderState());
		}

		if (flashdeliverOrderStatusUpdateReceiveParam.getOrderStateName() != null) {
			unifiedOrderUpdateLog.setOrderStateName(flashdeliverOrderStatusUpdateReceiveParam.getOrderStateName());
			unifiedOrder4Update.setOrderStateName(flashdeliverOrderStatusUpdateReceiveParam.getOrderStateName());
		}
		// TODO 未确认 linjinyu 订单状态 end

		if (flashdeliverOrderStatusUpdateReceiveParam.getCompletState() != null) {
			unifiedOrderUpdateLog.setCompletState(flashdeliverOrderStatusUpdateReceiveParam.getCompletState());
			unifiedOrder4Update.setCompletState(flashdeliverOrderStatusUpdateReceiveParam.getCompletState());
		}

		if (flashdeliverOrderStatusUpdateReceiveParam.getFinishTime() != null) {
//			unifiedOrderUpdateLog.set(flashdeliverOrderStatusUpdateReceiveParam.getFinishTime());
			unifiedOrder4Update.setFinishTime(flashdeliverOrderStatusUpdateReceiveParam.getFinishTime());
		}

		unifiedOrder4Update.setUpdateTime(DateUtil.date());

		if (flashdeliverOrderStatusUpdateReceiveParam.getUserName() != null) {
			unifiedOrderUpdateLog.setUserName(flashdeliverOrderStatusUpdateReceiveParam.getUserName());
			unifiedOrder4Update.setUserName(flashdeliverOrderStatusUpdateReceiveParam.getUserName());
		}

		// userType的类型不想动了,转换一下吧
		if (flashdeliverOrderStatusUpdateReceiveParam.getUserType() != null) {
			unifiedOrderUpdateLog.setUserType(AnStringUtils.getString(flashdeliverOrderStatusUpdateReceiveParam.getUserType()));
			unifiedOrder4Update.setUserType(AnStringUtils.getString(flashdeliverOrderStatusUpdateReceiveParam.getUserType()));
		}

		if (flashdeliverOrderStatusUpdateReceiveParam.getUserId() != null) {
			unifiedOrderUpdateLog.setUserId(flashdeliverOrderStatusUpdateReceiveParam.getUserId());
			unifiedOrder4Update.setUpdateUserId(flashdeliverOrderStatusUpdateReceiveParam.getUserId());
		}


		/****************************************** 实现上 kafka 记录上没有这些 start ******************************************/

		// change 0401
//		if (jsonMap.get("purchase_virt") != null && StringUtils.isNotEmpty(jsonMap.get("purchase_virt").toString())) {
//			String[] purchaseVirt = jsonMap.get("purchase_virt").toString().trim().split("_");
//			update.setPurchaseVirtId(Long.parseLong(purchaseVirt[1]));
//			update.setPurchaseVirtName(purchaseVirt[0]);
//		}
//
//		if (jsonMap.get("purchase_user") != null && StringUtils.isNotEmpty(jsonMap.get("purchase_user").toString())) {
//			String[] purchaseUser = jsonMap.get("purchase_user").toString().trim().split("_");
//
//			int length = purchaseUser.length;
//			update.setPurchaseUserId(Long.parseLong(purchaseUser[length-1]));
//			update.setPurchaseUserName(purchaseUser[0]);
//		}
//
//		if (jsonMap.get("sale") != null && StringUtils.isNotEmpty(jsonMap.get("sale").toString())) {
//			String[] sale = jsonMap.get("sale").toString().trim().split("_");
//			update.setSaleId(Long.parseLong(sale[1]));
//			update.setSaleName(sale[0]);
//		}
//
//		if (jsonMap.get("amount") != null && StringUtils.isNotEmpty(jsonMap.get("amount").toString())) {
//			update.setAmount(new BigDecimal(jsonMap.get("amount").toString()));
//		}
//
//		if (jsonMap.get("cost_amount") != null && StringUtils.isNotEmpty(jsonMap.get("cost_amount").toString())) {
//			update.setCostAmount(new BigDecimal(jsonMap.get("cost_amount").toString()));
//		}
//
//		List<UnifiedOrderGoods> unifiedOrderGoodsList = new ArrayList<>();
//
//		if (jsonMap.get("goods") != null) {
//
//			List<UnifiedLnssOrderGoodsAdd> goodAdds = JSONArray.parseArray(jsonMap.get("goods").toString(), UnifiedLnssOrderGoodsAdd.class);
//
//			for (UnifiedLnssOrderGoodsAdd item : goodAdds) {
//
//				UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();
//
//				unifiedOrderGoods.setGoodsType(UnifiedOrderGoodsTypeEnum.商品.getKey());
//				unifiedOrderGoods.setDirection(CommonDirectionEnum.正向.getKey());
//				unifiedOrderGoods.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
//				unifiedOrderGoods.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());
//
//
//				unifiedOrderGoods.setOrderSn(order.getOrderSn());
//
//				String[] goods = item.getGoods_name().split("_");
//
//				unifiedOrderGoods.setGoodsId(Long.parseLong(goods[1]));
//				unifiedOrderGoods.setGoodsName(goods[0]);
//				unifiedOrderGoods.setGoodsParams(item.getGoods_params());
//
//				unifiedOrderGoods.setPrice(new BigDecimal(item.getPrice()));
//				unifiedOrderGoods.setCostPrice(new BigDecimal(item.getCost_price()));
//
//				unifiedOrderGoods.setQuantity(Integer.parseInt(item.getQuantity()));
//
//
//				unifiedOrderGoods.setCreateTime(DateUtil.date());
//				unifiedOrderGoods.setUpdateTime(DateUtil.date());
//
//				unifiedOrderGoodsList.add(unifiedOrderGoods);
//			}
//		}

		/****************************************** 实现上 kafka 记录上没有这些 start ******************************************/

//		kafkaFlashDeliverOrderStateUpdateProcess(unifiedOrder4Update, unifiedOrderUpdateLog, unifiedOrderGoodsList);
		kafkaFlashDeliverOrderStateUpdateProcess(unifiedOrder4Update, unifiedOrderUpdateLog, null);

	}

	/**
	 * 只是简单移位重构 这个逻辑还是错的 mark by linjinyu at 20201209
	 *
	 * @param unifiedOrder4Update
	 * @param unifiedOrderUpdateLog
	 * @param unifiedOrderGoodsList
	 */
	@Transactional
	public void kafkaFlashDeliverOrderStateUpdateProcess(UnifiedOrder unifiedOrder4Update, UnifiedOrderUpdate unifiedOrderUpdateLog, List<UnifiedOrderGoods> unifiedOrderGoodsList) {

		// 更新
		commonOrderProcessService.attachUpdate(unifiedOrder4Update);
		// 状态变更的流水记录吧
		unifiedOrderUpdateMapper.insert(unifiedOrderUpdateLog);

		if (AnCollectionUtils.isNotEmpty(unifiedOrderGoodsList)) {

			unifiedOrderGoodsMapperEx.deleteByOrderSn(unifiedOrderUpdateLog.getOrderSn());

			for (UnifiedOrderGoods item : unifiedOrderGoodsList) {
				unifiedOrderGoodsMapper.insert(item);
			}
		}
	}


	/**
	 * 补丁程序
	 * DELETE FROM `sys_enterprise` WHERE `enterprise_id` > 1000000000000000000
	 * <p>
	 * SELECT * FROM `unified_order` WHERE `purchase_virt_id` >1000000000000000000 AND `purchase_virt_name` LIKE '%游客企业'
	 * <p>
	 * UPDATE `unified_order` SET `purchase_virt_id` = NULL,`purchase_virt_name` = NULL WHERE `purchase_virt_id` >1000000000000000000 AND `purchase_virt_name` LIKE '%游客企业'
	 * <p>
	 * SELECT * FROM `unified_order` WHERE `purchase_virt_id` >1000000000000000000 AND `purchase_virt_name` NOT LIKE '%游客企业'
	 * <p>
	 * <p>
	 * <p>
	 * SELECT * FROM `unified_order` WHERE `purchase_virt_id` >1000000000000000 AND `purchase_virt_name` LIKE '%游客企业'
	 * <p>
	 * UPDATE `unified_order` SET `purchase_virt_id` = NULL,`purchase_virt_name` = NULL WHERE `purchase_virt_id` >1000000000000000 AND `purchase_virt_name` LIKE '%游客企业'
	 * <p>
	 * SELECT * FROM `sys_enterprise` WHERE `enterprise_name` LIKE '%游客企业'
	 *
	 * @param receiveParam
	 * @return
	 */
	@Override
	public UnifiedOrderIssuesFlowingParam kafkaFlashDeliverPatchUnifiedOrderFieldOutVirt(FlashDeliverOrderPatchUnifiedOrderFieldOutVirt receiveParam) {

		UnifiedOrderIssuesFlowingParam callback = new UnifiedOrderIssuesFlowingParam();
		callback.setUid(receiveParam.getUid());
		callback.setProcessResult(CommonProcessResultEnum.正常.getKey());

		SysEnterprise sysEnterprise = null;

		// 情况是楼闪送 有段时间 的问题单 有企业名没有企业Id
		if (StringUtils.isNotBlank(receiveParam.getPurchaseVirtName())) {
			sysEnterprise = sysEnterpriseService.findByOutVirtName(receiveParam.getPurchaseVirtName());
		} else {
			sysEnterprise = sysEnterpriseService.touchByOutOrgId(receiveParam.getProjectId());
		}

		if (null != sysEnterprise) {

			UnifiedOrder unifiedOrderPatchFieldOutVirt = new UnifiedOrder();
			unifiedOrderPatchFieldOutVirt.setId(receiveParam.getId());
			unifiedOrderPatchFieldOutVirt.setPurchaseVirtId(sysEnterprise.getEnterpriseId());
			unifiedOrderPatchFieldOutVirt.setPurchaseVirtName(sysEnterprise.getEnterpriseName());

			commonOrderProcessService.attachUpdate(unifiedOrderPatchFieldOutVirt);

			callback.setProcessReport(StrUtil.format("{}@{}=>{}@{}", receiveParam.getPurchaseVirtId(), receiveParam.getPurchaseVirtName(), sysEnterprise.getEnterpriseId(), sysEnterprise.getEnterpriseName()));

		} else {
			callback.setProcessResult(CommonProcessResultEnum.异常_数据本身缺失.getKey());
			callback.setProcessReport(StrUtil.format("企业信息异常@{}@{}", receiveParam.getId(), receiveParam.getOrderSn()));
		}


		return callback;


	}

	@Override
	public R<List<UnifiedOrder>> patchFlashDeliverPatchUnifiedOrderFieldOutVirt(PageQueryParam pageQueryParam) {

		Integer pageNumber = pageQueryParam.getPageNo();
		Integer pageSize   = pageQueryParam.getPageSize();

		PageHelper.startPage(pageNumber, pageSize);

		UnifiedOrderExample example = new UnifiedOrderExample();
		example.createCriteria()
				.andServiceNoEqualTo(CommonServiceNoEnum.楼闪送.getServiceNo())
				.andPurchaseVirtIdIsNull()/* 采购人企业Id IsNull */;
		List<UnifiedOrder>     resultList = unifiedOrderMapper.selectByExample(example);
		PageInfo<UnifiedOrder> pageInfo   = new PageInfo<UnifiedOrder>(resultList);

		PageHelper.clearPage();

		return new R<List<UnifiedOrder>>(pageInfo.getPageNum(), pageInfo.getPageSize(), (int) pageInfo.getTotal(), resultList);

	}
}
