package cn.superdesk.uniorder.service.accounting.unified.supplier.Impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderDimCreateByEnum;
import cn.superdesk.uniorder.common.enums.accounting.customer.AccountingOrderCustomerAccountingStatusEnum;
import cn.superdesk.uniorder.common.enums.accounting.supplier.AccountingOrderSupplierAccountingStatusEnum;
import cn.superdesk.uniorder.common.enums.common.CommonAccountingStateEnum;
import cn.superdesk.uniorder.common.enums.common.CommonNeedReviseMarkEnum;
import cn.superdesk.uniorder.common.enums.common.CommonServiceNoEnum;
import cn.superdesk.uniorder.common.enums.common.CommonSourceFromEnum;
import cn.superdesk.uniorder.common.enums.invoice.supplier.InvoiceApplySupplierInvoiceProgressingStatusEnum;
import cn.superdesk.uniorder.common.enums.invoice.supplier.InvoiceApplySupplierPayOffAccountStatusEnum;
import cn.superdesk.uniorder.common.exception.UnifiedOrderRuntimeException;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.lamda.AnLamdaUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.dao.convert.DtoSugarUpUtils;
import cn.superdesk.uniorder.dao.entity.accounting.unified.supplier.*;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderExample;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderGoods;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderGoodsExample;
import cn.superdesk.uniorder.dao.entity.sys.SysUser;
import cn.superdesk.uniorder.dao.mapper.accounting.unified.supplier.*;
import cn.superdesk.uniorder.dao.mapper.base.*;
import cn.superdesk.uniorder.dto.param.accounting.unified.supplier.AccountingOrderUnifiedSupplierQueryCriteria;
import cn.superdesk.uniorder.dto.vo.accounting.unified.supplier.AccountingOrderUnifiedSuplierHeadVo;
import cn.superdesk.uniorder.dto.vo.accounting.unified.supplier.AccountingOrderUnifiedSupplierListItemVo;
import cn.superdesk.uniorder.service.accounting.unified.supplier.AccountingUnifiedSupplierService;
import cn.superdesk.uniorder.service.accounting.unified.supplier.AccountingUnifiedSupplierServiceOpStatistics;
import cn.superdesk.uniorder.service.accounting.unified.supplier.AccountingUnifiedSupplierXGoodsService;
import cn.superdesk.uniorder.service.order.base.UnifiedOrderCreditService;
import cn.superdesk.uniorder.service.order.base.UnifiedOrderGoodsService;
import cn.superdesk.uniorder.service.order.base.UnifiedOrderService;
import cn.superdesk.uniorder.service.invoice.supplier.InvoiceApplySupplierService;
import cn.superdesk.uniorder.service.setting.UnifiedSnConfigService;
import cn.superdesk.uniorder.service.sys.SysUserService;
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.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;


