package cn.superdesk.uniorder.dubbo.provider.accounting.customer;

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.enums.common.CommonServiceNoEnum;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.enums.pay.UnifiedOrderPayStateEnum;
import cn.superdesk.uniorder.common.enums.pay.UnifiedOrderPayTypeEnum;
import cn.superdesk.uniorder.common.enums.accounting.customer.AccountingOrderCustomerAccountingStatusEnum;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderBackAccountStatusEnum;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderInvoiceApplyStatusEnum;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderIsSendEmailEnum;
import cn.superdesk.uniorder.dao.entity.accounting.unified.customer.AccountingUnifiedCustomer;
import cn.superdesk.uniorder.dao.entity.accounting.unified.customer.AccountingUnifiedCustomerOrder;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderGoods;
import cn.superdesk.uniorder.dao.entity.order.ExpressCompany;
import cn.superdesk.uniorder.dao.entity.order.OrderSourceType;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterprise;
import cn.superdesk.uniorder.dao.entity.organisation.SysOrganization;
import cn.superdesk.uniorder.dao.entity.sys.SysInvoice;
import cn.superdesk.uniorder.dao.entity.sys.SysOderUser;
import cn.superdesk.uniorder.dao.entity.sys.SysOrder;
import cn.superdesk.uniorder.dao.entity.sys.SysUser;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.dto.param.accounting.unified.customer.UnifiedCustomerCreateDimGoodsParam;
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.SysOrderQuery;
import cn.superdesk.uniorder.dubbo.facade.accounting.customer.DubboAccountingUnifiedCustomerService;
import cn.superdesk.uniorder.service.accounting.unified.customer.*;
import cn.superdesk.uniorder.service.order.base.UnifiedOrderService;
import cn.superdesk.uniorder.service.common.OrderSourceTypeService;
import cn.superdesk.uniorder.service.order._leaveover.ExpressCompanyService;
import cn.superdesk.uniorder.service.order._leaveover.SysInvoiceService;
import cn.superdesk.uniorder.service.order.old.SysOrderService;
import cn.superdesk.uniorder.service.organisation.SysEnterpriseService;
import cn.superdesk.uniorder.service.organisation.SysOrganizationService;
import cn.superdesk.uniorder.service.sys.SysOderUserService;
import cn.superdesk.uniorder.service.sys.SysUserService;

import cn.superdesk.uniorder.common.lamda.AnLamdaUtils;
import cn.superdesk.uniorder.common.numerical.AnConvertBeanUtil;
import com.alibaba.dubbo.config.annotation.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service(version = "1.0.0", retries = -1, timeout = 60000)
public class DubboAccountingUnifiedCustomerServiceImpl implements DubboAccountingUnifiedCustomerService {

	@Autowired
	private AccountingUnifiedCustomerService                 accountingUnifiedCustomerService;
	@Autowired
	private AccountingUnifiedCustomerServiceOpCreateDimGoods accountingUnifiedCustomerServiceOpCreateDimGoods;
	@Autowired
	private AccountingUnifiedCustomerServiceOpCreateDimOrder accountingUnifiedCustomerServiceOpCreateDimOrder;
	@Autowired
	private AccountingUnifiedCustomerServiceOpEditDimGoods   accountingUnifiedCustomerServiceOpEditDimGoods;
	@Autowired
	private AccountingUnifiedCustomerServiceOpEditDimOrder   accountingUnifiedCustomerServiceOpEditDimOrder;
	@Autowired
	private AccountingUnifiedCustomerServiceCommon           accountingUnifiedCustomerServiceCommon;

	@Autowired
	private AccountingUnifiedOrderCustomerService accountingUnifiedOrderCustomerService;

	@Autowired
	private SysInvoiceService      sysInvoiceService;
	@Autowired
	private SysOrganizationService sysOrganizationService;
	@Autowired
	private SysEnterpriseService   sysEnterpriseService;
	@Autowired
	private SysUserService         sysUserService;
	@Autowired
	private SysOderUserService     sysOderUserService;
	@Autowired
	private SysOrderService        sysOrderService;

	@Autowired
	private OrderSourceTypeService orderSourceTypeService;


	@Autowired
	private UnifiedOrderService unifiedOrderService;

	@Autowired
	private ExpressCompanyService expressCompanyService;


	/****************************************** 自动 生成对账单 start ******************************************/


