package cn.superdesk.uniorder.service.order.base;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.superdesk.uniorder.common.enums.common.CommonOrderGoodsIdEnum;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.dao.entity.base.*;
import cn.superdesk.uniorder.dao.entity.operation.UnifiedOrderIssuesFlowing;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterprise;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterpriseExample;
import cn.superdesk.uniorder.dao.entity.organisation.SysOrganization;
import cn.superdesk.uniorder.dao.entity.organisation.SysOrganizationExample;
import cn.superdesk.uniorder.dao.mapper.base.UnifiedOrderCreditMapper;
import cn.superdesk.uniorder.dao.mapper.base.UnifiedOrderGoodsMapper;
import cn.superdesk.uniorder.dao.mapper.base.UnifiedOrderMapper;
import cn.superdesk.uniorder.dao.mapper.organisation.SysEnterpriseMapper;
import cn.superdesk.uniorder.dao.mapper.organisation.SysOrganizationMapper;
import cn.superdesk.uniorder.interceptor.monitor.annotation.MonitorLogger;
import cn.superdesk.uniorder.service.organisation.SysEnterpriseService;
import cn.superdesk.uniorder.service.organisation.SysOrganizationService;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


/**
 * @Description: 重构 处理 合并数据 不写 interface
 * @Author: linjinyu
 * @CreateDate: 9/15/20 5:03 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 9/15/20 5:03 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@MonitorLogger
@Slf4j
@Service
public class CommonOrderProcessService {

	@Autowired
	private UnifiedOrderMapper       unifiedOrderMapper;
	@Autowired
	private UnifiedOrderGoodsMapper  unifiedOrderGoodsMapper;
	@Autowired
	private UnifiedOrderCreditMapper unifiedOrderCreditMapper;

	@Autowired
	private SysOrganizationService sysOrganizationService;
	@Autowired
	private SysEnterpriseService   sysEnterpriseService;
	@Autowired
	private SysOrganizationMapper  sysOrganizationMapper;
	@Autowired
	private SysEnterpriseMapper    sysEnterpriseMapper;

	public int attachInsert(UnifiedOrder unifiedOrderEntity) {

		// TODO ...
		checkAndReviseOrgName(unifiedOrderEntity);

		return unifiedOrderMapper.insert(unifiedOrderEntity);
	}

	public int attachUpdate(UnifiedOrder unifiedOrderEntity) {

		// TODO ...
		checkAndReviseOrgName(unifiedOrderEntity);

		return unifiedOrderMapper.updateByPrimaryKeySelective(unifiedOrderEntity);
	}

	/**
	 * 主要是解决 有的订单过来时 项目Id 传了 项目名称 没有传的情况
	 *
	 * @param unifiedOrderEntity
	 */
	private void checkAndReviseOrgName(UnifiedOrder unifiedOrderEntity) {

		if (ObjectUtil.isNotNull(unifiedOrderEntity.getProjectId()) && StrUtil.isBlank(unifiedOrderEntity.getProjectName())) {

			SysOrganization sysOrganization = sysOrganizationService.getByOutOrgId(unifiedOrderEntity.getProjectId());

			if (ObjectUtil.isNotNull(sysOrganization)) {
				unifiedOrderEntity.setProjectName(sysOrganization.getOrganizationName());
			}
		}
	}

	/**
	 * 核算 订单金额
	 * 20210128 目前定义的订单金额是包含运费的
	 *
	 * @param unifiedOrderEntity
	 * @param processUnifiedOrderGoodsList
	 * @param uid
	 * @return
	 */
	public UnifiedOrderIssuesFlowing processOrderAmount(UnifiedOrder unifiedOrderEntity, List<UnifiedOrderGoods> processUnifiedOrderGoodsList, String uid) {

		log.info("{}", AnJsonUtils.toJson(processUnifiedOrderGoodsList));

		StringBuffer stringBuffer = new StringBuffer();

		if (AnCollectionUtils.isEmpty(processUnifiedOrderGoodsList)) {
			stringBuffer.append("原始订单商品Size:").append(processUnifiedOrderGoodsList.size()).append(";");
		}


		UnifiedOrderIssuesFlowing unifiedOrderIssuesFlowing = new UnifiedOrderIssuesFlowing();
		unifiedOrderIssuesFlowing.setUid(uid);


		// TODO 现在有个问题 就是老数据 goodsId都是为空的

		// TODO 20210407 发现 代客下单 有 goodsId 是空的

		Long isExistGoodsIdIsNull = processUnifiedOrderGoodsList.stream().filter(o -> null == o.getGoodsId()).count();

		if (isExistGoodsIdIsNull.compareTo(0L) > 0) {
			stringBuffer.append("订单商品goodsId存在异常-导致的问题是-订单销售金额-订单成本金额-核算会有异常-导出开票数据合并商品没有基准:").append(isExistGoodsIdIsNull).append(";");
		}

		// filter 为 排除 运费 商户承担运费 退运费 TODO 消除魔法数字
		// goodsId
		// 0 客户承担运费
		// 1 商户承担运费
		// -1 退运费
		BigDecimal goodsAmount = processUnifiedOrderGoodsList
				.stream()
				.filter(o -> null != o.getGoodsId() && o.getGoodsId().compareTo(CommonOrderGoodsIdEnum.运费.getKey()) != 0 && o.getGoodsId().compareTo(CommonOrderGoodsIdEnum.商户承担运费.getKey()) != 0 && o.getGoodsId().compareTo(CommonOrderGoodsIdEnum.退单退运费.getKey()) != 0)
				.map(item -> item.getPrice() == null ? BigDecimal.ZERO : item.getPrice().multiply(new BigDecimal(item.getQuantity())))
				.reduce(BigDecimal.ZERO, BigDecimal::add);

		BigDecimal goodsCostAmount = processUnifiedOrderGoodsList
				.stream()
				.filter(o -> null != o.getGoodsId() && o.getGoodsId().compareTo(CommonOrderGoodsIdEnum.运费.getKey()) != 0 && o.getGoodsId().compareTo(CommonOrderGoodsIdEnum.商户承担运费.getKey()) != 0 && o.getGoodsId().compareTo(CommonOrderGoodsIdEnum.退单退运费.getKey()) != 0)
				.map(item -> item.getCostPrice() == null ? BigDecimal.ZERO : item.getCostPrice().multiply(new BigDecimal(item.getQuantity())))
				.reduce(BigDecimal.ZERO, BigDecimal::add);

		BigDecimal orderAmount     = goodsAmount.add(unifiedOrderEntity.getTransportAmount());
		BigDecimal orderCostAmount = goodsCostAmount.add(unifiedOrderEntity.getTransportAmount());

		// 添加 条件 如果 isExistGoodsIdIsNull >0 的情况就不把核算后金额覆盖 mark by linjinyu at 20210408
		if (unifiedOrderEntity.getAmount().compareTo(orderAmount) != 0 && isExistGoodsIdIsNull.compareTo(0L) == 0) {

			stringBuffer.append("原始订单销售金额:").append(unifiedOrderEntity.getAmount()).append(";")
					.append("核算订单销售金额:").append(orderAmount).append(";");

			unifiedOrderEntity.setAmount(orderAmount);
		}

		if (unifiedOrderEntity.getCostAmount().compareTo(orderCostAmount) != 0) {

			stringBuffer.append("原始订单成本金额:").append(unifiedOrderEntity.getCostAmount()).append(";")
					.append("核算订单成本金额:").append(orderCostAmount).append(";");

			unifiedOrderEntity.setCostAmount(orderCostAmount);
		}


		/****************************************** 记录异常 start ******************************************/

		if (stringBuffer.length() > 0) {

			stringBuffer.insert(0, "69:异常订单数据;").append(unifiedOrderEntity.getRemarks());

			unifiedOrderIssuesFlowing.setProcessResult(2);
			unifiedOrderIssuesFlowing.setProcessReport(stringBuffer.toString());

		}

		unifiedOrderEntity.setGoodsAmount(goodsAmount);
		unifiedOrderEntity.setGoodsCostAmount(goodsCostAmount);

		return unifiedOrderIssuesFlowing;

	}

	/**
	 * 清理错误订单
	 *
	 * @param orderSn
	 */
	public void cleanErrorOrder(String orderSn) {

		UnifiedOrderExample unifiedOrderExample4Delete = new UnifiedOrderExample();
		unifiedOrderExample4Delete.createCriteria()
				.andOrderSnEqualTo(orderSn);
		unifiedOrderMapper.deleteByExample(unifiedOrderExample4Delete);

		UnifiedOrderGoodsExample unifiedOrderGoodsExample4Delete = new UnifiedOrderGoodsExample();
		unifiedOrderGoodsExample4Delete.createCriteria()
				.andOrderSnEqualTo(orderSn);
		unifiedOrderGoodsMapper.deleteByExample(unifiedOrderGoodsExample4Delete);

		UnifiedOrderCreditExample unifiedOrderCreditExample4Delete = new UnifiedOrderCreditExample();
		unifiedOrderCreditExample4Delete.createCriteria()
				.andOrderSnEqualTo(orderSn);
		unifiedOrderCreditMapper.deleteByExample(unifiedOrderCreditExample4Delete);

	}

	/**
	 * 级联-更新-TODO 这样做可能会有性能问题,也可能有不相关的数据更新
	 *
	 * @param outOrgId
	 * @param outOrgName
	 */