/**
 * @Description: 供应商结算-对账单
 * @Author: linjinyu 补充与修改
 * @CreateDate: 4/24/20 2:16 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 4/24/20 2:16 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class AccountingUnifiedSupplierServiceImpl implements AccountingUnifiedSupplierService {

    @Autowired
    private UnifiedOrderMapper                   unifiedOrderMapper;
    @Autowired
    private UnifiedOrderMapperEx                 unifiedOrderMapperEx;
    @Autowired
    private UnifiedOrderMapperExSupplierDimOrder unifiedOrderMapperExSupplierDimOrder;
    @Autowired
    private UnifiedOrderService                  unifiedOrderService;

    @Autowired
    private UnifiedOrderGoodsMapper   unifiedOrderGoodsMapper;
    @Autowired
    private UnifiedOrderGoodsMapperEx unifiedOrderGoodsMapperEx;
    @Autowired
    private UnifiedOrderGoodsService  unifiedOrderGoodsService;

    @Autowired
    private UnifiedOrderCreditMapper  unifiedOrderCreditMapper;
    @Autowired
    private UnifiedOrderCreditService unifiedOrderCreditService;

    @Autowired
    private AccountingUnifiedSupplierMapper   accountingUnifiedSupplierMapper;
    @Autowired
    private AccountingUnifiedSupplierMapperEx accountingUnifiedSupplierMapperEx;

    @Autowired
    private AccountingUnifiedSupplierOrderMapper    accountingUnifiedSupplierOrderMapper;
    @Autowired
    private AccountingUnifiedSupplierXOrderMapperEx accountingUnifiedSupplierXOrderMapperEx;

    @Autowired
    private AccountingUnifiedSupplierXGoodsMapper   accountingUnifiedSupplierXGoodsMapper;
    @Autowired
    private AccountingUnifiedSupplierXGoodsMapperEx accountingUnifiedSupplierXGoodsMapperEx;

    @Autowired
    private AccountingUnifiedSupplierXGoodsService accountingUnifiedSupplierXGoodsService;

    @Autowired
    private AccountingUnifiedSupplierServiceOpStatistics accountingUnifiedSupplierServiceOpStatistics;

    @Autowired
    private UnifiedSnConfigService unifiedSnConfigService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private InvoiceApplySupplierService invoiceApplySupplierService;

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

        return null;
    }

    @Override
    public void deleteObj(Long id) {

        accountingUnifiedSupplierMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(AccountingUnifiedSupplier statementOfAccount) {

        return accountingUnifiedSupplierMapper.updateByPrimaryKeySelective(statementOfAccount);
    }


    /**
     * 申请状态 // 通过 开票申请的流程进度推进 反过来再更新 对账单的开票申请的流程进度
     *
     * @param accountingOrderId
     * @param invoiceApplySupplierInvoiceProgressingStatusEnum
     * @param loginSysUser
     * @return
     */
    @Override
    public int updateFieldInvoiceStatus(
            Long accountingOrderId,
            InvoiceApplySupplierInvoiceProgressingStatusEnum invoiceApplySupplierInvoiceProgressingStatusEnum,
            LoginSysUser loginSysUser) {

        AccountingUnifiedSupplier forUpdate = new AccountingUnifiedSupplier();
        forUpdate.setId(accountingOrderId);

        forUpdate.setInvoiceStatus(invoiceApplySupplierInvoiceProgressingStatusEnum.getKey());
        forUpdate.setUpdateUserId(loginSysUser.getSysUserId());
        forUpdate.setUpdateTime(DateUtil.date());

        return accountingUnifiedSupplierMapper.updateByPrimaryKeySelective(forUpdate);
    }

    /**
     * 付款状态
     *
     * @param accountingOrderId
     * @param invoiceApplySupplierPayOffAccountStatusEnum
     * @param loginSysUser
     * @return
     */
    @Override
    public int updateFieldBackAccountStatus(
            Long accountingOrderId,
            InvoiceApplySupplierPayOffAccountStatusEnum invoiceApplySupplierPayOffAccountStatusEnum,
            LoginSysUser loginSysUser) {
        AccountingUnifiedSupplier forUpdate = new AccountingUnifiedSupplier();
        forUpdate.setId(accountingOrderId);

        forUpdate.setBackAccountStatus(invoiceApplySupplierPayOffAccountStatusEnum.getKey());
        forUpdate.setUpdateUserId(loginSysUser.getSysUserId());
        forUpdate.setUpdateTime(DateUtil.date());

        return accountingUnifiedSupplierMapper.updateByPrimaryKeySelective(forUpdate);
    }

    @Override
    public AccountingUnifiedSupplier findById(Long id) {

        return accountingUnifiedSupplierMapper.selectByPrimaryKey(id);
    }

    @Override
    public AccountingUnifiedSupplier findByAccountingOrderSn(String accountingOrderSn) {

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

        List<AccountingUnifiedSupplier> result = accountingUnifiedSupplierMapper.selectByExample(example);

        if (CollUtil.isNotEmpty(result)) {
            return result.get(0);
        }

        return null;


    }

    @Override
    public int insertSelective(AccountingUnifiedSupplier statementOfAccount) {

        return accountingUnifiedSupplierMapper.insert(statementOfAccount);
    }

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

        return null;
    }

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

        PageHelper.startPage(pageNo, pageSize);
        List<AccountingOrderUnifiedSupplierListItemVo>     resultList = accountingUnifiedSupplierMapperEx.getStatementOfAccountList(params);
        PageInfo<AccountingOrderUnifiedSupplierListItemVo> page       = new PageInfo<AccountingOrderUnifiedSupplierListItemVo>(resultList);
        PageHelper.clearPage();

        additionalInfoAccountingOrderUnifiedSupplierListItemVo(resultList);

        DtoSugarUpUtils.sugarUpUnifiedSupplierStatementOfAccountVo(resultList);

        /**************************************** 补丁程序 start ****************************************/

        /**
         * mark by linjinyu at 2022-05-139 06:56:45 脱钩 转 xxl job 发起
         // 修正 v2.1 统计信息
         patchNeedReviseMarkStatistics(resultList, LoginSysUser.builder().build());

         // 修正 v2.3 serviceNo sourceFrom
         patchNeedReviseMarkServiceNoSourceFrom(resultList, LoginSysUser.builder().build());
         */

        /**************************************** 补丁程序   end ****************************************/

        return new R<List<AccountingOrderUnifiedSupplierListItemVo>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), resultList);
    }

    public R<List<AccountingOrderUnifiedSupplierListItemVo>> pageQueryAccountingOrderUnifiedSupplierList(AccountingOrderUnifiedSupplierQueryCriteria queryCriteria) {

        PageHelper.startPage(queryCriteria.getPageNumber(), queryCriteria.getPageSize());
        List<AccountingOrderUnifiedSupplierListItemVo>     resultList = accountingUnifiedSupplierMapperEx.getStatementOfAccountList(queryCriteria);
        PageInfo<AccountingOrderUnifiedSupplierListItemVo> page       = new PageInfo<AccountingOrderUnifiedSupplierListItemVo>(resultList);
        PageHelper.clearPage();

        additionalInfoAccountingOrderUnifiedSupplierListItemVo(resultList);

        // 金额 格式化
        DtoSugarUpUtils.sugarUpUnifiedSupplierStatementOfAccountVo(resultList);

        /**************************************** 补丁程序 start ****************************************/

        /**
         * mark by linjinyu at 2022-05-139 06:56:45 脱钩 转 xxl job 发起
         // 修正 v2.1 统计信息
         patchNeedReviseMarkStatistics(resultList, LoginSysUser.builder().build());

         // 修正 v2.3 serviceNo sourceFrom
         patchNeedReviseMarkServiceNoSourceFrom(resultList, LoginSysUser.builder().build());
         */

        /**************************************** 补丁程序   end ****************************************/

        return new R<List<AccountingOrderUnifiedSupplierListItemVo>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), resultList);
    }

    /**
     * 查询勾选的数据，导出报表
     *
     * @param queryCriteria
     * @param loginSysUser
     * @return
     */
    @Override
    public List<AccountingOrderUnifiedSupplierListItemVo> queryAccountingOrderUnifiedSupplierList(
            AccountingOrderUnifiedSupplierQueryCriteria queryCriteria,
            LoginSysUser loginSysUser) {

        List<AccountingOrderUnifiedSupplierListItemVo> resultList = new ArrayList<>();

        resultList = accountingUnifiedSupplierMapperEx.getStatementOfAccountList(queryCriteria);

        additionalInfoAccountingOrderUnifiedSupplierListItemVo(resultList);

        // 金额 格式化
        DtoSugarUpUtils.sugarUpUnifiedSupplierStatementOfAccountVo(resultList);

        /**************************************** 补丁程序 start ****************************************/


        /**
         * mark by linjinyu at 2022-05-20 15:01:45 脱钩 转 xxl job 发起
         // 修正 v2.1 统计信息
         patchNeedReviseMarkStatistics(resultList, LoginSysUser.builder().build());

         // 修正 v2.3 serviceNo sourceFrom
         patchNeedReviseMarkServiceNoSourceFrom(resultList, LoginSysUser.builder().build());
         */

        /**************************************** 补丁程序   end ****************************************/

        return resultList;
    }

    public void patchNeedReviseMarkStatistics(List<AccountingOrderUnifiedSupplierListItemVo> resultList, LoginSysUser loginSysUser) {


        log.info("进入 patchNeedReviseMarkStatistics");

        if (CollUtil.isEmpty(resultList)) {
            return;
        }

        resultList.forEach(vo -> {

            if (ObjectUtil.isNotNull(vo.getNeedReviseMark())
                    && vo.getNeedReviseMark().compareTo(CommonNeedReviseMarkEnum.修正.getKey()) == 0) {

                if (AccountingOrderDimCreateByEnum.订单.getKey().compareTo(vo.getDimCreateBy()) == 0) {
                    accountingUnifiedSupplierServiceOpStatistics.fixDimOrder(vo);
//                    accountingUnifiedSupplierServiceOpStatistics.fixDimGoods(vo);
                } else if (AccountingOrderDimCreateByEnum.商品.getKey().compareTo(vo.getDimCreateBy()) == 0) {
                    accountingUnifiedSupplierServiceOpStatistics.fixDimGoods(vo);
                }

                int retReset = opResetNeedReviseMark(vo.getId());

            }


        });

    }

    public void patchNeedReviseMarkServiceNoSourceFrom(List<AccountingOrderUnifiedSupplierListItemVo> resultList, LoginSysUser loginSysUser) {

        log.info("进入 patchNeedReviseMarkServiceNoSourceFrom");

        if (CollUtil.isEmpty(resultList)) {
            return;
        }

        for (AccountingOrderUnifiedSupplierListItemVo vo : resultList) {


            if (ObjectUtil.isNotNull(vo.getNeedReviseMark())
                    && vo.getNeedReviseMark().compareTo(CommonNeedReviseMarkEnum.修数据_20220519.getKey()) == 0) {


                log.info("{}", JSONUtil.toJsonStr(vo));

                Long   accountingOrderId = vo.getId();
                String accountingOrderSn = vo.getAccountingOrderSn();


                String serviceNo  = vo.getServiceNo();
                String sourceFrom = vo.getSourceFrom();

                // 目的
                // 1. 首先是传导

                /**************************************** 验证 start ****************************************/

                if (StrUtil.isBlank(sourceFrom)) {
                    continue;
                }

                /**************************************** 验证 start ****************************************/

                int retFix = invoiceApplySupplierService.pathFixFieldServiceNoSourceFrom(accountingOrderSn, serviceNo, sourceFrom, loginSysUser);

                int retReset = opResetNeedReviseMark(accountingOrderId);

            } else {
                log.info("{} {}", vo.getNeedReviseMark(), JSONUtil.toJsonStr(vo));
            }
        }
    }

    public int opResetNeedReviseMark(Long accountingOrderId) {

        int ret = 0;

        AccountingUnifiedSupplier forUpdate = new AccountingUnifiedSupplier();

        forUpdate.setId(accountingOrderId);
        forUpdate.setNeedReviseMark(CommonNeedReviseMarkEnum.正常.getKey());

        ret = accountingUnifiedSupplierMapper.updateByPrimaryKeySelective(forUpdate);

        return ret;
    }

    private void additionalInfoAccountingOrderUnifiedSupplierListItemVo(List<AccountingOrderUnifiedSupplierListItemVo> resultList) {

        if (CollUtil.isEmpty(resultList)) {
            return;
        }

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

        List<Long> sysUserIds = new ArrayList<>();

        List<Long> createUserIds = resultList.stream().filter(o -> o.getCreateUserId() != null).filter(AnLamdaUtils.distinctByKey(o -> o.getCreateUserId())).map(o -> o.getCreateUserId()).collect(Collectors.toList());
        List<Long> updateUserIds = resultList.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());


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


        // 修正显示 iterator 为 对账单
        for (AccountingOrderUnifiedSupplierListItemVo vo : resultList) {

            // 补 订单类型-订单来源-引用enum CommonServiceNoEnum
            if (ObjectUtil.isNotNull(vo.getServiceNo())) {
                vo.setServiceNoName(CommonServiceNoEnum.getByServiceNo(vo.getServiceNo()).getServiceName());
            } else {
                vo.setServiceNoName(CommonServiceNoEnum.UNKNOW.getServiceName());
            }
            // 补 操作来源-引用enum CommonSourceFromEnum
            if (ObjectUtil.isNotNull(vo.getSourceFrom())) {
                vo.setSourceFromName(CommonSourceFromEnum.getBySourceFromCode(vo.getSourceFrom()).getSourceFromName());
            } else {
                vo.setSourceFromName(CommonSourceFromEnum.UNKNOW.getSourceFromName());
            }

            vo.setAccountingStatusName(AccountingOrderSupplierAccountingStatusEnum.getDesc(vo.getAccountingStatus()));
            vo.setInvoiceStatusName(InvoiceApplySupplierInvoiceProgressingStatusEnum.getDesc(vo.getInvoiceStatus()));
            vo.setBackAccountStatusName(InvoiceApplySupplierPayOffAccountStatusEnum.getDesc(vo.getBackAccountStatus()));


            // 再补个

            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.getCreateUserId().equals(1L)) {
                vo.setUpdateUserName("系统");
            }
        }

        /****************************************** 补充信息   end ******************************************/
    }

    @Override
    public AccountingOrderUnifiedSuplierHeadVo getStatementOfAccountHeadSum(Map<String, Object> params) {

        AccountingOrderUnifiedSuplierHeadVo headVo = accountingUnifiedSupplierMapperEx.getStatementOfAccountHeadSum(params);

        DtoSugarUpUtils.sugarUpAccountingUnifiedSuplierHeadVo(headVo);

        return headVo;
    }

    @Override
    public AccountingOrderUnifiedSuplierHeadVo getStatementOfAccountHeadSum(AccountingOrderUnifiedSupplierQueryCriteria queryCriteria) {

        AccountingOrderUnifiedSuplierHeadVo headVo = accountingUnifiedSupplierMapperEx.getStatementOfAccountHeadSum(queryCriteria);

        DtoSugarUpUtils.sugarUpAccountingUnifiedSuplierHeadVo(headVo);

        return headVo;
    }

    public int updateFieldByPrimaryKeySelective(AccountingUnifiedSupplier statementOfAccount) {
        return accountingUnifiedSupplierMapper.updateByPrimaryKeySelective(statementOfAccount);
    }


    /**
     * 补丁程序
     * 侨城汇
     * 大概是可以与超级前台的逻辑共用,还是要查证一下
     */
    public void patchXDimOrder2DimGoods(String accountingOrderSn) {

        // TODO 先找出 全部 对账单(有效) X orders

        AccountingUnifiedSupplierExample          example00 = new AccountingUnifiedSupplierExample();
        AccountingUnifiedSupplierExample.Criteria criteria  = example00.createCriteria();

        criteria.andDimCreateByEqualTo(0)
                .andAccountingStatusNotEqualTo(AccountingOrderCustomerAccountingStatusEnum.已取消.getKey());

        if (StringUtils.isNotBlank(accountingOrderSn)) {
            criteria.andAccountingOrderSnEqualTo(accountingOrderSn);
        }

        List<AccountingUnifiedSupplier> accountingUnifiedSupplierList = accountingUnifiedSupplierMapper.selectByExample(example00);

        if (CollUtil.isNotEmpty(accountingUnifiedSupplierList)) {

            for (AccountingUnifiedSupplier item00 : accountingUnifiedSupplierList) {

                AccountingUnifiedSupplierOrderExample example1 = new AccountingUnifiedSupplierOrderExample();
                example1.clear();
                example1.createCriteria()
                        .andAccountingOrderSnEqualTo(item00.getAccountingOrderSn());
                List<AccountingUnifiedSupplierOrder> accountingUnifiedSupplierOrderList = accountingUnifiedSupplierOrderMapper.selectByExample(example1);

                for (AccountingUnifiedSupplierOrder item01 : accountingUnifiedSupplierOrderList) {

                    // TODO 坑位？ 这个 createCriteria 没作用？
                    UnifiedOrderGoodsExample example2 = new UnifiedOrderGoodsExample();
                    example2.clear();
                    example2.createCriteria()
                            .andOrderSnEqualTo(item01.getOrderSn());
                    List<UnifiedOrderGoods> unifiedOrderGoodsList = unifiedOrderGoodsMapper.selectByExample(example2);

                    // TODO 坑位？ 这个 createCriteria 没作用？
                    UnifiedOrderExample example3 = new UnifiedOrderExample();
                    example3.createCriteria()
                            .andOrderSnEqualTo(item01.getOrderSn());
                    List<UnifiedOrder> unifiedOrderList = unifiedOrderMapper.selectByExample(example3);

                    UnifiedOrder item03 = unifiedOrderList.get(0);

                    for (UnifiedOrderGoods item02 : unifiedOrderGoodsList) {

                        AccountingUnifiedSupplierXGoods xGoods = new AccountingUnifiedSupplierXGoods();

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

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

                        xGoods.setUnifiedOrderId(item03.getId());
                        xGoods.setOrderSn(item01.getOrderSn());

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

                        xGoods.setCreateUserId(1L);
                        xGoods.setCreateTime(DateUtil.date());
                        xGoods.setUpdateUserId(1L);
                        xGoods.setCreateTime(DateUtil.date());

                        accountingUnifiedSupplierXGoodsMapper.insert(xGoods);

                    }

                    // 基于 orderSn 来更新 供应商对账状态
                    UnifiedOrderGoods goods = new UnifiedOrderGoods();
                    goods.setAccountingStateSupplier(CommonAccountingStateEnum.已对账.getKey());
                    unifiedOrderGoodsMapper.updateByExampleSelective(goods, example2);
                }

            }
        }


        // 再按 orders 去更新 goods?


    }

    /**
     * 供应商 patchXCheckAndFix
     * <p>
     * 1. 首先 输入的 供应商对账单 SN ! 已确认 ！不存在
     * <p>
     * 2. 对账单 关联关系 去 AccountingUnifiedSupplierXGoods 找关系
     * 关联关系 不存在 问题对账单
     * 关联关系 Size
     * <p>
     * 3. 对账单 关联 商品 通过 存的 AccountingUnifiedSupplierXGoods 分别过滤出 订单 与 商品
     * <p>
     * 4. 过滤出 问题数据 已经生成对账单 但状态还是未对账
     * 关联商品 供应商对账状态-未对账 不存在 不需要修正
     * 关联商品 供应商对账状态-未对账 存在 Size
     * <p>
     * 5. 修正状态
     * 商品-供应商 对账状态-已对账
     *
     * @param accountingOrderSn
     */
    @Transactional
    public String patchXCheckAndFix(String accountingOrderSn) {


        StringBuffer report = new StringBuffer();

        report.append("对账单编号 : ").append(accountingOrderSn);

        /****************************************** 对账单 start ******************************************/


//		AccountingUnifiedSupplierExample          example00                         = new AccountingUnifiedSupplierExample();
//		AccountingUnifiedSupplierExample.Criteria accountingUnifiedSupplierCriteria = example00.createCriteria();
//
//		// 先屏蔽
////		accountingUnifiedSupplierCriteria
//////				.andDimCreateByEqualTo(0)
////				.andAccountingStatusEqualTo(AccountingOrderAccountingStatusEnum.已确认.getKey());
//
//		if (StringUtils.isNotBlank(accountingOrderSn)) {
//			accountingUnifiedSupplierCriteria.andAccountingOrderSnEqualTo(accountingOrderSn);
//		}

//		AccountingUnifiedSupplierExample          example00                         = new AccountingUnifiedSupplierExample();
//		example00.createCriteria().andAccountingOrderSnEqualTo(accountingOrderSn);
//
//		List<AccountingUnifiedSupplier> accountingUnifiedSupplierList = accountingUnifiedSupplierMapper.selectByExample(example00);


//		if (CollUtil.isEmpty(accountingUnifiedSupplierList)) {
//			// 就是说明 这个对账单 是不一个有作用的对账单
//
//			// 返回错误的信息
//
//			report.append("CollUtil.isEmpty(accountingUnifiedSupplierList:true:不存在:").append(JsonUtils.toJson(accountingUnifiedSupplierList));
//
//			log.info(report.toString());
//
//			return report.toString();
//		}
        /****************************************** 对账单   end ******************************************/


        /****************************************** 交叉逻辑 mark by linjinyu at 20210205 start ******************************************/
//		AccountingUnifiedSupplier accountingUnifiedSupplier = accountingUnifiedSupplierList.get(0);


        AccountingUnifiedSupplier accountingUnifiedSupplier = accountingUnifiedSupplierMapperEx.getByAnnountingOrderSn(accountingOrderSn);

        if (null == accountingUnifiedSupplier) {
            report.append("null:accountingUnifiedSupplier:不存在:").append(AnJsonUtils.toJson(accountingUnifiedSupplier));
            log.info(report.toString());

            return report.toString();
        }

        final CommonAccountingStateEnum beFilter;
        final CommonAccountingStateEnum beUpdate;
        switch (AccountingOrderCustomerAccountingStatusEnum.get(accountingUnifiedSupplier.getAccountingStatus())) {
            case 待提交:

                beFilter = CommonAccountingStateEnum.未对账;
                beUpdate = CommonAccountingStateEnum.已对账;
                break;
            case 未确认:
                beFilter = CommonAccountingStateEnum.未对账;
                beUpdate = CommonAccountingStateEnum.已对账;
                break;
            case 已确认:
                beFilter = CommonAccountingStateEnum.未对账;
                beUpdate = CommonAccountingStateEnum.已对账;
                break;
            case 已取消:
                beFilter = CommonAccountingStateEnum.已对账;
                beUpdate = CommonAccountingStateEnum.未对账;
                break;
            case 已拒绝:
                beFilter = CommonAccountingStateEnum.已对账;
                beUpdate = CommonAccountingStateEnum.未对账;
                break;
            default:
                throw new UnifiedOrderRuntimeException(500, "没命中?出问题");

        }


        /****************************************** 对账单 关联关系 start ******************************************/

        AccountingUnifiedSupplierXGoodsExample          exampleX                                       = new AccountingUnifiedSupplierXGoodsExample();
        AccountingUnifiedSupplierXGoodsExample.Criteria accountingUnifiedSupplierXGoodsExampleCriteria = exampleX.createCriteria();

        accountingUnifiedSupplierXGoodsExampleCriteria.andAccountingOrderSnEqualTo(accountingOrderSn);

        List<AccountingUnifiedSupplierXGoods> accountingUnifiedSupplierXGoodsList = accountingUnifiedSupplierXGoodsMapper.selectByExample(exampleX);

        if (CollUtil.isEmpty(accountingUnifiedSupplierXGoodsList)) {
            report.append(" : 关联关系 不存在 问题对账单");

            return report.toString();
        } else {
            report.append(" : 关联关系 Size : ").append(accountingUnifiedSupplierXGoodsList.size());
        }

        /****************************************** 对账单 关联关系   end ******************************************/


        /****************************************** 对账单 关联 商品 start ******************************************/
        List<String> processUnifiedOrderSns         = accountingUnifiedSupplierXGoodsList.stream().filter(o -> null != o.getOrderSn()).map(o -> o.getOrderSn()).collect(Collectors.toList());
        List<Long>   processUnifiedOrderGoodsIdFull = accountingUnifiedSupplierXGoodsList.stream().filter(o -> null != o.getUnifiedOrderGoodsId()).map(o -> o.getUnifiedOrderGoodsId()).collect(Collectors.toList());

        UnifiedOrderGoodsExample example = new UnifiedOrderGoodsExample();
        example.createCriteria()
                .andIdIn(processUnifiedOrderGoodsIdFull);
        List<UnifiedOrderGoods> unifiedOrderGoodsList = unifiedOrderGoodsMapper.selectByExample(example);

        if (CollUtil.isEmpty(unifiedOrderGoodsList)) {
            report.append(" : 关联商品 不存在 问题对账单");

            return report.toString();
        } else {
            report.append(" : 关联商品 Size : ").append(unifiedOrderGoodsList.size());
        }

        /****************************************** 对账单 关联 商品 start ******************************************/


        /****************************************** 过滤出 问题数据 已经生成对账单 但状态还是未对账 start ******************************************/
        List<Predicate<UnifiedOrderGoods>> predicatesByAccountingStateSupplierEq2 = new ArrayList<>();
        predicatesByAccountingStateSupplierEq2.add(r -> r.getAccountingStateSupplier() != null && r.getAccountingStateSupplier().equals(beFilter.getKey()));
        List<UnifiedOrderGoods> processUnifiedOrderGoodsByAccountingStateSupplierEq2 = AnLamdaUtils.filters(unifiedOrderGoodsList, predicatesByAccountingStateSupplierEq2);

        List<Long> processUnifiedOrderGoodsIdsByAccountingStateSupplierEq2 = processUnifiedOrderGoodsByAccountingStateSupplierEq2.stream().filter(o -> null != o.getId()).map(o -> o.getId()).collect(Collectors.toList());

        if (CollUtil.isEmpty(processUnifiedOrderGoodsIdsByAccountingStateSupplierEq2)) {
            report.append(" : 关联商品 供应商对账状态-未对账 不存在 不需要修正");

            return report.toString();
        } else {
            report.append(" : 关联商品 供应商对账状态-未对账 存在 Size : ").append(processUnifiedOrderGoodsIdsByAccountingStateSupplierEq2.size());
        }

        /****************************************** 过滤出 问题数据 已经生成对账单 但状态还是未对账   end ******************************************/


        /****************************************** 修正状态 start ******************************************/
        // 供应商对账状态
        unifiedOrderGoodsService.updateAccountingStateSupplierByOrderSnAndSysUnifiedOrderGoodsIds(processUnifiedOrderSns, processUnifiedOrderGoodsIdsByAccountingStateSupplierEq2, beUpdate);
        /****************************************** 修正状态   end ******************************************/


        return report.toString();


    }


}