	@Override
	public AccountingUnifiedCustomer addAuto(String company, Long realnameId, Integer dateType, String startTime, String endTime, LoginSysUser loginSysUser) throws Exception {


		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		// 1 查找订单
		Map<String, Object> queryMap = new HashMap<>();
		queryMap.put("enterpriseId", Long.parseLong(company));
		queryMap.put("startTime", startTime);
		queryMap.put("endTime", endTime);
		queryMap.put("realnameId", realnameId);
		queryMap.put("dateType", dateType);
		queryMap.put("isGenBill", Byte.valueOf("0"));
		List<SysOrder> sysOrderList = accountingUnifiedCustomerService.findAllFromOrder(queryMap);

		// TODO 如果没数据呢？要处理呀 mark by linjinyu at 20201218

		// 2 生成对账订单实体
		List<AccountingUnifiedCustomerOrder> dzOrders = new ArrayList<>();
		for (SysOrder order : sysOrderList) {
			AccountingUnifiedCustomerOrder dzOrder = AnConvertBeanUtil.copyBean(order, AccountingUnifiedCustomerOrder.class);
			dzOrder.setId(null);
			dzOrder.setOrderId(order.getId());
			// TODO 这个字段是重构前是真的,但对映的数据库字段是没有的
//			dzOrder.setMyOrderId(order.getMyOrderId());
			dzOrders.add(dzOrder);
		}

		AccountingUnifiedCustomer accountingUnifiedCustomer = new AccountingUnifiedCustomer();
		accountingUnifiedCustomer.setDateType(Integer.valueOf(dateType.toString()));
		accountingUnifiedCustomer.setPurchaseAddress(sysOrderList.get(0).getAddressAddress());
		accountingUnifiedCustomer.setInvoiceCompanyName(sysOrderList.get(0).getCompanyname());
		accountingUnifiedCustomer.setBackAccountStatus(AccountingOrderBackAccountStatusEnum.未回款.getKey());
		accountingUnifiedCustomer.setInvoiceStatus(AccountingOrderInvoiceApplyStatusEnum.未申请.getKey());
		// 因为自动对账 所以是没有 3-待提交
		accountingUnifiedCustomer.setAccountingStatus(AccountingOrderCustomerAccountingStatusEnum.未确认.getKey());
		accountingUnifiedCustomer.setEndTime(sdf.parse(endTime));

		// TODO 错错错?
		accountingUnifiedCustomer.setEnterpriseId(Long.valueOf(company));

		accountingUnifiedCustomer.setInvoiceType(Integer.valueOf(sysOrderList.get(0).getInvoicetype()));
		accountingUnifiedCustomer.setIsSendEmail(AccountingOrderIsSendEmailEnum.未发送.getKey());
		accountingUnifiedCustomer.setPurchaseUserId(realnameId);
		accountingUnifiedCustomer.setStartTime(sdf.parse(startTime));
		accountingUnifiedCustomer.setInvoiceTaxpayersIDCode(sysOrderList.get(0).getTaxpayersidcode());

		accountingUnifiedCustomer.setCreateTime(DateUtil.date());
		accountingUnifiedCustomer.setCreateUserId(loginSysUser.getSysUserId());
		accountingUnifiedCustomer.setUpdateTime(DateUtil.date());
		accountingUnifiedCustomer.setUpdateUserId(loginSysUser.getSysUserId());

		return accountingUnifiedCustomerServiceOpCreateDimOrder.addTran(accountingUnifiedCustomer, dzOrders);
	}

	/****************************************** 自动 生成对账单   end ******************************************/

