package cn.superdesk.uniorder.service.accounting.unified.customer.impl;

import cn.superdesk.libs.common.json.JsonUtils;
import cn.superdesk.libs.common.util.BeanUtils;
import cn.superdesk.libs.common.util.CollectionUtils;
import cn.superdesk.uniorder.common.R;
import cn.superdesk.uniorder.common.enums.common.CommonAccountingStateEnum;
import cn.superdesk.uniorder.common.enums.invoice.InvoiceApplyBackAccountStatusEnum;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderAccountingStatusEnum;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderBackAccountStatusEnum;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderDimCreateByEnum;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderInvoiceStatusEnum;
import cn.superdesk.uniorder.dao.entity.accounting.unified.customer.*;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderGoods;
import cn.superdesk.uniorder.dao.entity.invoice.customer.InvoiceApply;
import cn.superdesk.uniorder.dao.entity.invoice.customer.InvoiceOrder;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterprise;
import cn.superdesk.uniorder.dao.entity.organisation.SysOrganization;
import cn.superdesk.uniorder.dao.entity.scheduler.SysQuartzScheduleTaskStatementOfAccount;
import cn.superdesk.uniorder.dao.entity.sys.SysOderUser;
import cn.superdesk.uniorder.dao.entity.sys.SysOrder;
import cn.superdesk.uniorder.dao.entity.unified.UnifiedBankInfo;
import cn.superdesk.uniorder.dao.mapper.accounting.unified.customer.*;
import cn.superdesk.uniorder.dao.mapper.base.UnifiedOrderGoodsMapperEx;
import cn.superdesk.uniorder.dao.mapper.base.UnifiedOrderMapper;
import cn.superdesk.uniorder.dao.mapper.base.UnifiedOrderMapperEx;
import cn.superdesk.uniorder.dao.mapper.base.UnifiedOrderReturnGoodsMapperEx;
import cn.superdesk.uniorder.dao.mapper.invoice.customer.InvoiceApplyMapperEx;
import cn.superdesk.uniorder.dao.mapper.organisation.SysEnterpriseMapperEx;
import cn.superdesk.uniorder.dao.mapper.organisation.SysOrganizationMapperEx;
import cn.superdesk.uniorder.dao.mapper.scheduler.SysQuartzScheduleTaskStatementOfAccountMapper;
import cn.superdesk.uniorder.dao.mapper.sys.SysConfigMapper;
import cn.superdesk.uniorder.dao.mapper.sys.SysOderUserMapperEx;
import cn.superdesk.uniorder.dao.mapper.sys.SysOrderMapper;
import cn.superdesk.uniorder.dao.mapper.unified.UnifiedBankInfoMapper;
import cn.superdesk.uniorder.dto.param.accounting.unified.customer.UnifiedCustomerCreateDimGoodsParam;
import cn.superdesk.uniorder.dto.param.accounting.unified.customer.UnifiedCustomerCreateDimGoodsParamJsonStruct;
import cn.superdesk.uniorder.dto.param.accounting.unified.customer.UnifiedCustomerCreateDimOrderParam;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.*;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.statement.CustomerStatementOfAccountDetailItemVo;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.statement.CustomerStatementOfAccountDetailVo;
import cn.superdesk.uniorder.dto.vo.sys.SysInvoiceOrder;
import cn.superdesk.uniorder.dto.vo.sys.SysOrderQuery;
import cn.superdesk.uniorder.service.accounting.unified.customer.AccountingUnifiedCustomerOrderGoodsService;
import cn.superdesk.uniorder.service.accounting.unified.customer.AccountingUnifiedCustomerOrderService;
import cn.superdesk.uniorder.service.accounting.unified.customer.AccountingUnifiedCustomerService;
import cn.superdesk.uniorder.service.accounting.unified.customer.AccountingUnifiedCustomerXGoodsService;
import cn.superdesk.uniorder.service.base.UnifiedOrderCreditService;
import cn.superdesk.uniorder.service.base.UnifiedOrderGoodsService;
import cn.superdesk.uniorder.service.base.UnifiedOrderService;
import cn.superdesk.uniorder.service.sys.SysConfigService;
import cn.superdesk.uniorder.utils.lamda.LamdaUtils;
import cn.superdesk.uniorder.utils.numerical.AnIntegerUtils;
import cn.superdesk.uniorder.utils.numerical.AnLongUtils;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: 对账单 TODO 此类存在乱七八糟的东西 要清理
 * @Author: linjinyu 补充 修改
 * @CreateDate: 4/28/20 4:30 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 4/28/20 4:30 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class AccountingUnifiedCustomerServiceImpl implements AccountingUnifiedCustomerService {


	@Autowired
	private AccountingUnifiedCustomerMapper      accountingUnifiedCustomerMapper;
	@Autowired
	private AccountingUnifiedCustomerMapperEx    accountingUnifiedCustomerMapperEx;
	@Autowired
	private AccountingUnifiedCustomerMapperExSys accountingUnifiedCustomerMapperExSys;

	@Autowired
	private AccountingUnifiedCustomerXGoodsMapper  accountingUnifiedCustomerXGoodsMapper;
	@Autowired
	private AccountingUnifiedCustomerXGoodsService accountingUnifiedCustomerXGoodsService;


	/****************************************** 对账单 订单 商品 表 将要弃用 start ******************************************/
	@Autowired
	private AccountingUnifiedCustomerOrderMapper   accountingUnifiedCustomerOrderMapper;
	@Autowired
	private AccountingUnifiedCustomerOrderMapperEx accountingUnifiedCustomerOrderMapperEx;

	@Autowired
	private AccountingUnifiedCustomerOrderGoodsMapper   accountingUnifiedCustomerOrderGoodsMapper;
	@Autowired
	private AccountingUnifiedCustomerOrderGoodsMapperEx accountingUnifiedCustomerOrderGoodsMapperEx;

	@Autowired
	private AccountingUnifiedCustomerOrderService      accountingUnifiedCustomerOrderService;
	@Autowired
	private AccountingUnifiedCustomerOrderGoodsService accountingUnifiedCustomerOrderGoodsService;

	/****************************************** 对账单 订单 商品 表 将要弃用   end ******************************************/

	@Autowired
	private UnifiedBankInfoMapper unifiedBankInfoMapper;

	@Autowired
	private SysConfigMapper     sysConfigMapper;
	@Autowired
	private SysOrderMapper      sysOrderMapper;
	@Autowired
	private SysOderUserMapperEx sysOderUserMapper;

	@Autowired
	private UnifiedOrderMapper              unifiedOrderMapper;
	@Autowired
	private UnifiedOrderMapperEx            unifiedOrderMapperEx;
	@Autowired
	private UnifiedOrderGoodsMapperEx       unifiedOrderGoodsMapperEx;
	@Autowired
	private UnifiedOrderReturnGoodsMapperEx unifiedOrderReturnGoodsMapperEx;


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

	@Autowired
	private SysQuartzScheduleTaskStatementOfAccountMapper sysQuartzScheduleTaskStatementOfAccountMapper;

	@Autowired
	private SysEnterpriseMapperEx   sysEnterpriseMapperEx;
	@Autowired
	private SysOrganizationMapperEx sysOrganizationMapper;

	@Autowired
	private InvoiceApplyMapperEx invoiceApplyMapperEx;

	@Autowired
	private SysConfigService sysConfigService;


	@Override
	public PageInfo<AccountingUnifiedCustomer> findByPaging(Map<String, Object> params, Integer pageNo, Integer pageSize) {

		return null;
	}

	@Override
	public void deleteObj(Long id) {


	}

	@Override
	public void updateObj(AccountingUnifiedCustomer t) {

		accountingUnifiedCustomerMapper.updateByPrimaryKeySelective(t);
	}

	@Override
	public AccountingUnifiedCustomer findById(Long id) {

		return accountingUnifiedCustomerMapper.selectByPrimaryKey(id);
	}

	@Override
	public AccountingUnifiedCustomer findByAccountingOrderSn(String accountingOrderSn) {


		AccountingUnifiedCustomerExample example = new AccountingUnifiedCustomerExample();
		example.createCriteria()
				.andAccountingOrderSnEqualTo(accountingOrderSn);

		List<AccountingUnifiedCustomer> result = accountingUnifiedCustomerMapper.selectByExample(example);

		if (CollectionUtils.isEmpty(result)) {
			return null;
		} else {
			return result.get(0);
		}
		// 弃用 mark by linjinyu at 20210105
//		return accountingUnifiedCustomerMapperEx.findBySn(dzSn);
	}

	@Override
	public void addObj(AccountingUnifiedCustomer t) {


	}

	@Override
	public List<AccountingUnifiedCustomer> findAll(Map<String, Object> queryMap) {

		return null;
	}


	/****************************************** 对账单 创建 start ******************************************/
	/**
	 * 这个是老的生成对账单
	 *
	 * @param accountingUnifiedCustomer
	 * @param accountingUnifiedCustomerOrderList
	 * @return
	 */
	@Transactional
	@Override
	public AccountingUnifiedCustomer addTran(AccountingUnifiedCustomer accountingUnifiedCustomer, List<AccountingUnifiedCustomerOrder> accountingUnifiedCustomerOrderList) {

		Map<String, Object> codeMap = sysConfigService.getConfigByDZSN();

		accountingUnifiedCustomer.setAccountingOrderSn(codeMap.get("sn").toString());

		accountingUnifiedCustomerMapper.insert(accountingUnifiedCustomer);

		for (AccountingUnifiedCustomerOrder dzOrder : accountingUnifiedCustomerOrderList) {

			dzOrder.setDzId(accountingUnifiedCustomer.getId());
			accountingUnifiedCustomerOrderMapper.insert(dzOrder);

			// 更新订单对账状态
			SysOrder order = new SysOrder();

			order.setId(dzOrder.getOrderId());
			order.setIsGenBill(Byte.valueOf("1"));
			sysOrderMapper.updateByPrimaryKeySelective(order);


			// TODO 这个字段是重构前是真的，但对映的数据库字段是没有的
			// TODO 整个 弃了吧 start
//			Map<String, Object> queryMap = new HashMap<>();
//			queryMap.put("sysOrderId", dzOrder.getMyOrderId());
//			List<SysGood> goods = dzOrderGoodMapper.findAllFromGood(queryMap);
//
//			for (SysGood sysGood : goods) {
//				AccountingUnifiedCustomerOrderGoods orderGood = ConvertBeanUtil.copyBean(sysGood, AccountingUnifiedCustomerOrderGoods.class);
//				orderGood.setDzOrderId(dzOrder.getId());
//				orderGood.setGoodId(sysGood.getId());
//
//				dzOrderGoodMapper.insert(orderGood);
//			}
			// TODO 整个 弃了吧 end
		}

		// 更新账单号
		sysConfigService.updateSysConfigFieldDataIntByCode(codeMap);

		return accountingUnifiedCustomer;
	}


	/**
	 * 装箱
	 *
	 * @param accountingUnifiedCustomerOrder
	 * @param unifiedOrder
	 */
	private void convertUnifiedOrder2AccountingUnifiedCustomerOrder(AccountingUnifiedCustomerOrder accountingUnifiedCustomerOrder, UnifiedOrder unifiedOrder) {

		accountingUnifiedCustomerOrder.setId(null);

		accountingUnifiedCustomerOrder.setOrderId(unifiedOrder.getId());
		accountingUnifiedCustomerOrder.setOrderSn(unifiedOrder.getOrderSn());

		accountingUnifiedCustomerOrder.setPrice(unifiedOrder.getAmount());
		accountingUnifiedCustomerOrder.setPayType(unifiedOrder.getPayType());

		accountingUnifiedCustomerOrder.setOrderType(unifiedOrder.getServiceNo());
		accountingUnifiedCustomerOrder.setStatus(unifiedOrder.getCompletState());

		accountingUnifiedCustomerOrder.setDispatchPrice(unifiedOrder.getTransportAmount());

		accountingUnifiedCustomerOrder.setOrganizationId(unifiedOrder.getProjectId());
		// 企业ID
		accountingUnifiedCustomerOrder.setEnterpriseId(unifiedOrder.getPurchaseVirtId());

		accountingUnifiedCustomerOrder.setMerchName(unifiedOrder.getSaleName());

		accountingUnifiedCustomerOrder.setRealnameId(Integer.parseInt(unifiedOrder.getPurchaseUserId().toString()));

		// dzOrder.setExamineId(examineId);
		// dzOrder.setRemark(order.get);
		// dzOrder.setMyOrderId(order.getId());

		accountingUnifiedCustomerOrder.setFinishTime(unifiedOrder.getUpdateTime());
		accountingUnifiedCustomerOrder.setCreateTime(unifiedOrder.getCreateTime());

		//add dz 1029
		accountingUnifiedCustomerOrder.setAddressAddress(unifiedOrder.getRecAddress());
		accountingUnifiedCustomerOrder.setAddressMobile(unifiedOrder.getRecUserphone());
		accountingUnifiedCustomerOrder.setAddressRealname(unifiedOrder.getRecUsername());
	}

	/**
	 * 装箱
	 *
	 * @param accountingUnifiedCustomerOrderGoods
	 * @param unifiedOrderGoods
	 * @param accountingUnifiedCustomerOrderId
	 */
	private void convertUnifiedOrderGoods2AccountingUnifiedCustomerOrderGoods(AccountingUnifiedCustomerOrderGoods accountingUnifiedCustomerOrderGoods, UnifiedOrderGoods unifiedOrderGoods, Long accountingUnifiedCustomerOrderId) {

		accountingUnifiedCustomerOrderGoods.setDzOrderId(accountingUnifiedCustomerOrderId);
		accountingUnifiedCustomerOrderGoods.setGoodId(unifiedOrderGoods.getId());

		//orderGood.setDispatchPrice(dispatchPrice);
		//orderGood.setFiscalCode(fiscalCode);
		//orderGood.setGoodno(sysGood.getGoodsName());
		accountingUnifiedCustomerOrderGoods.setOptionname(unifiedOrderGoods.getGoodsName());
		//orderGood.setTaxCode(taxCode);
		// 这个逻辑 也是错的 mark by linjinyu at 202012241722
		accountingUnifiedCustomerOrderGoods.setPrice(new BigDecimal(unifiedOrderGoods.getPrice().doubleValue() * unifiedOrderGoods.getQuantity().doubleValue()));
		accountingUnifiedCustomerOrderGoods.setTotal(unifiedOrderGoods.getQuantity());
		accountingUnifiedCustomerOrderGoods.setTotalPrice(new BigDecimal(unifiedOrderGoods.getPrice().doubleValue() * unifiedOrderGoods.getQuantity().doubleValue()));
		//orderGood.setUnit(sysGood.);
		accountingUnifiedCustomerOrderGoods.setUnitPrice(unifiedOrderGoods.getPrice());
	}


	@Override
	public AccountingUnifiedCustomer opCreateAccountingDimOrderPreProcess(Long userId, List<UnifiedOrder> unifiedOrderList, UnifiedCustomerCreateDimOrderParam unifiedCustomerCreateDimOrderParam) {

		// 1 生成对账订单实体
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


		/****************************************** 处理 AccountingUnifiedCustomerOrder start ******************************************/
		List<AccountingUnifiedCustomerOrder> accountingUnifiedCustomerOrderList = new ArrayList<>();

		for (UnifiedOrder unifiedOrder : unifiedOrderList) {

			AccountingUnifiedCustomerOrder accountingUnifiedCustomerOrder = new AccountingUnifiedCustomerOrder();

			// ConvertBeanUtil.copyBean(order, DzOrder.class); 弃用 字段差得太多
			convertUnifiedOrder2AccountingUnifiedCustomerOrder(accountingUnifiedCustomerOrder, unifiedOrder);

			accountingUnifiedCustomerOrderList.add(accountingUnifiedCustomerOrder);
		}
		/****************************************** 处理 AccountingUnifiedCustomerOrder   end ******************************************/

		UnifiedOrder firstOrder = unifiedOrderList.get(0);

		/****************************************** 处理 AccountingUnifiedCustomer start ******************************************/

		AccountingUnifiedCustomer accountingUnifiedCustomer = new AccountingUnifiedCustomer();

		// TODO 写死
		accountingUnifiedCustomer.setDateType(2);
//		accountingUnifiedCustomer.setStartTime(sdf.parse(unifiedCustomerCreateDimOrderParam.getStartTime()));
//		accountingUnifiedCustomer.setEndTime(sdf.parse(unifiedCustomerCreateDimOrderParam.getEndTime()));
		accountingUnifiedCustomer.setStartTime(unifiedCustomerCreateDimOrderParam.getStartTime());
		accountingUnifiedCustomer.setEndTime(unifiedCustomerCreateDimOrderParam.getEndTime());

		accountingUnifiedCustomer.setCycleBeginTime(unifiedCustomerCreateDimOrderParam.getStartTime());
		accountingUnifiedCustomer.setCycleEndTime(unifiedCustomerCreateDimOrderParam.getEndTime());


		// TODO 错错错 哪就不是错
		accountingUnifiedCustomer.setEnterpriseId(unifiedOrderList.get(0).getPurchaseVirtId());


		accountingUnifiedCustomer.setIsSendEmail(unifiedCustomerCreateDimOrderParam.getIsSendEmail());
		accountingUnifiedCustomer.setSendEmailTime(new Date());


		// dzMain.setInvoicetype(orders.get(0).getInvoicetype());
		// dzMain.setInvoiceTaxpayersIDCode(orders.get(0).getTaxpayersidcode());
		// dzMain.setPurchaseAddress(orders.get(0).getAddressAddress());
		// dzMain.setInvoiceCompanyName(orders.get(0).get());

		accountingUnifiedCustomer.setCreateTime(new Date());
		accountingUnifiedCustomer.setCreateUserId(userId);
		accountingUnifiedCustomer.setUpdateTime(new Date());
		accountingUnifiedCustomer.setUpdateUserId(userId);

		// add 20200110
		// TODO 写死 支付类型
		accountingUnifiedCustomer.setPayType(0);
		// TODO 写死 支付状态
		accountingUnifiedCustomer.setPayStatus(2);

		// add 20200302
		if (StringUtils.isEmpty(unifiedCustomerCreateDimOrderParam.getServiceNo())) {

			accountingUnifiedCustomer.setServiceNo(firstOrder.getServiceNo());
			accountingUnifiedCustomer.setPurchaseUserName(firstOrder.getPurchaseUserName());
			accountingUnifiedCustomer.setPurchasePhone(firstOrder.getPurchasePhone());

		} else {

			accountingUnifiedCustomer.setServiceNo(unifiedCustomerCreateDimOrderParam.getServiceNo());
			accountingUnifiedCustomer.setPurchaseUserName(unifiedCustomerCreateDimOrderParam.getPurchaseUserName());
			accountingUnifiedCustomer.setPurchasePhone(unifiedCustomerCreateDimOrderParam.getPurchasePhone());

		}

		accountingUnifiedCustomer.setPurchaseUserId(unifiedCustomerCreateDimOrderParam.getPurchaseUserId());

		// add
		accountingUnifiedCustomer.setBankInfoId(unifiedCustomerCreateDimOrderParam.getBankInfoId());

		accountingUnifiedCustomer.setAccountingAmount(unifiedCustomerCreateDimOrderParam.getDzMoney());
		accountingUnifiedCustomer.setQuantityOrder(unifiedCustomerCreateDimOrderParam.getOrderQuantity());

		accountingUnifiedCustomer.setInvoiceStatus(AccountingOrderInvoiceStatusEnum.未申请.getKey());
		// 新版 3-待提交
		accountingUnifiedCustomer.setAccountingStatus(AccountingOrderAccountingStatusEnum.待提交.getKey());
		accountingUnifiedCustomer.setBackAccountStatus(AccountingOrderBackAccountStatusEnum.未回款.getKey());

		/****************************************** 处理 AccountingUnifiedCustomer   end ******************************************/

		return opCreateAccountingDimOrder(accountingUnifiedCustomer, accountingUnifiedCustomerOrderList);
	}

	/**
	 * 新版 对账单
	 *
	 * @param accountingUnifiedCustomer
	 * @param accountingUnifiedCustomerOrderList
	 * @return
	 */
	@Transactional
	@Override
	public AccountingUnifiedCustomer opCreateAccountingDimOrder(AccountingUnifiedCustomer accountingUnifiedCustomer, List<AccountingUnifiedCustomerOrder> accountingUnifiedCustomerOrderList) {


		accountingUnifiedCustomer.setDimCreateBy(AccountingOrderDimCreateByEnum.订单.getKey());
		// 用于标记生成逻辑:10-早期(加字段时已经默认);20-改版202012
		accountingUnifiedCustomer.setLogicMode(20);

		Map<String, Object> codeMap = sysConfigService.getConfigByDZSN();
		accountingUnifiedCustomer.setAccountingOrderSn(codeMap.get("sn").toString());

		accountingUnifiedCustomerMapper.insert(accountingUnifiedCustomer);

		List<String> processOrderSn = accountingUnifiedCustomerOrderList.stream().filter(LamdaUtils.distinctByKey(o -> o.getOrderSn())).map(o -> o.getOrderSn()).collect(Collectors.toList());


		List<AccountingUnifiedCustomerXGoods> processXGoods = new ArrayList<>();


		/**
		 * 通过上一步 处理过的 accountingUnifiedCustomerOrderList 再来 返过来再 处理 unified_order 更新 客户结算状态  unified_order_goods
		 */
		for (AccountingUnifiedCustomerOrder accountingUnifiedCustomerOrder : accountingUnifiedCustomerOrderList) {

			// TODO 没有判定就入库 mark by linjinyu at 20201228
			accountingUnifiedCustomerOrder.setDzId(accountingUnifiedCustomer.getId());

			accountingUnifiedCustomerOrderMapper.insert(accountingUnifiedCustomerOrder);


			/****************************************** 单个订单 客户结算状态 更新 重构 改成批量 mark by linjinyu at 202012281757 start ******************************************/
//			UnifiedOrder order = new UnifiedOrder();
//			order.setId(accountingUnifiedCustomerOrder.getOrderId());
//			// 更新订单对账状态
//			// TODO 写死
//			order.setAccountingStateCustomer(1);
//			unifiedOrderMapper.updateByPrimaryKeySelective(order);
			/****************************************** 单个订单 客户结算状态 更新 重构 改成批量 mark by linjinyu at 202012281757   end ******************************************/


			/****************************************** 处理 正的商品 start ******************************************/
			// TODO 迷题已经解开 TAPD_ID_1000492 当时此代码屏蔽 但相关 逻辑并未修改 所以 会有可能 有些对账单 没有详情
			// change 20200302 抛弃对账下货品信息
			// TODO 20200428 linjinyu 打开 start ====================
//			Map<String, Object> queryMap = new HashMap<>();
//			queryMap.put("orderSn", accountingUnifiedCustomerOrder.getOrderSn());
//			List<UnifiedOrderGoods> unifiedOrderGoodsList = unifiedOrderGoodsMapperEx.findAll(queryMap);

			/****************************************** 重构 mark by linjinyu at 20210113 start ******************************************/
			List<UnifiedOrderGoods> unifiedOrderGoodsList = new ArrayList<>();
			unifiedOrderGoodsList = unifiedOrderGoodsService.findByOrderSn(accountingUnifiedCustomerOrder.getOrderSn());


			// 已完成  还要 更新 unified_order_goods 的客户对账状态 mark by linjinyu at 202012241719

			// 大概的作用类似批次
			Date processDate = new Date();

			for (UnifiedOrderGoods unifiedOrderGoods : unifiedOrderGoodsList) {


				/****************************************** 关联 start ******************************************/
				// 重构 mark by linjinyu at 20210113
				accountingUnifiedCustomerXGoodsService.storedAccountingUnifiedCustomerXGoods(accountingUnifiedCustomer, accountingUnifiedCustomerOrder, unifiedOrderGoods, processDate);

				/****************************************** 关联   end ******************************************/


				AccountingUnifiedCustomerOrderGoods accountingUnifiedCustomerOrderGoods = new AccountingUnifiedCustomerOrderGoods();

				// ConvertBeanUtil.copyBean(sysGood, DzOrderGood.class); 弃用
				convertUnifiedOrderGoods2AccountingUnifiedCustomerOrderGoods(accountingUnifiedCustomerOrderGoods, unifiedOrderGoods, accountingUnifiedCustomerOrder.getId());

				accountingUnifiedCustomerOrderGoodsMapper.insert(accountingUnifiedCustomerOrderGoods);
			}
			// TODO 20200428 linjinyu 打开  end  ====================


			/****************************************** 处理 正的商品   end ******************************************/


			/****************************************** 处理 运费 这个已经处理过 大概是要屏蔽 start ******************************************/
			// 判断是否运费//change 20190925
			// TODO 20200428 linjinyu 打开 start ====================
			// TODO mark by linjinyu 运费作为 商品 插入一行
			// TODO mark by linjinyu at 20201203 这个是不是有逻辑问题呀，为什么这里又加一个
//			if (accountingUnifiedCustomerOrder.getDispatchPrice().doubleValue() > 0) {
//
//				AccountingUnifiedCustomerOrderGoods accountingUnifiedCustomerOrderGoods = new AccountingUnifiedCustomerOrderGoods();
//
//				accountingUnifiedCustomerOrderGoods.setDzOrderId(accountingUnifiedCustomerOrder.getId());
//
//				accountingUnifiedCustomerOrderGoods.setOptionname("运费");
//				accountingUnifiedCustomerOrderGoods.setPrice(accountingUnifiedCustomerOrder.getDispatchPrice());
//				accountingUnifiedCustomerOrderGoods.setTotal(1);
//				accountingUnifiedCustomerOrderGoods.setTotalPrice(accountingUnifiedCustomerOrder.getDispatchPrice());
//				accountingUnifiedCustomerOrderGoods.setUnitPrice(accountingUnifiedCustomerOrder.getDispatchPrice());
//
//				accountingUnifiedCustomerOrderGoodsMapper.insert(accountingUnifiedCustomerOrderGoods);
//
//			}
			// TODO 20200428 linjinyu 打开  end  ====================
			/****************************************** 处理 运费 这个已经处理过 大概是要屏蔽   end ******************************************/


			/****************************************** 处理 退单 这个已经处理过 大概是要屏蔽 start ******************************************/
			// 判断是否有退单 change 2019-09-25
			// TODO 20200428 linjinyu 打开 start ====================
			// 查询退单 start ================================================================================
//			Map<String, Object> returnOrderSearchParams = new HashMap<>();
//			returnOrderSearchParams.put("orderSn", accountingUnifiedCustomerOrder.getOrderSn());
//			List<ViewUnifiedOrderReturn> rs = unifiedOrderReturnGoodsMapperEx.findView(returnOrderSearchParams);
//			// 查询退单 end   ================================================================================
//
//
//			// 处理退单 start ================================================================================
//			if (rs != null && rs.size() > 0) {
//
//				for (ViewUnifiedOrderReturn vr : rs) {
//
//					AccountingUnifiedCustomerOrderGoods accountingUnifiedCustomerOrderGoods = new AccountingUnifiedCustomerOrderGoods();
//
//					accountingUnifiedCustomerOrderGoods.setOptionname(vr.getGoodsName());
//					accountingUnifiedCustomerOrderGoods.setPrice(new BigDecimal(0 - (vr.getQuantity() * vr.getPrice().doubleValue())));
//					accountingUnifiedCustomerOrderGoods.setTotal(0 - vr.getQuantity());
//					accountingUnifiedCustomerOrderGoods.setTotalPrice(new BigDecimal(0 - (vr.getQuantity() * vr.getPrice().doubleValue())));
//					accountingUnifiedCustomerOrderGoods.setUnitPrice(vr.getPrice());
//					accountingUnifiedCustomerOrderGoods.setDzOrderId(accountingUnifiedCustomerOrder.getId());
//
//					accountingUnifiedCustomerOrderGoodsMapper.insert(accountingUnifiedCustomerOrderGoods);
//				}
//
//			}
			// 处理退单 end   ================================================================================
			// TODO 20200428 linjinyu 打开  end  ====================
			/****************************************** 处理 退单 这个已经处理过 大概是要屏蔽   end ******************************************/
		}

		// 更新 订单 供应商对账状态
		unifiedOrderService.updateAccountingStateCustomerByOrderSns(processOrderSn, CommonAccountingStateEnum.已对账);

		// 更新 商品 供应商对账状态
		unifiedOrderGoodsService.updateAccountingStateCustomerByOrderSn(processOrderSn, CommonAccountingStateEnum.已对账);

		// 更新 流水 供应商对账状态
//		unifiedOrderCreditService.updateAccountingStateCustomerByOrderSn(processOrderSn, CommonAccountingStateEnum.已对账);

		// 更新账单号
		sysConfigService.updateSysConfigFieldDataIntByCode(codeMap);

		return accountingUnifiedCustomer;
	}

	@Override
	public AccountingUnifiedCustomer opCreateAccountingDimGoodsPreProcess(UnifiedCustomerCreateDimGoodsParam unifiedCustomerCreateDimGoodsParam, String userId) {
		/****************************************** 构建对账单信息 start ******************************************/

		AccountingUnifiedCustomer accountingUnifiedCustomer = new AccountingUnifiedCustomer();

		// TODO 写死 这个是周期类型？1-发货时间;2-下单时间;3-完成时间;
		accountingUnifiedCustomer.setDateType(2);
		accountingUnifiedCustomer.setStartTime(unifiedCustomerCreateDimGoodsParam.getStartTime());
		accountingUnifiedCustomer.setEndTime(unifiedCustomerCreateDimGoodsParam.getEndTime());

		accountingUnifiedCustomer.setCycleBeginTime(unifiedCustomerCreateDimGoodsParam.getStartTime());
		accountingUnifiedCustomer.setCycleEndTime(unifiedCustomerCreateDimGoodsParam.getEndTime());

		//dzMain.setPurchaseAddress(orders.get(0).getAddressAddress());
		//dzMain.setInvoiceCompanyName(orders.get(0).get());


		// TODO 错错错 哪就不是错
		accountingUnifiedCustomer.setEnterpriseId(0L);


		accountingUnifiedCustomer.setCreateTime(new Date());
		accountingUnifiedCustomer.setCreateUserId(AnLongUtils.getLong(userId));
		accountingUnifiedCustomer.setUpdateTime(new Date());
		accountingUnifiedCustomer.setUpdateUserId(AnLongUtils.getLong(userId));

		// add 20200110
		// TODO 写死 支付类型
		accountingUnifiedCustomer.setPayType(0);
		// TODO 写死 支付状态
		accountingUnifiedCustomer.setPayStatus(2);


		accountingUnifiedCustomer.setInvoiceStatus(AccountingOrderInvoiceStatusEnum.未申请.getKey());
		// 新版 3-待提交
		accountingUnifiedCustomer.setAccountingStatus(AccountingOrderAccountingStatusEnum.待提交.getKey());
		accountingUnifiedCustomer.setBackAccountStatus(AccountingOrderBackAccountStatusEnum.未回款.getKey());


		/****************************************** TODO 再去细化 mark by linjinyu at 202012242028 start ******************************************/
		accountingUnifiedCustomer.setEnterpriseId(unifiedCustomerCreateDimGoodsParam.getOutVirtId());
		accountingUnifiedCustomer.setAccountingAmount(unifiedCustomerCreateDimGoodsParam.getAccountingAmount());
		accountingUnifiedCustomer.setQuantityOrder(unifiedCustomerCreateDimGoodsParam.getOrderQuantity());

		// 不自动发 邮件
//		accountingUnifiedCustomer.setIsSendEmail(unifiedCustomerCreateDimGoodsParam.getIsSendEmail());
//		accountingUnifiedCustomer.setSendEmailTime(new Date());

		// 当手动 创建 对账单的时候 订单维度的 有可能 存多个 商品维度已经作了过滤 所以 不存在这个问题
		accountingUnifiedCustomer.setServiceNo(unifiedCustomerCreateDimGoodsParam.getServiceNo());

		// 修正为 读配置？当发现不是唯一的情况下
		accountingUnifiedCustomer.setBankInfoId(unifiedCustomerCreateDimGoodsParam.getBankInfoId());
		accountingUnifiedCustomer.setPurchaseUserId(unifiedCustomerCreateDimGoodsParam.getPurchaseUserId());
		accountingUnifiedCustomer.setPurchaseUserName(unifiedCustomerCreateDimGoodsParam.getPurchaseUserName());
		accountingUnifiedCustomer.setPurchasePhone(unifiedCustomerCreateDimGoodsParam.getPurchasePhone());


		/****************************************** TODO 再去细化 mark by linjinyu at 202012242028 start ******************************************/


		/****************************************** 构建对账单信息   end ******************************************/


//		List<UnifiedCustomerCreateDimGoodsParamJsonStruct> requestParams = JsonUtils.toList(unifiedCustomerCreateDimGoodsParam.getJsonStr(), UnifiedCustomerCreateDimGoodsParamJsonStruct.class);
		List<UnifiedCustomerCreateDimGoodsParamJsonStruct> requestParams = unifiedCustomerCreateDimGoodsParam.getJsonStr();
		log.info("客户结算 创建对账单(商品维度) 包体 {}", JsonUtils.toJson(requestParams));


		return opCreateAccountingDimGoods(accountingUnifiedCustomer, requestParams);
	}

	// statementOfAccount
	@Transactional
	@Override
	public AccountingUnifiedCustomer opCreateAccountingDimGoods(AccountingUnifiedCustomer accountingUnifiedCustomer, List<UnifiedCustomerCreateDimGoodsParamJsonStruct> requestParams) {

		accountingUnifiedCustomer.setDimCreateBy(AccountingOrderDimCreateByEnum.商品.getKey());
		// 用于标记生成逻辑:10-早期;20-改版202012
		accountingUnifiedCustomer.setLogicMode(20);

		Map<String, Object> codeMap = sysConfigService.getConfigByDZSN();
		accountingUnifiedCustomer.setAccountingOrderSn(codeMap.get("sn").toString());

		// 对账单 信息在上一步已经好了
		accountingUnifiedCustomerMapper.insert(accountingUnifiedCustomer);

		/****************************************** 差异部分 Dim Goods start ******************************************/


		List<Long> processSysUnifiedOrderIds      = requestParams.stream().filter(o -> null != o.getUnifiedOrderId()).filter(LamdaUtils.distinctByKey(o -> o.getUnifiedOrderId())).map(UnifiedCustomerCreateDimGoodsParamJsonStruct::getUnifiedOrderId).collect(Collectors.toList());
		List<Long> processSysUnifiedOrderGoodsIds = requestParams.stream().filter(o -> null != o.getUnifiedOrderGoodsId()).filter(LamdaUtils.distinctByKey(o -> o.getUnifiedOrderGoodsId())).map(UnifiedCustomerCreateDimGoodsParamJsonStruct::getUnifiedOrderGoodsId).collect(Collectors.toList());
		List<Long> processOutGoodsIds             = requestParams.stream().filter(o -> null != o.getGoodsId()).filter(LamdaUtils.distinctByKey(o -> o.getGoodsId())).map(UnifiedCustomerCreateDimGoodsParamJsonStruct::getGoodsId).collect(Collectors.toList());

		List<String> processOrderSn = unifiedOrderService.convertSysUnifiedOrderIds2OrderSn(processSysUnifiedOrderIds);

		Map<Long, String>            mapSysUnifiedOrderId2OrderSn     = unifiedOrderService.convertSysUnifiedOrderIds2MapSysUnifiedOrderId2OrderSn(processSysUnifiedOrderIds);
		Map<Long, UnifiedOrderGoods> mapSysUnifiedOrderGoodsId2Entity = unifiedOrderGoodsService.convertSysUnifiedOrderGoodsIds2MapSysUnifiedOrderGoodsId2Entity(processSysUnifiedOrderGoodsIds);

		Map<String, Object> params = new HashMap<>();
		params.put("dimCreateBy", AccountingOrderDimCreateByEnum.商品.getKey());
		params.put("accountingOrderSn", accountingUnifiedCustomer.getAccountingOrderSn());
		params.put("ids", processSysUnifiedOrderIds); // 这个是 uo.id


		// 对账单 X [订单] X 商品 TODO mark by linjinyu 20201029 由于时间赶 先这样弄 一条条没效率
		for (UnifiedCustomerCreateDimGoodsParamJsonStruct structItem : requestParams) {

			AccountingUnifiedCustomerXGoods xGoods = new AccountingUnifiedCustomerXGoods();

			xGoods.setDimCreateBy(AccountingOrderDimCreateByEnum.商品.getKey());

			xGoods.setAccountingOrderId(accountingUnifiedCustomer.getId());
			xGoods.setAccountingOrderSn(accountingUnifiedCustomer.getAccountingOrderSn());

			xGoods.setUnifiedOrderId(structItem.getUnifiedOrderId());
			xGoods.setOrderSn(mapSysUnifiedOrderId2OrderSn.get(structItem.getUnifiedOrderId()));

			xGoods.setUnifiedOrderGoodsId(structItem.getUnifiedOrderGoodsId());
			xGoods.setGoodsId(mapSysUnifiedOrderGoodsId2Entity.get(structItem.getUnifiedOrderGoodsId()).getGoodsId());
			xGoods.setOutSnapshotOrderGoodsId(mapSysUnifiedOrderGoodsId2Entity.get(structItem.getUnifiedOrderGoodsId()).getOutSnapshotOrderGoodsId());

			xGoods.setCreateUserId(1L);
			xGoods.setCreateTime(new Date());
			xGoods.setUpdateUserId(1L);
			xGoods.setCreateTime(new Date());

			accountingUnifiedCustomerXGoodsMapper.insert(xGoods);

		}

		// 更新 订单 客户对账状态 -> 已对账
		unifiedOrderService.updateAccountingStateCustomerByOrderSns(processOrderSn, CommonAccountingStateEnum.已对账);

		// 更新 商品 客户对账状态 -> 已对账
		unifiedOrderGoodsService.updateAccountingStateCustomerByOrderSnAndSysUnifiedOrderGoodsIds(processOrderSn, processSysUnifiedOrderGoodsIds, CommonAccountingStateEnum.已对账);

		// 更新 流水 客户对账状态  -> 已对账 20200925 客户结算 创建对账单 如果 积分 流水 有的话 关联 更新状态 为 已对账状态
//		unifiedOrderCreditService.updateAccountingStateCustomerByOrderSnAndOutGoodsIds(processOrderSn, processOutGoodsIds, CommonAccountingStateEnum.已对账);

		// 更新账单号
		sysConfigService.updateSysConfigFieldDataIntByCode(codeMap);


		/****************************************** 差异部分 Dim Goods   end ******************************************/

		return accountingUnifiedCustomer;
	}
	/****************************************** 对账单 创建   end ******************************************/


	/****************************************** 对账单 状态 回款状态 start ******************************************/

	/**
	 * 分组 by AccountingOrderId
	 *
	 * @param invoiceOrder
	 * @return
	 */
	private Long fetchGroupKeyByAccountingOrderId(InvoiceOrder invoiceOrder) {
		return invoiceOrder.getDzId();
	}

	/**
	 * TODO 再想一下重构的问题，先顺逻辑
	 *
	 * @param invoiceX
	 */
	@Override
	public void updateFieldBackAccountStatusByInvoiceX(/*数据集为以某对账单的关联关系*/List<InvoiceOrder> invoiceX) {

		// 先判定是否存在多个对账单
		Map<Long, List<InvoiceOrder>> transferMapGroupByAccountingOrderId = invoiceX.parallelStream()
				.collect(Collectors.groupingBy(e -> fetchGroupKeyByAccountingOrderId(e), Collectors.toList()));

		Integer isManyMap = transferMapGroupByAccountingOrderId.size();

		if (isManyMap.compareTo(1) > 0) {
			log.error("此方法只能处理 1 数据集为以某1对账单的关联关系 ");
			return;
		}

		Integer invoiceXCount                = 0;
		Integer invoiceXBackAccountStatusEq1 = 0;

		invoiceXCount = invoiceX.size();
		invoiceXBackAccountStatusEq1 = AnIntegerUtils.getInteger(invoiceX.stream().filter(o -> null != o.getBackStatus() && o.getBackStatus().equals(1)).count());

		// return 为 ret 标记 不是计算数量
		if (invoiceXCount.compareTo(0) <= 0) {
			return;
		}

		if (invoiceXBackAccountStatusEq1.compareTo(0) <= 0) {
			return;
		}

		/****************************************** 不处理 未回款问题 start ******************************************/
		AccountingOrderBackAccountStatusEnum accountingOrderBackAccountStatusEnum;
		if (invoiceXCount.compareTo(invoiceXBackAccountStatusEq1) == 0) {
			accountingOrderBackAccountStatusEnum = AccountingOrderBackAccountStatusEnum.全部回款;
		} else {
			accountingOrderBackAccountStatusEnum = AccountingOrderBackAccountStatusEnum.部分回款;
		}

		List<Long> accountingOrderIds = invoiceX.stream().filter(o -> null != o.getDzId()).map(o -> o.getDzId()).collect(Collectors.toList());

		updateFieldBackAccountStatusByAccountingOrderIds(accountingOrderIds, accountingOrderBackAccountStatusEnum);


	}

	public void updateFieldBackAccountStatusByAccountingOrderIds(List<Long> accountingOrderIds, AccountingOrderBackAccountStatusEnum accountingOrderBackAccountStatusEnum) {

		AccountingUnifiedCustomerExample exampleForUpdate = new AccountingUnifiedCustomerExample();
		exampleForUpdate.createCriteria()
				.andIdIn(accountingOrderIds);

		AccountingUnifiedCustomer entityForUpdate = new AccountingUnifiedCustomer();
		entityForUpdate.setBackAccountStatus(accountingOrderBackAccountStatusEnum.getKey());

		accountingUnifiedCustomerMapper.updateByExample(entityForUpdate, exampleForUpdate);
	}
	/****************************************** 对账单 状态 回款状态   end ******************************************/

	/**
	 * 先压到这边做
	 */
	public void taskCreateAccountingDimGoods(SysQuartzScheduleTaskStatementOfAccount sysQuartzScheduleTaskStatementOfAccount) {

	}


	/****************************************** 对账单 编辑 start ******************************************/
	@Transactional
	@Override
	public void opEditAccountingDimOrder(AccountingUnifiedCustomer statementOfAccount, UnifiedOrder unifiedOrder, /* 方向 1 新增 非1 删除 加入 orderSn 对映的商品 */String add, Long userId) {

		// 要动的表有五
		// AccountingUnifiedCustomerXGoods 订单 商品 维度都有
		// AccountingUnifiedCustomerOrder 订单 维度
		// AccountingUnifiedCustomerOrderGoods 订单 维度
		// 订单
		// 商品

		List<String> processOrderSn = Arrays.asList(unifiedOrder.getOrderSn());

		List<UnifiedOrderGoods> unifiedOrderGoodsList          = unifiedOrderGoodsService.findByOrderSns(processOrderSn);
		List<Long>              processSysUnifiedOrderGoodsIds = unifiedOrderGoodsList.stream().map(o -> o.getId()).collect(Collectors.toList());

		if (add.equals("1")) {

			// 处理 对账单 订单
			AccountingUnifiedCustomerOrder accountingUnifiedCustomerOrder = new AccountingUnifiedCustomerOrder();
			convertUnifiedOrder2AccountingUnifiedCustomerOrder(accountingUnifiedCustomerOrder, unifiedOrder);
			accountingUnifiedCustomerOrder.setDzId(statementOfAccount.getId());
			accountingUnifiedCustomerOrderMapper.insert(accountingUnifiedCustomerOrder);

			// 处理 对账单 订单 商品
			// 处理 对账单 X 订单 X 商品
			// 大概的作用类似批次
			Date processDate = new Date();
			for (UnifiedOrderGoods unifiedOrderGoods : unifiedOrderGoodsList) {


				AccountingUnifiedCustomerOrderGoods accountingUnifiedCustomerOrderGoods = new AccountingUnifiedCustomerOrderGoods();

				// ConvertBeanUtil.copyBean(sysGood, DzOrderGood.class); 弃用
				convertUnifiedOrderGoods2AccountingUnifiedCustomerOrderGoods(accountingUnifiedCustomerOrderGoods, unifiedOrderGoods, accountingUnifiedCustomerOrder.getId());

				accountingUnifiedCustomerOrderGoodsMapper.insert(accountingUnifiedCustomerOrderGoods);

				/****************************************** 关联 start ******************************************/
				AccountingUnifiedCustomerXGoods xGoods = new AccountingUnifiedCustomerXGoods();

				xGoods.setDimCreateBy(AccountingOrderDimCreateByEnum.订单.getKey());

				xGoods.setAccountingOrderId(statementOfAccount.getId());
				xGoods.setAccountingOrderSn(statementOfAccount.getAccountingOrderSn());

				// 与创建时的差别
				xGoods.setUnifiedOrderId(unifiedOrder.getId());
				xGoods.setOrderSn(unifiedOrder.getOrderSn());

				xGoods.setUnifiedOrderGoodsId(unifiedOrderGoods.getId());
				xGoods.setGoodsId(unifiedOrderGoods.getGoodsId());
				xGoods.setOutSnapshotOrderGoodsId(unifiedOrderGoods.getOutSnapshotOrderGoodsId());

				xGoods.setCreateUserId(1L);
				xGoods.setCreateTime(processDate);
				xGoods.setUpdateUserId(1L);
				xGoods.setCreateTime(processDate);

				accountingUnifiedCustomerXGoodsMapper.insert(xGoods);

				/****************************************** 关联   end ******************************************/
			}


			// 更新 订单 客户对账状态 -> 已对账
			unifiedOrderService.updateAccountingStateCustomerByOrderSns(processOrderSn, CommonAccountingStateEnum.已对账);

			// 更新 商品 客户对账状态 -> 已对账
			unifiedOrderGoodsService.updateAccountingStateCustomerByOrderSnAndSysUnifiedOrderGoodsIds(processOrderSn, processSysUnifiedOrderGoodsIds, CommonAccountingStateEnum.已对账);

			// 更新 流水 客户对账状态  -> 已对账 20200925 客户结算 创建对账单 如果 积分 流水 有的话 关联 更新状态 为 已对账状态
			// unifiedOrderCreditService.updateAccountingStateCustomerByOrderSnAndOutGoodsIds(processOrderSn, processOutGoodsIds, CommonAccountingStateEnum.已对账);


		} else {

			// 处理 对账单 订单
			// 处理 对账单 订单 商品
			AccountingUnifiedCustomerOrder accountingUnifiedCustomerOrder = accountingUnifiedCustomerOrderService.findByByAccountingOrderIdAndOrderSn(statementOfAccount.getId(), unifiedOrder.getOrderSn());

			if (null != accountingUnifiedCustomerOrder) {
				accountingUnifiedCustomerOrderService.deleteByAccountingOrderIdAndOrderSn(statementOfAccount.getId(), unifiedOrder.getOrderSn());
				accountingUnifiedCustomerOrderGoodsService.deleteByAccountingUnifiedCustomerOrderId(accountingUnifiedCustomerOrder.getId());
			}

			// 处理 对账单 X 订单 X 商品
			accountingUnifiedCustomerXGoodsService.deleteByAccountingOrderIdAndOrderSn(statementOfAccount.getId(), unifiedOrder.getOrderSn());


			// 更新 订单 客户对账状态 -> 未对账
			unifiedOrderService.updateAccountingStateCustomerByOrderSns(processOrderSn, CommonAccountingStateEnum.未对账);

			// 更新 商品 客户对账状态 -> 未对账
			unifiedOrderGoodsService.updateAccountingStateCustomerByOrderSnAndSysUnifiedOrderGoodsIds(processOrderSn, processSysUnifiedOrderGoodsIds, CommonAccountingStateEnum.未对账);

			// 更新 流水 客户对账状态  -> 未对账 20200925 客户结算 创建对账单 如果 积分 流水 有的话 关联 更新状态 为 已对账状态
			// unifiedOrderCreditService.updateAccountingStateCustomerByOrderSnAndOutGoodsIds(processOrderSn, processOutGoodsIds, CommonAccountingStateEnum.未对账);

		}


		// TODO 是不需要更新对账单的订单数与金额
		checkAndFixAccountingUnifiedCustomerOfAccountingAmountOfQuantityOrder(statementOfAccount);

	}


	@Transactional
	@Override
	public void opEditAccountingDimGoods(AccountingUnifiedCustomer statementOfAccount, UnifiedOrder processUnifiedOrder, UnifiedOrderGoods processUnifiedOrderGoods, /* 方向 1 新增 非1 删除 加入 orderSn 对映的商品 */String add, Long userId) {


		// 要动的表有三
		// AccountingUnifiedCustomerXGoods 订单 商品 维度都有
		// 订单
		// 商品

		List<String> processOrderSn = Arrays.asList(processUnifiedOrder.getOrderSn());

		List<UnifiedOrderGoods> unifiedOrderGoodsList          = null;
		List<Long>              processSysUnifiedOrderGoodsIds = null;

		// 0-订单;1-商品;2-流水; 默认为1;
		Integer modeBy = 1;

		// 如果为空 说明要以 订单维度去操作
		if (null == processUnifiedOrderGoods) {
			modeBy = 0;
			unifiedOrderGoodsList = unifiedOrderGoodsService.findByOrderSns(processOrderSn);

		} else {
			modeBy = 1;
			unifiedOrderGoodsList = Arrays.asList(processUnifiedOrderGoods);
		}

		processSysUnifiedOrderGoodsIds = unifiedOrderGoodsList.stream().map(o -> o.getId()).collect(Collectors.toList());


		if (add.equals("1")) {

			// 处理 对账单 X 订单 X 商品
			// 大概的作用类似批次
			Date processDate = new Date();
			for (UnifiedOrderGoods unifiedOrderGoods : unifiedOrderGoodsList) {


				/****************************************** 关联 start ******************************************/
				AccountingUnifiedCustomerXGoods xGoods = new AccountingUnifiedCustomerXGoods();

				xGoods.setDimCreateBy(AccountingOrderDimCreateByEnum.商品.getKey());

				xGoods.setAccountingOrderId(statementOfAccount.getId());
				xGoods.setAccountingOrderSn(statementOfAccount.getAccountingOrderSn());

				// 与创建时的差别
				xGoods.setUnifiedOrderId(processUnifiedOrder.getId());
				xGoods.setOrderSn(processUnifiedOrder.getOrderSn());

				xGoods.setUnifiedOrderGoodsId(unifiedOrderGoods.getId());
				xGoods.setGoodsId(unifiedOrderGoods.getGoodsId());
				xGoods.setOutSnapshotOrderGoodsId(unifiedOrderGoods.getOutSnapshotOrderGoodsId());

				xGoods.setCreateUserId(1L);
				xGoods.setCreateTime(processDate);
				xGoods.setUpdateUserId(1L);
				xGoods.setCreateTime(processDate);

				accountingUnifiedCustomerXGoodsMapper.insert(xGoods);
				/****************************************** 关联   end ******************************************/
			}


			// 更新 订单 客户对账状态 -> 已对账
			unifiedOrderService.updateAccountingStateCustomerByOrderSns(processOrderSn, CommonAccountingStateEnum.已对账);

			// 更新 商品 客户对账状态 -> 已对账
			unifiedOrderGoodsService.updateAccountingStateCustomerByOrderSnAndSysUnifiedOrderGoodsIds(processOrderSn, processSysUnifiedOrderGoodsIds, CommonAccountingStateEnum.已对账);

			// 更新 流水 客户对账状态  -> 已对账 20200925 客户结算 创建对账单 如果 积分 流水 有的话 关联 更新状态 为 已对账状态
			// unifiedOrderCreditService.updateAccountingStateCustomerByOrderSnAndOutGoodsIds(processOrderSn, processOutGoodsIds, CommonAccountingStateEnum.已对账);


		} else {

			// 处理 对账单 X 订单 X 商品
			accountingUnifiedCustomerXGoodsService.deleteByAccountingOrderIdAndOrderSnAndSysUnifiedOrderGoodsIds(statementOfAccount.getId(), processUnifiedOrder.getOrderSn(), processSysUnifiedOrderGoodsIds);

			// 更新 订单 客户对账状态 -> 未对账
			unifiedOrderService.updateAccountingStateCustomerByOrderSns(processOrderSn, CommonAccountingStateEnum.未对账);

			// 更新 商品 客户对账状态 -> 未对账
			unifiedOrderGoodsService.updateAccountingStateCustomerByOrderSnAndSysUnifiedOrderGoodsIds(processOrderSn, processSysUnifiedOrderGoodsIds, CommonAccountingStateEnum.未对账);

			// 更新 流水 客户对账状态  -> 未对账 20200925 客户结算 创建对账单 如果 积分 流水 有的话 关联 更新状态 为 已对账状态
			// unifiedOrderCreditService.updateAccountingStateCustomerByOrderSnAndOutGoodsIds(processOrderSn, processOutGoodsIds, CommonAccountingStateEnum.未对账);

		}


		// TODO 是不需要更新对账单的订单数与金额
		checkAndFixAccountingUnifiedCustomerOfAccountingAmountOfQuantityOrder(statementOfAccount);
	}

	/****************************************** 对账单 编辑   end ******************************************/

	@Override
	public List<SysOrder> findAllFromOrder(Map<String, Object> queryMap) {

		return accountingUnifiedCustomerMapperExSys.findAllFromOrder(queryMap);
	}

	@Override
	public List<String> findRealNamesByOrder(Map<String, Object> queryMap) {

		return accountingUnifiedCustomerMapperExSys.findRealNamesByOrder(queryMap);
	}

	@Override
	public R<List<DzMainAutoPage>> findAllViewPage(Map<String, Object> params, int pageNo, int pageSize) {

		PageHelper.startPage(pageNo, pageSize);

		List<DzMainAutoPage> ls = accountingUnifiedCustomerMapperEx.findAllView(params);

		PageInfo<DzMainAutoPage> page = new PageInfo<DzMainAutoPage>(ls);

		PageHelper.clearPage();

		return new R<List<DzMainAutoPage>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), ls);

	}

	@Override
	public R<List<ViewSysOrder>> findOrderViewPage(Map<String, Object> params, int pageNo, int pageSize) {

		PageHelper.startPage(pageNo, pageSize);
		List<ViewSysOrder>     ls   = accountingUnifiedCustomerMapperExSys.findViewFromOrder(params);
		PageInfo<ViewSysOrder> page = new PageInfo<ViewSysOrder>(ls);
		PageHelper.clearPage();
		return new R<List<ViewSysOrder>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), ls);

	}

	@Override
	public ReportOrderQA findReportFromOrder(Map<String, Object> params) {

		return accountingUnifiedCustomerMapperExSys.findReportFromOrder(params);
	}

	@Override
	public List<ViewSysOrderGoods> findOrderViewGoods(SysOrderQuery params) {

		return accountingUnifiedCustomerMapperExSys.findViewFromOrderGoods(params);
	}


	/****************************************** 对账单 详情 start ******************************************/

	public void checkAndFixAccountingUnifiedCustomerOfAccountingAmountOfQuantityOrder(AccountingUnifiedCustomer statementOfAccount) {


		List<CustomerStatementOfAccountDetailItemVo> viewDzorderList = null;

		switch (AccountingOrderDimCreateByEnum.get(statementOfAccount.getDimCreateBy())) {
			case 订单:

				viewDzorderList = getCustomerStatementOfAccountDetailFillItemDimOrder2Goods(statementOfAccount.getId());
				break;
			case 商品:

				viewDzorderList = getCustomerStatementOfAccountDetailFillItemDimGoods2Goods(statementOfAccount.getId());
				break;
			case 流水:
				break;
		}

		if (CollectionUtils.isEmpty(viewDzorderList)) {
			return;
		}

		BigDecimal goodsAmount = viewDzorderList
				.stream()
				.map(item -> item.getPrice() == null ? BigDecimal.ZERO : item.getPrice().multiply(new BigDecimal(item.getQuantity())))
				.reduce(BigDecimal.ZERO, BigDecimal::add);
		BigDecimal goodsCostAmount = viewDzorderList
				.stream()
				.map(item -> item.getCostPrice() == null ? BigDecimal.ZERO : item.getCostPrice().multiply(new BigDecimal(item.getQuantity())))
				.reduce(BigDecimal.ZERO, BigDecimal::add);

		Integer quantityOrder = 0;
		quantityOrder = viewDzorderList.stream().filter(LamdaUtils.distinctByKey(o -> o.getOrderSn())).collect(Collectors.toList()).size();


		AccountingUnifiedCustomer forUpdate = new AccountingUnifiedCustomer();
		forUpdate.setId(statementOfAccount.getId());
		forUpdate.setAccountingAmount(goodsAmount);
		forUpdate.setQuantityOrder(quantityOrder);

		accountingUnifiedCustomerMapper.updateByPrimaryKeySelective(forUpdate);

	}

	@Override
	public CustomerStatementOfAccountDetailVo getCustomerStatementOfAccountDetailDimOrder2Goods(Long accountingOrderId) {

		Map<String, Object> params = new HashMap<>();
		// accounting_unified_customer.id
		params.put("id", accountingOrderId);

		// 用id 查询，只会有一个吧? NND 这不就是accounting_unified_customer吗?还这样写,唉,没空改,但这有点弱智
		List<CustomerStatementOfAccountDetailVo> customerStatementOfAccountDetailVoList = accountingUnifiedCustomerMapperEx.getAccountingUnifiedCustomerView(params);


		if (CollectionUtils.isEmpty(customerStatementOfAccountDetailVoList)) {
			return null;
		} else {


			/****************************************** 填充对账单信息 start ******************************************/
			CustomerStatementOfAccountDetailVo customerStatementOfAccountDetailVo = customerStatementOfAccountDetailVoList.get(0);

			// 填充 收货人信息
			customerStatementOfAccountDetailVoFillPurchaseInfo(customerStatementOfAccountDetailVo);

			// 填充 企业信息 项目信息
			customerStatementOfAccountDetailVoFillVirtInfo(customerStatementOfAccountDetailVo);

			// 填充 收款方 信息
			customerStatementOfAccountDetailVoFillBankinfo(customerStatementOfAccountDetailVo);
			/****************************************** 填充对账单信息   end ******************************************/


			/****************************************** 填充对账单 订单商品信息 TODO 待重构 将弃用 start ******************************************/
			List<CustomerStatementOfAccountDetailItemVo> viewDzorderList = getCustomerStatementOfAccountDetailFillItemDimOrder2Goods(customerStatementOfAccountDetailVo.getId());

			customerStatementOfAccountDetailItemVoFillInvoiceInfo(viewDzorderList);

			customerStatementOfAccountDetailVo.setOrders(viewDzorderList);
			/****************************************** 填充对账单 订单信息 TODO 待重构 将弃用   end ******************************************/

			return customerStatementOfAccountDetailVo;

		}

	}

	public List<CustomerStatementOfAccountDetailItemVo> getCustomerStatementOfAccountDetailFillItemDimOrder2Goods(Long accountingOrderId) {

		Map<String, Object> paramsOrder = new HashMap<>();
		paramsOrder.put("dzId", accountingOrderId);
		// 目前是这样拉数据 TODO 待重构
//			accounting_unified_customer_order auco
//			LEFT JOIN unified_order uo ON auco.order_sn = uo.order_sn
//			LEFT JOIN unified_order_goods uog ON uo.order_sn = uog.order_sn
		List<CustomerStatementOfAccountDetailItemVo> viewDzorderList = accountingUnifiedCustomerMapperEx.getCustomerStatementOfAccountDetailFillItemDimOrder2Goods(paramsOrder);

		return viewDzorderList;
	}

	public List<CustomerStatementOfAccountDetailItemVo> getCustomerStatementOfAccountDetailFillItemDimGoods2Goods(Long accountingOrderId) {

		List<CustomerStatementOfAccountDetailItemVo> viewDzorderList = accountingUnifiedCustomerMapperEx.getCustomerStatementOfAccountDetailFillItemDimGoods2Goods(accountingOrderId);

		return viewDzorderList;
	}

	@Override
	public CustomerStatementOfAccountDetailVo getCustomerStatementOfAccountDetailDimGoods2Goods(Long accountingOrderId) {

		/****************************************** 填充对账单信息 start ******************************************/

		AccountingUnifiedCustomer accountingUnifiedCustomer = findById(accountingOrderId);

		if (null == accountingUnifiedCustomer) {
			return null;
		}

		CustomerStatementOfAccountDetailVo customerStatementOfAccountDetailVo = BeanUtils.copy(accountingUnifiedCustomer, CustomerStatementOfAccountDetailVo.class);

		log.info("观察COPY情况 \n{}\n{}", JsonUtils.toJson(accountingUnifiedCustomer), JsonUtils.toJson(customerStatementOfAccountDetailVo));

		// 填充 收货人信息
		customerStatementOfAccountDetailVoFillPurchaseInfo(customerStatementOfAccountDetailVo);

		// 填充 企业信息 项目信息
		customerStatementOfAccountDetailVoFillVirtInfo(customerStatementOfAccountDetailVo);

		// 填充 收款方 信息
		customerStatementOfAccountDetailVoFillBankinfo(customerStatementOfAccountDetailVo);

		/****************************************** 填充对账单信息   end ******************************************/


		/****************************************** 填充对账单 订单信息 start ******************************************/
		List<CustomerStatementOfAccountDetailItemVo> viewDzorderList = getCustomerStatementOfAccountDetailFillItemDimGoods2Goods(customerStatementOfAccountDetailVo.getId());

		customerStatementOfAccountDetailItemVoFillInvoiceInfo(viewDzorderList);

		customerStatementOfAccountDetailVo.setOrders(viewDzorderList);
		/****************************************** 填充对账单 订单信息   end ******************************************/

		return customerStatementOfAccountDetailVo;
	}

	private void customerStatementOfAccountDetailVoFillPurchaseInfo(CustomerStatementOfAccountDetailVo customerStatementOfAccountDetailVo) {
		SysOderUser orderUser = sysOderUserMapper.selectByUserId(customerStatementOfAccountDetailVo.getPurchaseUserId());

		if (orderUser != null) {
			customerStatementOfAccountDetailVo.setPurchaseUserName(orderUser.getRealname());
			customerStatementOfAccountDetailVo.setPurchasePhone(orderUser.getMobile());
			customerStatementOfAccountDetailVo.setBillEmail(orderUser.getBillEmail());
		}
	}

	private void customerStatementOfAccountDetailVoFillVirtInfo(CustomerStatementOfAccountDetailVo customerStatementOfAccountDetailVo) {
		SysEnterprise enterprise = sysEnterpriseMapperEx.findByVirtId(customerStatementOfAccountDetailVo.getEnterpriseId());
		if (enterprise != null) {

			customerStatementOfAccountDetailVo.setProjectId(enterprise.getOrganizationId());

			SysOrganization organization = sysOrganizationMapper.selectByOrgId(enterprise.getOrganizationId());
			if (organization != null) {
				customerStatementOfAccountDetailVo.setProjectName(organization.getOrganizationName());
			}

			customerStatementOfAccountDetailVo.setEnterpriseName(enterprise.getEnterpriseName());
		}
	}

	private void customerStatementOfAccountDetailVoFillBankinfo(CustomerStatementOfAccountDetailVo customerStatementOfAccountDetailVo) {

		if (null != customerStatementOfAccountDetailVo.getBankInfoId()) {
			UnifiedBankInfo    bankInfo           = unifiedBankInfoMapper.selectByPrimaryKey(customerStatementOfAccountDetailVo.getBankInfoId());
			ViewDzMainBankInfo viewDzMainBankInfo = BeanUtils.copy(bankInfo, ViewDzMainBankInfo.class);
			customerStatementOfAccountDetailVo.setBankInfo(viewDzMainBankInfo);
		} else {
			ViewDzMainBankInfo viewDzMainBankInfo = new ViewDzMainBankInfo();
			viewDzMainBankInfo.setCompanyName("楼宇云仓商贸（深圳）有限公司");
			viewDzMainBankInfo.setBankAccount("7559 4355 0010 501");
			viewDzMainBankInfo.setBankName("招商银行深圳福华路支行");
			viewDzMainBankInfo.setSupplyName("深圳市超级前台信息技术有限公司");
			viewDzMainBankInfo.setTel("400-8386-065");
			viewDzMainBankInfo.setAddress("深圳市 福田区 深南中路3024号 航空大厦32层7-11室");

			customerStatementOfAccountDetailVo.setBankInfo(viewDzMainBankInfo);
		}
	}

	private void customerStatementOfAccountDetailItemVoFillInvoiceInfo(List<CustomerStatementOfAccountDetailItemVo> viewDzorderList) {

		for (CustomerStatementOfAccountDetailItemVo orderItem : viewDzorderList) {

			// 临时 查找 发票信息
			Map<String, Object> invQuery = new HashMap<>();
			invQuery.put("orderSn", orderItem.getOrderSn());
			List<InvoiceApply> invoiceApplyList = invoiceApplyMapperEx.findInvoiceByOrderSn(invQuery);

			if (invoiceApplyList != null && invoiceApplyList.size() == 1) {

				orderItem.setInvNumber(invoiceApplyList.get(0).getInvoiceNumber());
				orderItem.setInvSn(invoiceApplyList.get(0).getInvoiceNo());
			}
		}
	}

	/****************************************** 对账单 详情   end ******************************************/

	@Override
	public R<List<CustomerStatementOfAccountDetailVo>> getAccountingUnifiedCustomerViewByPage(Map<String, Object> params, int pageNo, int pageSize) {

		PageHelper.startPage(pageNo, pageSize);

		List<CustomerStatementOfAccountDetailVo> viewDzMainList = accountingUnifiedCustomerMapperEx.getAccountingUnifiedCustomerView(params);

		PageInfo<CustomerStatementOfAccountDetailVo> page = new PageInfo<CustomerStatementOfAccountDetailVo>(viewDzMainList);

		PageHelper.clearPage();

		return new R<List<CustomerStatementOfAccountDetailVo>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), viewDzMainList);

	}

	/**
	 * TODO 坑资源
	 *
	 * @param params
	 * @return
	 */
	@Override
	public ReportOrderQA getAccountingUnifiedCustomerViewHead(Map<String, Object> params) {

		// 这个是没有分页的 是全部的数据
		// TODO 所以问题 TAPD_ID_1000679_【PC端】对账单（客户结算、供应商结算）账单金额计算时剔除已取消、已拒绝状态对账单金额及数量
		// 在此加条件就可以达到了
		List<CustomerStatementOfAccountDetailVo> viewDzMainList = accountingUnifiedCustomerMapperEx.getAccountingUnifiedCustomerView(params);

		if (CollectionUtils.isNotEmpty(viewDzMainList)) {

			// 对账单 ID
			List<String> ids = new ArrayList<>();

			for (CustomerStatementOfAccountDetailVo item : viewDzMainList) {
				ids.add(item.getId().toString());
			}

			Map<String, Object> dzOrderQueryParams = new HashMap<>();
			if (ids.size() > 0) {
				dzOrderQueryParams.put("dzids", ids.toArray());
			}

			ReportOrderQA qa = accountingUnifiedCustomerOrderMapperEx.getReportQuantity(dzOrderQueryParams);

			qa.setDzquantity(viewDzMainList.size());

			return qa;

		} else {

			ReportOrderQA qa = new ReportOrderQA();

			qa.setAmount(new BigDecimal(0));
			qa.setDzquantity(0);
			qa.setQuantity(0);
			qa.setRealamount(new BigDecimal(0));
			qa.setReturnamount(new BigDecimal(0));

			return qa;
		}


	}

	@Override
	public List<ViewSysOrderJoinGoods> findOrderViewGoodsTb(Map<String, Object> params) {

		return accountingUnifiedCustomerMapperExSys.findOrderViewGoodsTb(params);
	}

	/**
	 * 订单 维度
	 * @param id
	 * @param dzState
	 */
	@Transactional
	@Override
	public void optAccountingCustomerActionCancel(Long id, Integer dzState) {

		/****************************************** 查出这个对账单 关联的 订单 中间表数据 start ******************************************/
		Map<String, Object> params = new HashMap<>();
		params.put("dzId", id);
		List<AccountingUnifiedCustomerOrder> accountingUnifiedCustomerOrderList = accountingUnifiedCustomerOrderMapperEx.findAll(params);

		for (AccountingUnifiedCustomerOrder accountingUnifiedCustomerOrder : accountingUnifiedCustomerOrderList) {

			// 老的订单是这样修正对账状态
//			SysOrder order =new SysOrder();
//			order.setId(item.getOrderId());
//			order.setIsGenBill(Byte.valueOf("0"));
//			orderMapper.updateByPrimaryKeySelective(order);

			UnifiedOrder unifiedOrder = unifiedOrderMapperEx.selectByPrimaryOrderSn(accountingUnifiedCustomerOrder.getOrderSn());

			// TODO 坑位 20200715 by linjinyu
			// 为什么 要加这个判定
			// 超级前台的人员有可以做错单，要求后端人员去数据库删除原始订单 而这个 对账单 X 订单 的中意数据 是没有处理的 ，也没有重新核算对账单
			if (null != unifiedOrder) {
				UnifiedOrder order = new UnifiedOrder();
				order.setId(unifiedOrder.getId());
				order.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
				order.setUpdateTime(new Date());
				unifiedOrderMapper.updateByPrimaryKeySelective(order);
			}
		}

		AccountingUnifiedCustomer accountingUnifiedCustomer = new AccountingUnifiedCustomer();

		accountingUnifiedCustomer.setId(id);
		accountingUnifiedCustomer.setAccountingStatus(dzState);

		accountingUnifiedCustomerMapper.updateByPrimaryKeySelective(accountingUnifiedCustomer);
	}

	@Override
	public List<CustomerStatementOfAccountDetailVo> getDzMainView(Map<String, Object> params) {

		return accountingUnifiedCustomerMapperEx.getAccountingUnifiedCustomerView(params);
	}

	/***
	 * 订单列表
	 */
	@Override
	public R<List<ExpSysOrder>> getOrderViewByPage(SysOrderQuery params, int pageNo, int pageSize) {

		PageHelper.startPage(pageNo, pageSize);
		//List<ExpSysOrder> ls = dzOrderMapper.findOrderView(params);//findViewFromOrderGoods(params);
		List<ExpSysOrder> ls = accountingUnifiedCustomerOrderMapperEx.findSysOrderGoods(params);

		PageInfo<ExpSysOrder> page = new PageInfo<ExpSysOrder>(ls);
		PageHelper.clearPage();
		return new R<List<ExpSysOrder>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), ls);

	}

	@Override
	public R<List<ExpSysOrder>> getOrderViewByPageProject(SysOrderQuery params, int pageNo, int pageSize) {

		PageHelper.startPage(pageNo, pageSize);
		//List<ExpSysOrder> ls = dzOrderMapper.findOrderView(params);//findViewFromOrderGoods(params);
		List<ExpSysOrder> ls = accountingUnifiedCustomerOrderMapperEx.findSysOrderGoodsProject(params);

		PageInfo<ExpSysOrder> page = new PageInfo<ExpSysOrder>(ls);
		PageHelper.clearPage();
		return new R<List<ExpSysOrder>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), ls);

	}

	/***
	 * 导出对账单EXCEL-根据对账单查询结果
	 */
	public List<CustomerStatementOfAccountDetailItemVo> getDzMainViewExcel(Map<String, Object> params) {

		List<CustomerStatementOfAccountDetailVo> accountingUnifiedCustomerViewList = accountingUnifiedCustomerMapperEx.getAccountingUnifiedCustomerView(params);

		List<String> ids = new ArrayList<>();

		for (CustomerStatementOfAccountDetailVo item : accountingUnifiedCustomerViewList) {
			ids.add(item.getId().toString());
		}

		Map<String, Object> paramsFindAccountingOrderUnified = new HashMap<>();
		if (ids.size() > 0) {
			paramsFindAccountingOrderUnified.put("dzIds", ids.toArray());
		}

		List<CustomerStatementOfAccountDetailItemVo> dzOrders = accountingUnifiedCustomerMapperEx.findAllDzOrderView(paramsFindAccountingOrderUnified);

		return dzOrders;
	}

	@Override
	public ReportOrderQA getOrderReportData(SysOrderQuery query) {

		return accountingUnifiedCustomerMapperExSys.getOrderReportData(query);
	}

	@Override
	public ReportOrderQA getOrderReportDataDeath(SysOrderQuery query) {

		ReportOrderQA qa = accountingUnifiedCustomerMapperExSys.getOrderReportDataDeath(query);
		qa.setReturnamount(accountingUnifiedCustomerMapperExSys.getOrderReturnAmountDeath(query).getAmount());
		qa.setRealamount(qa.getAmount().subtract(qa.getReturnamount()));
		return qa;
	}

	@Deprecated
	@Override
	public List<ExpSysOrder> findOrderViewExcel(Map<String, Object> params) {

		List<ViewSysOrder> ls  = accountingUnifiedCustomerMapperExSys.findViewFromOrder(params);
		List<String>       ids = new ArrayList<String>();
		for (ViewSysOrder item : ls) {
			ids.add(item.getId().toString());
		}
		Map<String, Object> paramsOrder = new HashMap<>();
		if (ids.size() > 0) {
			paramsOrder.put("oIds", ids.toArray());
		}
		List<ExpSysOrder> resLs = accountingUnifiedCustomerOrderMapperEx.findOrderViewExcel(paramsOrder);
		return resLs;
	}

	/***
	 * 导出订单列表
	 */
	@Override
	public List<ExpSysOrder> getOrderViewExcel(SysOrderQuery query) {

//		List<ViewSysOrderGoods> ls = dzMainMapper.findViewFromOrderGoods(query);
//		List<String> ids = new ArrayList<String>();
//		for (ViewSysOrderGoods item : ls) {
//			ids.add(item.getId().toString());
//		}
//		Map<String, Object> params_order = new HashMap<>();
//		if(ids.size()>0) {
//			params_order.put("oIds", ids.toArray());
//		}
		List<ExpSysOrder> resLs = accountingUnifiedCustomerOrderMapperEx.getOrderViewExcel(query);
		return resLs;
		//return dzOrderMapper.findSysOrderGoods(query);
	}

	@Override
	public SysInvoiceOrder findInvByOrderId(Long id) {

		return accountingUnifiedCustomerOrderMapperEx.findInvByOrderId(id);
	}

}