//	@MonitorLogger
	public void cascadeUpdateTableUnifiedOrderFieldOrgName(Long outOrgId, String outOrgName) {

		UnifiedOrderExample unifiedOrderExample4UpdateFieldOutOrgName = new UnifiedOrderExample();
		unifiedOrderExample4UpdateFieldOutOrgName.createCriteria()
				.andProjectIdEqualTo(outOrgId)
				// 这个不等于可能有性能问题
				.andProjectNameNotEqualTo(outOrgName);

		Long count = unifiedOrderMapper.countByExample(unifiedOrderExample4UpdateFieldOutOrgName);

		if (count.compareTo(0L) > 0) {
			UnifiedOrder unifiedOrder4UpdateFieldOutOrgName = new UnifiedOrder();
			unifiedOrder4UpdateFieldOutOrgName.setProjectName(outOrgName);
			unifiedOrderMapper.updateByExampleSelective(unifiedOrder4UpdateFieldOutOrgName, unifiedOrderExample4UpdateFieldOutOrgName);
		}
	}

	/**
	 * 级联-更新-TODO 这样做可能会有性能问题,也可能有不相关的数据更新
	 *
	 * @param outVirtId
	 * @param outVirtName
	 */
//	@MonitorLogger
	public void cascadeUpdateTableUnifiedOrderFieldVirtName(Long outVirtId, String outVirtName) {

		UnifiedOrderExample unifiedOrderExample4UpdateFieldOutVirtName = new UnifiedOrderExample();
		unifiedOrderExample4UpdateFieldOutVirtName.createCriteria()
				.andPurchaseVirtIdEqualTo(outVirtId)
				// 这个不等于可能有性能问题
				.andPurchaseVirtNameNotEqualTo(outVirtName);

		Long count = unifiedOrderMapper.countByExample(unifiedOrderExample4UpdateFieldOutVirtName);

		if (count.compareTo(0L) > 0) {
			UnifiedOrder unifiedOrder4UpdateFieldOutVirtName = new UnifiedOrder();
			unifiedOrder4UpdateFieldOutVirtName.setPurchaseVirtName(outVirtName);
			unifiedOrderMapper.updateByExampleSelective(unifiedOrder4UpdateFieldOutVirtName, unifiedOrderExample4UpdateFieldOutVirtName);
		}

	}


	public void cascadeUpdateTableOrganizationFieldIsHasOrder(Long outOrgId, String outOrgName) {

		UnifiedOrderExample unifiedOrderExample4UpdateFieldOutOrgName = new UnifiedOrderExample();
		unifiedOrderExample4UpdateFieldOutOrgName.createCriteria()
				.andProjectIdEqualTo(outOrgId);

		Long count = unifiedOrderMapper.countByExample(unifiedOrderExample4UpdateFieldOutOrgName);


		SysOrganization sysOrganization4UpdateFieldIsHasOrder = null;

		if (count.compareTo(0L) > 0) {
			// set
			sysOrganization4UpdateFieldIsHasOrder = new SysOrganization();
			// 是否有订单:0-默认;1-有的;2-没有;
			sysOrganization4UpdateFieldIsHasOrder.setIsHasOrder(1);

		} else if (count.compareTo(0L) == 0) {

			// set
			sysOrganization4UpdateFieldIsHasOrder = new SysOrganization();
			// 是否有订单:0-默认;1-有的;2-没有;
			sysOrganization4UpdateFieldIsHasOrder.setIsHasOrder(2);
		}

		// 判定有点多余
		if (null != sysOrganization4UpdateFieldIsHasOrder) {
			// where
			SysOrganizationExample sysOrganizationExample4UpdateFieldIsHasOrder = new SysOrganizationExample();
			sysOrganizationExample4UpdateFieldIsHasOrder.createCriteria()
					.andOrganizationIdEqualTo(outOrgId);

			sysOrganizationMapper.updateByExampleSelective(sysOrganization4UpdateFieldIsHasOrder, sysOrganizationExample4UpdateFieldIsHasOrder);
		}
	}

	public void cascadeUpdateTableEnterpriseFieldIsHasOrder(Long outVirtId, String outVirtName) {

		UnifiedOrderExample unifiedOrderExample4UpdateFieldOutVirtName = new UnifiedOrderExample();
		unifiedOrderExample4UpdateFieldOutVirtName.createCriteria()
				.andPurchaseVirtIdEqualTo(outVirtId);

		Long count = unifiedOrderMapper.countByExample(unifiedOrderExample4UpdateFieldOutVirtName);

		SysEnterprise sysEnterprise4UpdateFieldIsHasOrder = null;

		if (count.compareTo(0L) > 0) {
			sysEnterprise4UpdateFieldIsHasOrder = new SysEnterprise();
			sysEnterprise4UpdateFieldIsHasOrder.setIsHasOrder(1);
			// 是否有订单:0-默认;1-有的;2-没有;

		} else if (count.compareTo(0L) == 0) {
			sysEnterprise4UpdateFieldIsHasOrder = new SysEnterprise();
			// 是否有订单:0-默认;1-有的;2-没有;
			sysEnterprise4UpdateFieldIsHasOrder.setIsHasOrder(2);
		}

		// 判定有点多余
		if (null != sysEnterprise4UpdateFieldIsHasOrder) {

			SysEnterpriseExample sysEnterpriseExample4UpdateFieldIsHasOrder = new SysEnterpriseExample();
			sysEnterpriseExample4UpdateFieldIsHasOrder.createCriteria()
					.andEnterpriseIdEqualTo(outVirtId);

			sysEnterpriseMapper.updateByExampleSelective(sysEnterprise4UpdateFieldIsHasOrder, sysEnterpriseExample4UpdateFieldIsHasOrder);
		}
	}
}