	/**
	 * 旧版 创建 对账单(结算单) ---- 客户结算
	 *
	 * @param userId
	 * @param sysOrderList
	 * @param startTime
	 * @param endTime
	 * @param dateType
	 * @param isSendEmail
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	@Override
	public AccountingUnifiedCustomer addDzMain(Long userId, List<SysOrder> sysOrderList, String startTime, String endTime, Integer dateType, Integer isSendEmail) throws Exception {

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

		List<AccountingUnifiedCustomerOrder> dzOrders = new ArrayList<>();

		for (SysOrder sysOrder : sysOrderList) {
			AccountingUnifiedCustomerOrder accountingUnifiedCustomerOrder = AnConvertBeanUtil.copyBean(sysOrder, AccountingUnifiedCustomerOrder.class);
			accountingUnifiedCustomerOrder.setId(null);
			accountingUnifiedCustomerOrder.setOrderId(sysOrder.getId());
			// TODO 这个字段是重构前是真的,但对映的数据库字段是没有的
//			dzOrder.setMyOrderId(order.getMyOrderId());
			dzOrders.add(accountingUnifiedCustomerOrder);
		}

		AccountingUnifiedCustomer accountingUnifiedCustomer = new AccountingUnifiedCustomer();
		accountingUnifiedCustomer.setDateType(Integer.valueOf(dateType.toString()));

		accountingUnifiedCustomer.setPurchaseAddress(sysOrderList.get(0).getAddressAddress());
		accountingUnifiedCustomer.setInvoiceCompanyName(sysOrderList.get(0).getCompanyname());

		accountingUnifiedCustomer.setInvoiceStatus(AccountingOrderInvoiceApplyStatusEnum.未申请.getKey());

		// 因为旧版 所以是没有 3-待提交
		accountingUnifiedCustomer.setAccountingStatus(AccountingOrderCustomerAccountingStatusEnum.未确认.getKey());
		accountingUnifiedCustomer.setBackAccountStatus(AccountingOrderBackAccountStatusEnum.未回款.getKey());
		accountingUnifiedCustomer.setEndTime(sdf.parse(endTime));

		accountingUnifiedCustomer.setEnterpriseId(sysOrderList.get(0).getEnterpriseId());
		accountingUnifiedCustomer.setInvoiceType(Integer.valueOf(sysOrderList.get(0).getInvoicetype()));

		accountingUnifiedCustomer.setIsSendEmail(isSendEmail);
		accountingUnifiedCustomer.setSendEmailTime(DateUtil.date());

		accountingUnifiedCustomer.setPurchaseUserId(sysOrderList.get(0).getRealnameId());
		accountingUnifiedCustomer.setStartTime(sdf.parse(startTime));

		accountingUnifiedCustomer.setInvoiceTaxpayersIDCode(sysOrderList.get(0).getTaxpayersidcode());

		accountingUnifiedCustomer.setCreateTime(DateUtil.date());
		accountingUnifiedCustomer.setCreateUserId(userId);
		accountingUnifiedCustomer.setUpdateTime(DateUtil.date());
		accountingUnifiedCustomer.setUpdateUserId(userId);

		return accountingUnifiedCustomerServiceOpCreateDimOrder.addTran(accountingUnifiedCustomer, dzOrders);
	}


	/****************************************** 对账单 创建 start ******************************************/
	/**
	 * 客户结算 对账单 创建 ---- 新版
	 *
	 * @param userId
	 * @param unifiedOrderList
	 * @param unifiedCustomerCreateDimOrderParam
	 * @return
	 * @throws Exception
	 */
	@Override
	public AccountingUnifiedCustomer opCreateAccountingDimOrder(Long userId, List<UnifiedOrder> unifiedOrderList, UnifiedCustomerCreateDimOrderParam unifiedCustomerCreateDimOrderParam) throws Exception {

		return accountingUnifiedCustomerServiceOpCreateDimOrder.opCreateAccountingDimOrderPreProcess(userId, unifiedOrderList, unifiedCustomerCreateDimOrderParam);
	}

	@Override
	public AccountingUnifiedCustomer opCreateAccountingDimGoods(UnifiedCustomerCreateDimGoodsParam unifiedCustomerCreateDimGoodsParam, LoginSysUser loginSysUser) {

		return accountingUnifiedCustomerServiceOpCreateDimGoods.opCreateAccountingDimGoodsPreProcess(unifiedCustomerCreateDimGoodsParam, loginSysUser);

	}
	/****************************************** 对账单 创建   end ******************************************/


	/****************************************** 对账单 编辑 start ******************************************/
	@Override
	public void opEditAccountingDimOrder(AccountingUnifiedCustomer statementOfAccount, UnifiedOrder unifiedOrder, String add, LoginSysUser loginSysUser) {
		accountingUnifiedCustomerServiceOpEditDimOrder.opEditAccountingDimOrder(statementOfAccount, unifiedOrder, add, loginSysUser);
	}

	@Override
	public void opEditAccountingDimGoods(AccountingUnifiedCustomer statementOfAccount, UnifiedOrder unifiedOrder, UnifiedOrderGoods unifiedOrderGoods, String add, LoginSysUser loginSysUser) {
		accountingUnifiedCustomerServiceOpEditDimGoods.opEditAccountingDimGoods(statementOfAccount, unifiedOrder, unifiedOrderGoods, add, loginSysUser);
	}
	/****************************************** 对账单 编辑   end ******************************************/

