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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.superdesk.uniorder.common.enums.common.*;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCompletStateEnum;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderGoods;
import cn.superdesk.uniorder.dao.mapper.base.*;
import cn.superdesk.uniorder.dto.param.operation.UnifiedOrderIssuesFlowingParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskmall.proxyclient.ProxyClientOrderGoodsReceiveParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskmall.proxyclient.ProxyClientOrderOptBecomeInvalidQueryCriteria;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskmall.proxyclient.ProxyClientOrderReceiveParam;
import cn.superdesk.uniorder.event.CommonEventPublisher;
import cn.superdesk.uniorder.service.order.receive.ReceiveProxyClientOrderService;
import cn.superdesk.uniorder.service.order.base.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 有空再重构吧
 * @Author: linjinyu
 * @CreateDate: 2021/4/26 上午11:40
 * @UpdateUser: linjinyu
 * @UpdateDate: 2021/4/26 上午11:40
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class ReceiveProxyClientOrderServiceImpl implements ReceiveProxyClientOrderService {

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

	@Autowired
	private UnifiedOrderService      unifiedOrderService;
	@Autowired
	private UnifiedOrderGoodsService unifiedOrderGoodsService;

	@Autowired
	private CommonOrderProcessService            commonOrderProcessService;
	@Autowired
	private CommonMergeOrderGoodsProcessService  commonOrderGoodsMergeProcessService;
	@Autowired
	private CommonMergeOrderCreditProcessService commonOrderCreditMergeProcessService;


	@Autowired
	private CommonEventPublisher commonEventPublisher;

	/****************************************** kafka 代客下单 start ******************************************/

	@Override
	public UnifiedOrderIssuesFlowingParam kafkaProxyClientOrderReceive(ProxyClientOrderReceiveParam receiveParam) {


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

		// 此通道处理 正负零
		if (null == receiveParam.getOrderAmount()
//				&& proxyClientOrderReceiveParam.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();
		convertProxyClientOrderReceiveParam2Entity(receiveParam, unifiedOrderEntity);


		List<UnifiedOrderGoods>                 processUnifiedOrderGoodsList          = new ArrayList<>();
		List<ProxyClientOrderGoodsReceiveParam> proxyClientOrderReceiveParamGoodsList = receiveParam.getGoodsList();

		for (ProxyClientOrderGoodsReceiveParam proxyClientOrderGoodsReceiveParam : proxyClientOrderReceiveParamGoodsList) {

			UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();
			convertProxyClientOrderGoodsReceiveParam2Entity(proxyClientOrderGoodsReceiveParam, unifiedOrderGoods);
			unifiedOrderGoods.setOrderSn(unifiedOrderEntity.getOrderSn());

			// TODO 【代客下单,同步订单数据时,商品数量≥1,否则不允许同步到统一订单。】 https://www.tapd.cn/33003868/prong/stories/view/1133003868001002022 如果是小于等于零要不同步要怎样反馈？
			if (null != unifiedOrderGoods.getQuantity() && unifiedOrderGoods.getQuantity().compareTo(1) >= 0) {
				processUnifiedOrderGoodsList.add(unifiedOrderGoods);
			}

		}

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

		/****************************************** TODO 再核算 20210126 拆单 子单 订单金额有可能是不包含运费 start ******************************************/
//		commonOrderIncidentalExpensesProcessService.proxyClientOrderAmountProcess(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 ******************************************/

		/****************************************** 代客下单 供应商信息处理 start ******************************************/
		commonEventPublisher.triggerProxyClientOrderSupplierCheckUpEvent(unifiedOrderEntity);
		/****************************************** 代客下单 供应商信息处理 start ******************************************/


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

		return callback;
	}

	/****************************************** kafka 代客下单   end ******************************************/

	private void convertProxyClientOrderReceiveParam2Entity(ProxyClientOrderReceiveParam proxyClientOrderReceiveParam, UnifiedOrder unifiedOrderEntity) {

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

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

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

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

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

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


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

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

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


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


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


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

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


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

		unifiedOrderEntity.setPurchaseVirtId(proxyClientOrderReceiveParam.getPurchaseVirtId());
		unifiedOrderEntity.setPurchaseVirtName(proxyClientOrderReceiveParam.getPurchaseVirtName());

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


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

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

		unifiedOrderEntity.setRemarks(proxyClientOrderReceiveParam.getRemark());

		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 convertProxyClientOrderGoodsReceiveParam2Entity(ProxyClientOrderGoodsReceiveParam proxyClientOrderGoodsReceiveParam, UnifiedOrderGoods unifiedOrderGoods) {

		unifiedOrderGoods.setGoodsId(proxyClientOrderGoodsReceiveParam.getGoodsId());
		unifiedOrderGoods.setOutSnapshotOrderGoodsId(proxyClientOrderGoodsReceiveParam.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(proxyClientOrderGoodsReceiveParam.getGoodsName());
		unifiedOrderGoods.setSelfOption(proxyClientOrderGoodsReceiveParam.getSelfOption());

		unifiedOrderGoods.setGoodsParams(proxyClientOrderGoodsReceiveParam.getGoodsParams());

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

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


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

		// 商户税率
		unifiedOrderGoods.setMerchTaxId(proxyClientOrderGoodsReceiveParam.getMerchTaxId());
		unifiedOrderGoods.setMerchTaxCode(proxyClientOrderGoodsReceiveParam.getMerchTaxCode());
		unifiedOrderGoods.setMerchTaxRate(proxyClientOrderGoodsReceiveParam.getMerchTaxRate());

		// 平台税率
		unifiedOrderGoods.setOperationTaxId(proxyClientOrderGoodsReceiveParam.getOperationTaxId());
		unifiedOrderGoods.setOperationTaxCode(proxyClientOrderGoodsReceiveParam.getOperationTaxCode());
		unifiedOrderGoods.setOperationTaxRate(proxyClientOrderGoodsReceiveParam.getOperationTaxRate());
		/************************************** update by linjinjy 20200904 20200723_林志鹏_税率,退款格式.docx **************************************/

		/****************************************** 三级分类 20200904 by linjinyu 20200904_林志鹏_三极分类 ******************************************/
		unifiedOrderGoods.setCateIdLv1(proxyClientOrderGoodsReceiveParam.getCateIdLv1());
		unifiedOrderGoods.setCateIdLv2(proxyClientOrderGoodsReceiveParam.getCateIdLv2());
		unifiedOrderGoods.setCateIdLv3(proxyClientOrderGoodsReceiveParam.getCateIdLv3());

		unifiedOrderGoods.setCateNameLv1(proxyClientOrderGoodsReceiveParam.getCateNameLv1());
		unifiedOrderGoods.setCateNameLv2(proxyClientOrderGoodsReceiveParam.getCateNameLv2());
		unifiedOrderGoods.setCateNameLv3(proxyClientOrderGoodsReceiveParam.getCateNameLv3());
		/****************************************** 三级分类 20200904 by linjinyu 20200904_林志鹏_三极分类 ******************************************/

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


	}


	/**
	 * 代客下单的接口实现
	 * 作废订单
	 *
	 * @param queryCriteria
	 * @return
	 */
	public R<String> proxyClientOrderOptBecomeInvalid(ProxyClientOrderOptBecomeInvalidQueryCriteria queryCriteria) {

//		①该订单在统一订单中存在&其所有的订单商品当前对账状态均为"未对账/不对账",允许作废该订单;
//		②若该订单在统一订单中不存在,不允许作废,返回错误内容"该订单在统一订单中心不存在";
//		③若该订单中部分商品当前对账状态为"已对账",不允许作废,返回错误内容"该订单已对账,不允许作废";
//		满足作废订单条件后,即允许作废该订单,该订单完成状态为"已作废";

		UnifiedOrder processUnifiedOrder = unifiedOrderService.findByOrderSn(queryCriteria.getOrderSn());

		if (null == processUnifiedOrder) {
			return ResponseResultOuterUtils.createErrorResult("500", "该订单在统一订单中心不存在");
		}

		List<UnifiedOrderGoods> processUnifiedOrderGoodsList = unifiedOrderGoodsService.findByOrderSn(queryCriteria.getOrderSn());

		Long isAccountingStateCustomer = processUnifiedOrderGoodsList.stream().filter(o -> null != o.getAccountingStateCustomer() && o.getAccountingStateSupplier().compareTo(CommonAccountingStateEnum.已对账.getKey()) == 0).count();
		Long isAccountingStateSupplier = processUnifiedOrderGoodsList.stream().filter(o -> null != o.getAccountingStateCustomer() && o.getAccountingStateSupplier().compareTo(CommonAccountingStateEnum.已对账.getKey()) == 0).count();

		if (isAccountingStateCustomer.compareTo(0L) > 0 || isAccountingStateSupplier.compareTo(0L) > 0) {
			return ResponseResultOuterUtils.createErrorResult("500", "该订单已对账,不允许作废 |" + isAccountingStateCustomer + "|" + isAccountingStateSupplier);
		}

		UnifiedOrder beUpdateUnifiedOrder = new UnifiedOrder();
		beUpdateUnifiedOrder.setId(processUnifiedOrder.getId());
		beUpdateUnifiedOrder.setCompletState(UnifiedOrderCompletStateEnum.已取消.getKey());

		unifiedOrderMapper.updateByPrimaryKeySelective(beUpdateUnifiedOrder);

		return ResponseResultOuterUtils.createSuccesResult();


	}
}