	/****************************************** 对账单 详情 start ******************************************/
	@Override
	public CustomerStatementOfAccountDetailVo getCustomerStatementOfAccountDetailDimOrder2Goods(Long accountingOrderId) {

		return accountingUnifiedCustomerServiceCommon.getCustomerStatementOfAccountDetailDimOrder2Goods(accountingOrderId);
	}

	@Override
	public CustomerStatementOfAccountDetailVo getCustomerStatementOfAccountDetailDimGoods2Goods(Long accountingOrderId) {
		return accountingUnifiedCustomerServiceCommon.getCustomerStatementOfAccountDetailDimGoods2Goods(accountingOrderId);
	}

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

	@Override
	public List<String> findRealNamesByOrder(String company, Integer dateType, String startTime, String endTime) {

		Map<String, Object> queryMap = new HashMap<>();
		queryMap.put("enterpriseId", Long.parseLong(company));
		queryMap.put("startTime", startTime);
		queryMap.put("endTime", endTime);
		queryMap.put("dateType", dateType);
		return accountingUnifiedCustomerService.findRealNamesByOrder(queryMap);
	}

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

		R<List<DzMainAutoPage>> rrls = accountingUnifiedCustomerService.findAllViewPage(params, pageNo, pageSize);

		for (DzMainAutoPage item : rrls.getData()) {
			SysEnterprise enterprise = sysEnterpriseService.findById(item.getEnterpriseId());
			if (enterprise != null)
				item.setEnterpriseName(enterprise.getEnterpriseName());
		}

		return rrls;
	}

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

		R<List<ViewSysOrder>> rrls = accountingUnifiedCustomerService.findOrderViewPage(params, pageNo, pageSize);
		for (ViewSysOrder item : rrls.getData()) {
			SysEnterprise enterprise = sysEnterpriseService.findById(item.getEnterpriseId());
			if (enterprise != null)
				item.setEnterpriseName(enterprise.getEnterpriseName());
			SysOderUser orderUser = sysOderUserService.selectByUserId(Long.parseLong(item.getRealnameId().toString()));
			if (orderUser != null) {
				item.setRealname(orderUser.getRealname());
				item.setMobile(orderUser.getMobile());
			}
			OrderSourceType sourceType = orderSourceTypeService.findById(Long.parseLong(item.getOrderType().toString()));
			item.setOrderTypeName(sourceType.getSourceName());
		}

		return rrls;
	}

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

		return accountingUnifiedCustomerService.findReportFromOrder(params);
	}

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

		return accountingUnifiedCustomerService.findOrderViewGoods(params);
	}

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

		return accountingUnifiedCustomerService.findAllFromOrder(queryMap);
	}


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

		R<List<CustomerStatementOfAccountDetailVo>> result = accountingUnifiedCustomerService.getAccountingUnifiedCustomerViewByPage(queryMap, pageNo, pageSize);


		/****************************************** 补充信息 start ******************************************/


		/****************************************** 填充 人的信息 start ******************************************/
		List<Long> sysUserIds = new ArrayList<>();

		List<Long> createUserIds = result.getData().stream().filter(o -> o.getCreateUserId() != null).filter(AnLamdaUtils.distinctByKey(o -> o.getCreateUserId())).map(o -> o.getCreateUserId()).collect(Collectors.toList());
		List<Long> updateUserIds = result.getData().stream().filter(o -> o.getUpdateUserId() != null).filter(AnLamdaUtils.distinctByKey(o -> o.getUpdateUserId())).map(o -> o.getUpdateUserId()).collect(Collectors.toList());

		sysUserIds.addAll(createUserIds);
		sysUserIds.addAll(updateUserIds);

		sysUserIds = sysUserIds.stream().distinct().collect(Collectors.toList());

		log.info("\n{}", AnJsonUtils.toJson(sysUserIds));

		Map<Long, SysUser> sysUserMap = sysUserService.convertSysUserIds2MapSysUserId2Entity(sysUserIds);

		log.info("\n{}", AnJsonUtils.toJson(sysUserMap));

		/****************************************** 填充 人的信息   end ******************************************/

		/****************************************** 填充 企业信息 start ******************************************/

		List<Long> sysVirtIds = new ArrayList<>();
		sysVirtIds = result.getData().stream().filter(o -> null != o.getEnterpriseId()).filter(AnLamdaUtils.distinctByKey(o -> o.getEnterpriseId())).map(o -> o.getEnterpriseId()).collect(Collectors.toList());

		log.info("\n{}", AnJsonUtils.toJson(sysVirtIds));

		Map<Long, SysEnterprise> sysEnterpriseMap = sysEnterpriseService.convertOutVirtIds2MapOutVirtId2Entity(sysVirtIds);

		/****************************************** 填充 企业信息   end ******************************************/

		// 修正显示
		for (CustomerStatementOfAccountDetailVo vo : result.getData()) {

			vo.setAccountingStatusName(AccountingOrderCustomerAccountingStatusEnum.getDesc(vo.getAccountingStatus()));
			vo.setInvoiceStatusName(AccountingOrderInvoiceApplyStatusEnum.getDesc(vo.getInvoiceStatus()));
			vo.setServiceName(CommonServiceNoEnum.getByServiceNo(vo.getServiceNo()).getServiceName());

			// 再补个

			if (sysUserMap.get(vo.getCreateUserId()) != null) {
				vo.setCreateUserName(sysUserMap.get(vo.getCreateUserId()).getFullname());
			} else if (vo.getCreateUserId().equals(1L)) {
				vo.setCreateUserName("系统");
			}

			if (sysUserMap.get(vo.getUpdateUserId()) != null) {
				vo.setUpdateUserName(sysUserMap.get(vo.getUpdateUserId()).getFullname());
			} else if (vo.getUpdateUserId().equals(1L)) {
				vo.setUpdateUserName("系统");
			}

			// TODO 填充 企业名称 已作缓存 基于 sys_enterprise id
			// 弃 缓存已清

			// 重构 mark by linjinyu at 20210202
//			SysEnterprise enterprise = sysEnterpriseService.findByVirtId(vo.getEnterpriseId());
//			if (enterprise != null) {
//				vo.setEnterpriseName(enterprise.getEnterpriseName());
//				vo.setEnterpriseNo(enterprise.getEnterpriseNo());
//			}

			// 重构为
			if (sysEnterpriseMap.get(vo.getEnterpriseId()) != null) {
				vo.setEnterpriseName(sysEnterpriseMap.get(vo.getEnterpriseId()).getEnterpriseName());
				vo.setEnterpriseNo(sysEnterpriseMap.get(vo.getEnterpriseId()).getEnterpriseNo());
			}

			vo.setAccountingStatusName(AccountingOrderCustomerAccountingStatusEnum.getDesc(vo.getAccountingStatus()));
			vo.setInvoiceStatusName(AccountingOrderInvoiceApplyStatusEnum.getDesc(vo.getInvoiceStatus()));

			vo.setBackAccountStatusName(AccountingOrderBackAccountStatusEnum.getDesc(vo.getBackAccountStatus()));

			// TODO 这个与订单的状态共用吗? 要再去验证一下 mark by linjinjy 202007151500
			vo.setPayStatusName(UnifiedOrderPayStateEnum.getDesc(vo.getPayStatus()));
			vo.setPayTypeName(UnifiedOrderPayTypeEnum.getDesc(vo.getPayType()));


//			SysOderUser orderUser = oderUserService.selectByUserId(Long.parseLong(item.getRealnameId().toString()));
//			if (orderUser != null) {
//				item.setRealname(orderUser.getRealname());
//				item.setMobile(orderUser.getMobile());
//				item.setBillEmail(orderUser.getBillEmail());
//			}
		}
		/****************************************** 补充信息   end ******************************************/


		return result;
	}

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

		return accountingUnifiedCustomerService.getAccountingUnifiedCustomerViewHead(params);
	}

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

		return accountingUnifiedCustomerService.findOrderViewGoodsTb(params);
	}

	@Override
	public AccountingUnifiedCustomer findById(Long id) {

		return accountingUnifiedCustomerService.findById(id);
	}

	/**
	 * 动作 重新对账
	 * 动作 取消对账 (相当于)
	 * <p>
	 * setAccountingStatus ? -> -1
	 *
	 * @param id
	 */
	@Override
	public void optAccountingCustomerActionCancel(Long id) {

		// 对账单 对账状态 审核向的
		accountingUnifiedCustomerService.optAccountingCustomerActionCancel(id, AccountingOrderCustomerAccountingStatusEnum.已取消);
	}

	/**
	 * 动作 拒绝对账
	 * 动作 取消对账 (相当于)
	 * <p>
	 * setAccountingStatus ? -> 2
	 *
	 * @param id
	 * @param userId
	 */
	@Override
	public void optAccountingCustomerActionRefuse(Long id, LoginSysUser loginSysUser) {

		// 对账单 对账状态 审核向的
		accountingUnifiedCustomerService.optAccountingCustomerActionCancel(id, AccountingOrderCustomerAccountingStatusEnum.已拒绝);
	}

	/**
	 * 动作-提交对账
	 *
	 * @param id
	 * @param userId
	 */
	@Override
	public void optAccountingCustomerActionSubmit(Long id, LoginSysUser loginSysUser) {

		AccountingUnifiedCustomer main = new AccountingUnifiedCustomer();

		main.setId(id);
		main.setAccountingStatus(AccountingOrderCustomerAccountingStatusEnum.未确认.getKey());
		main.setUpdateTime(DateUtil.date());
		main.setUpdateUserId(loginSysUser.getSysUserId());

		accountingUnifiedCustomerService.updateByPrimaryKeySelective(main);
	}

	/**
	 * 动作 确认对账
	 * <p>
	 * setAccountingStatus ? -> 1
	 *
	 * @param id
	 * @param userId
	 */
	@Override
	public void optAccountingCustomerActionConfirm(Long id, LoginSysUser loginSysUser) {

		AccountingUnifiedCustomer accountingUnifiedCustomer = new AccountingUnifiedCustomer();

		accountingUnifiedCustomer.setId(id);
		accountingUnifiedCustomer.setAccountingStatus(AccountingOrderCustomerAccountingStatusEnum.已确认.getKey());

		accountingUnifiedCustomer.setUpdateTime(DateUtil.date());
		accountingUnifiedCustomer.setUpdateUserId(loginSysUser.getSysUserId());

		accountingUnifiedCustomerService.updateByPrimaryKeySelective(accountingUnifiedCustomer);
	}

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

		return accountingUnifiedCustomerService.getDzMainView(params);
	}

	//	@Override
//	public ResponseResult<List<ViewSysOrderGoods>> getOrderViewByPage(SysOrderQuery params, int pageNum,
//			int pageSize) {
//
//		ResponseResult<List<ViewSysOrderGoods>> rrls = mainService.getOrderViewByPage(params,pageNum,pageSize);
//		for (ViewSysOrderGoods item : rrls.getData()) {
//			SysEnterprise enterprise = enterpriseService.findById(item.getEnterpriseId());
//			if(enterprise!=null)
//				item.setEnterpriseName(enterprise.getEnterpriseName());
//			SysOderUser orderUser= oderUserService.selectByUserId(Long.parseLong(item.getRealnameId().toString()));
//			if(orderUser!=null) {
//				item.setRealname(orderUser.getRealname());
//				item.setMobile(orderUser.getMobile());
//			}
//			OrderSourceType sourceType = sourceTypeService.findById(Long.parseLong(item.getOrderType().toString()));
//			item.setOrderTypeName(sourceType.getSourceName());
//		}
//		return rrls;
//	}
	@Override
	public R<List<ExpSysOrder>> getOrderViewByPage(SysOrderQuery params, int pageNum, int pageSize) {

		R<List<ExpSysOrder>> rrls = accountingUnifiedCustomerService.getOrderViewByPage(params, pageNum, pageSize);

		for (ExpSysOrder item : rrls.getData()) {
			//订单
			fillExpSysOrder(item);
		}
		return rrls;
	}

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

		R<List<ExpSysOrder>> rrls = accountingUnifiedCustomerService.getOrderViewByPageProject(params, pageNum, pageSize);
		for (ExpSysOrder item : rrls.getData()) {
			//订单
			fillExpSysOrder(item);
		}
		return rrls;
	}

	/**
	 * 标记 这个是导出excel用？
	 *
	 * @param params
	 * @return
	 */
	@Deprecated
	@Override
	public List<CustomerStatementOfAccountDetailItemVo> getDzMainViewExcel(Map<String, Object> params) {

		return accountingUnifiedCustomerService.getDzMainViewExcel(params);
	}

	@Override
	public ReportOrderQA getOrderReportData(SysOrderQuery query) {

		return accountingUnifiedCustomerService.getOrderReportData(query);
	}

	@Override
	public ReportOrderQA getOrderReportDataDeath(SysOrderQuery query) {

		return accountingUnifiedCustomerService.getOrderReportDataDeath(query);
	}


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

		List<ExpSysOrder> ls = accountingUnifiedCustomerService.findOrderViewExcel(params);
//		if(ls!=null&&ls.size()>0) {
//			for (ExpSysOrder item : ls) {
//				fillExpSysOrder(item);
//			}
//		}
		return ls;
	}

	@Override
	public List<ExpSysOrder> getOrderViewExcel(SysOrderQuery query) {

//		List<ExpSysOrder> ls= mainService.getOrderViewExcel(query);
//		if(ls!=null&&ls.size()>0) {
//			for (ExpSysOrder item : ls) {
//				fillExpSysOrder(item);
//			}
//		}

		return accountingUnifiedCustomerService.getOrderViewExcel(query);
	}


	@Deprecated
	public void fillExpSysOrder(ExpSysOrder expSysOrder) {

		List<SysOrder> orders = sysOrderService.findByOrderId(expSysOrder.getSysOrderId());

		if (orders != null && orders.size() > 0) {

			SysOrder order = orders.get(0);

			expSysOrder.setId(order.getId());
			expSysOrder.setDetailUrl(order.getDetailUrl());


			OrderSourceType sourceType = orderSourceTypeService.findById(Long.parseLong(expSysOrder.getOrderType().toString()));
			expSysOrder.setOrderTypeName(sourceType.getSourceName());
			expSysOrder.setOrderType(order.getOrderType());

			expSysOrder.setParentOrdersn(order.getParentOrdersn());
			expSysOrder.setOrdersn(order.getOrdersn());

			List<SysOrganization> orgs = sysOrganizationService.findByOutOrgId(order.getOrganizationId());
			if (orgs != null && orgs.size() > 0) {
				expSysOrder.setOrganizationName(orgs.get(0).getOrganizationName());
			}

			SysEnterprise enterprise = sysEnterpriseService.findById(order.getEnterpriseId());
			if (enterprise != null) {
				expSysOrder.setEnterpriseName(enterprise.getEnterpriseName());
			}

			expSysOrder.setPrice(order.getPrice());
//			expSysOrder.setPaytypeName(UnifiedOrderPayTypeEnum.getDesc(order.getPaytype()));

			switch (order.getPaytype()) {
				case 0:
					expSysOrder.setPaytypeName("未支付");
					break;
				case 1:
					expSysOrder.setPaytypeName("余额支付");
					break;
				case 2:
					expSysOrder.setPaytypeName("在线支付");
					break;
				case 3:
					expSysOrder.setPaytypeName("企业月结");
					break;
				case 11:
					expSysOrder.setPaytypeName("后台付款");
					break;
				case 21:
					expSysOrder.setPaytypeName("微信支付");
					break;
				case 22:
					expSysOrder.setPaytypeName("支付宝支付");
					break;
				case 23:
					expSysOrder.setPaytypeName("银联支付");
					break;

				default:
					expSysOrder.setPaytypeName("未支付");
					break;
			}
			switch (order.getStatus()) {
				case -1:
					expSysOrder.setStatusName("已关闭");
					break;
				case 0:
					expSysOrder.setStatusName("待付款");
					break;
				case 1:
					expSysOrder.setStatusName("待发货");
					break;
				case 2:
					expSysOrder.setStatusName("待收货");
					break;
				case 3:
					expSysOrder.setStatusName("已完成");
					break;
				default:
					expSysOrder.setStatusName("已关闭");
					break;
			}

			SysOderUser orderUser = sysOderUserService.selectByUserId(Long.parseLong(order.getRealnameId().toString()));
			if (orderUser != null) {
				expSysOrder.setRealname(orderUser.getRealname());
				expSysOrder.setMobile(orderUser.getMobile());
			}

			expSysOrder.setAddressAddress(order.getAddressAddress());
			expSysOrder.setCreatetime(order.getCreatetime());
			expSysOrder.setMerchName(order.getMerchName());
			expSysOrder.setRemark(order.getRemark());

			expSysOrder.setAddressMobile(order.getAddressMobile());
			expSysOrder.setAddressRealname(order.getAddressRealname());

			if (order.getInvoicetype() == 1) {
				expSysOrder.setInvoicetypeName("增值税普票");
			} else {
				expSysOrder.setInvoicetypeName("增值税专票");
			}

			expSysOrder.setInvoiceCompanyName(order.getCompanyname());
			expSysOrder.setSendtime(order.getSendtime());
			expSysOrder.setFinishtime(order.getFinishtime());

			Map<String, Object> doQueryMap = new HashMap<>();
			doQueryMap.put("orderId", order.getId());
			List<AccountingUnifiedCustomerOrder> dzOrders = accountingUnifiedOrderCustomerService.findAll(doQueryMap);
			if (AnCollectionUtils.isNotEmpty(dzOrders)) {
				AccountingUnifiedCustomer dzMain = accountingUnifiedCustomerService.findById(dzOrders.get(0).getDzId());

				// TODO 写死
				if (dzMain != null && dzMain.getAccountingStatus().equals(1)) {

					Map<String, Object> invQueryMap = new HashMap<>();
					invQueryMap.put("orderId", dzOrders.get(0).getId());
					List<SysInvoice> invoices = sysInvoiceService.findAll(invQueryMap);
					if (invoices != null && invoices.size() > 0) {
						SysInvoice     invoice        = invoices.get(0);
						ExpressCompany expressCompany = expressCompanyService.findById(invoice.getExpressCompanyId());
						if (expressCompany != null) {
							expSysOrder.setCompanyName(expressCompany.getCompanyName());
						}

						expSysOrder.setExpressNo(invoice.getExpressNo());
						expSysOrder.setInvoiceNumber(invoice.getInvoiceNumber());
						expSysOrder.setInvoiceTime(invoice.getInvoiceTime());
						switch (invoice.getInvoiceStatus()) {
							case 0:
								expSysOrder.setInvoiceStatusName("未邮寄");
								break;
							case 1:
								expSysOrder.setInvoiceStatusName("已邮寄");
								break;
							case 2:
								expSysOrder.setInvoiceStatusName("已作废");
								break;
							default:
								expSysOrder.setInvoiceStatusName("未邮寄");
								break;
						}
					}
				}
			}
		}
	}


	/**
	 * 客户结算-对账单-opt 导出报表(对账单)
	 *
	 * @param params
	 * @return
	 */
	@Override
	public List<ViewDzOrderExcel> getDzOrderExcel(Map<String, Object> params) {

		return accountingUnifiedOrderCustomerService.getDzOrderExcel(params);
	}

	@Override
	public AccountingUnifiedCustomerOrder findOrderById(Long dzOrderId) {
		return accountingUnifiedOrderCustomerService.findById(dzOrderId);
	}

	@Override
	public AccountingUnifiedCustomer findByAccountingOrderSn(String accountingOrderSn) {
		return accountingUnifiedCustomerService.findByAccountingOrderSn(accountingOrderSn);
	}


	@Override
	public List<UnifiedOrder> getUnifiedOrderByDzId(Map<String, Object> params) {
		return unifiedOrderService.findByDzId(params);
	}

	@Override
	public List<AccountingUnifiedCustomerOrder> getDzOrderAll(Map<String, Object> dzOrderMap) {
		return accountingUnifiedOrderCustomerService.findAll(dzOrderMap);
	}

	@Override
	public void updateObj(AccountingUnifiedCustomer statementOfAccount4Update, LoginSysUser loginSysUser) {
		accountingUnifiedCustomerService.updateByPrimaryKeySelective(statementOfAccount4Update);
	}

	/**
	 * 只更新业务字段
	 *
	 * @param statementOfAccount4Update
	 * @param loginSysUser
	 */
	@Override
	public void updateFieldRemark(AccountingUnifiedCustomer statementOfAccount4Update, LoginSysUser loginSysUser) {

		statementOfAccount4Update.setUpdateUserId(loginSysUser.getSysUserId());
		statementOfAccount4Update.setUpdateTime(DateUtil.date());

		accountingUnifiedCustomerService.updateByPrimaryKeySelective(statementOfAccount4Update);
	}

	/**
	 * 只更新业务字段
	 *
	 * @param parseLong
	 */
	@Override
	public void updateFieldSendEmailTime(Long parseLong) {

		AccountingUnifiedCustomer accountingUnifiedCustomer = new AccountingUnifiedCustomer();

		accountingUnifiedCustomer.setId(parseLong);
		accountingUnifiedCustomer.setSendEmailTime(DateUtil.date());
		accountingUnifiedCustomer.setIsSendEmail(AccountingOrderIsSendEmailEnum.已发送.getKey());

		accountingUnifiedCustomerService.updateByPrimaryKeySelective(accountingUnifiedCustomer);
	}


	/****************************************** 补丁程序 start ******************************************/
	@Override
	public void patchXDimOrder2DimGoods(String accountingOrderSn) {
		accountingUnifiedCustomerService.patchXDimOrder2DimGoods(accountingOrderSn);
	}

	@Override
	public void patchXAccountingAmountAndQuantityOrderAndQuantityGoods(String accountingOrderSn) {
		accountingUnifiedCustomerService.patchXAccountingAmountAndQuantityOrderAndQuantityGoods(accountingOrderSn);
	}
	/****************************************** 补丁程序   end ******************************************/


}
