package cn.superdesk.uniorder.dubbo.provider.order.base;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.superdesk.uniorder.common.enums.UnifiedCode;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderDimCreateByEnum;
import cn.superdesk.uniorder.common.enums.common.CommonAccountingLockingEnum;
import cn.superdesk.uniorder.common.enums.common.CommonAccountingStateEnum;
import cn.superdesk.uniorder.common.enums.common.CommonDirectionEnum;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCompletStateEnum;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import cn.superdesk.uniorder.common.numerical.AnConvertBeanUtil;
import cn.superdesk.uniorder.common.numerical.AnDateUtils;
import cn.superdesk.uniorder.common.numerical.AnLongUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.security.JwtUtil;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.dao.entity.accounting.unified.customer.AccountingUnifiedCustomer;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderGoods;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterprise;
import cn.superdesk.uniorder.dao.entity.organisation.SysOrganization;
import cn.superdesk.uniorder.dao.entity.sys.notify.SysNotify;
import cn.superdesk.uniorder.dto.param._function.select.SelectOptionDepartmentCriteria;
import cn.superdesk.uniorder.dto.param.accounting.score.customer.*;
import cn.superdesk.uniorder.dto.param.accounting.unified.customer.ExportCustomerStatementOfAccountDetailCriteria;
import cn.superdesk.uniorder.dto.param.accounting.unified.supplier.AccountingSupplierNotYetDimGoodsQueryCriteria;
import cn.superdesk.uniorder.dto.param.accounting.unified.supplier.SuplierStatementOfAccountDetailQueryCriteria;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskappservices.UnifiedLnssOrderAdd;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskappservices.UnifiedLnssOrderGoodsAdd;
import cn.superdesk.uniorder.dto.vo._function.select.SelectOptionDepartment;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.notyet.CustomerUnAccountingDimGoodsVo;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.notyet.UnifiedOrderCustomerHeadSumVo;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.notyet.UnifiedOrderCustomerNotCheckVo;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.statement.CustomerStatementOfAccountDetailVo;
import cn.superdesk.uniorder.dto.vo.accounting.unified.supplier.notyet.UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo;
import cn.superdesk.uniorder.dto.vo.accounting.unified.supplier.notyet.UnifiedOrderSupplierHeadSumVo;
import cn.superdesk.uniorder.dto.vo.invoice.customer.InvoiceApplyDetailDimCreditItemVo;
import cn.superdesk.uniorder.dto.vo.order.Org2VirtStatisticsVo;
import cn.superdesk.uniorder.dto.vo.score.ScoreOrderReconciliationNotYetHeadVo;
import cn.superdesk.uniorder.dto.vo.unified.*;
import cn.superdesk.uniorder.dto.vo.wechat.WxBillOrder;
import cn.superdesk.uniorder.dto.vo.wechat.WxBillVirt;
import cn.superdesk.uniorder.dto.vo.wechat.WxBillVirtItem;
import cn.superdesk.uniorder.dubbo.facade.operation.DubboUnifiedOrderIssuesService;
import cn.superdesk.uniorder.dubbo.facade.order.base.DubboUnifiedOrderService;
import cn.superdesk.uniorder.dubbo.facade.sys.notify.DubboSysNotifyService;
import cn.superdesk.uniorder.event.CommonEventPublisher;
import cn.superdesk.uniorder.service.accounting.unified.customer.AccountingUnifiedCustomerService;
import cn.superdesk.uniorder.service.accounting.unified.customer.AccountingUnifiedCustomerServiceCommon;
import cn.superdesk.uniorder.service.accounting.unified.supplier.AccountingUnifiedSupplierXGoodsService;
import cn.superdesk.uniorder.service.marketing.UnifiedStatisticsVirtCommonService;
import cn.superdesk.uniorder.service.order.base.ScoreOrderService;
import cn.superdesk.uniorder.service.order.base.UnifiedOrderExportExcelService;
import cn.superdesk.uniorder.service.order.base.UnifiedOrderGoodsService;
import cn.superdesk.uniorder.service.order.base.UnifiedOrderService;
import cn.superdesk.uniorder.service.organisation.SysEnterpriseService;
import cn.superdesk.uniorder.service.organisation.SysOrganizationService;
import cn.superdesk.uniorder.service.setting.UnifiedSnConfigService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @Description: 订单管理
 * @Author: linjinyu
 * @CreateDate: 2021/3/5 下午2:45
 * @UpdateUser: linjinyu
 * @UpdateDate: 2021/3/5 下午2:45
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service(version = "1.0.0", retries = -1, timeout = 180000)
public class DubboUnifiedOrderServiceImpl implements DubboUnifiedOrderService {

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

    @Autowired
    private ScoreOrderService scoreOrderService;


    @Autowired
    private AccountingUnifiedCustomerService       accountingUnifiedCustomerService;
    @Autowired
    private AccountingUnifiedCustomerServiceCommon accountingUnifiedCustomerServiceCommon;
    @Autowired
    private AccountingUnifiedSupplierXGoodsService accountingUnifiedSupplierXGoodsService;


    @Autowired
    private UnifiedSnConfigService             unifiedSnConfigService;
    @Autowired
    private UnifiedStatisticsVirtCommonService unifiedStatisticsVirtService;

    @Autowired
    private CommonEventPublisher commonEventPublisher;

    @Autowired
    private SysOrganizationService sysOrganizationService;
    @Autowired
    private SysEnterpriseService   sysEnterpriseService;

    /****************************************** export excel start ******************************************/
    @Autowired
    private UnifiedOrderExportExcelService unifiedOrderExportExcelService;

    /****************************************** 引用自身 Dubbo provider start ******************************************/
    @Reference(version = "1.0.0", timeout = 10000, retries = -1)
    private DubboSysNotifyService          dubboSysNotifyService;
    @Reference(version = "1.0.0", timeout = 10000, retries = -1)
    private DubboUnifiedOrderIssuesService dubboUnifiedOrderIssuesService;


    @Override
    public List<SelectOptionDepartment> getSelectPurchaseDepartment(SelectOptionDepartmentCriteria criteria, LoginSysUser loginSysUser) {

        return unifiedOrderService.getSelectPurchaseDepartment(criteria, loginSysUser);
    }

    /**
     * 楼闪送 添加订单会被调用
     *
     * @param unifiedLnssOrderAdd
     * @returnl
     */
    @Override
    public Map<String, Object> addObjTran(UnifiedLnssOrderAdd unifiedLnssOrderAdd) {

        Map<String, Object> response           = new HashMap<>();
        UnifiedOrder        unifiedOrderEntity = new UnifiedOrder();


        /****************************************** 青章银 订单 问题改的逻辑 mark by linjinyu at 20201209 start ******************************************/

        String orderSn = null;

        if (null != unifiedLnssOrderAdd.getOrderSn()) {
            orderSn = unifiedLnssOrderAdd.getOrderSn();

            UnifiedOrder checkIsExist = unifiedOrderService.findByOrderSn(orderSn);

            if (null != checkIsExist) {
                response.put("code", 50000);
                response.put("msg", "订单已存在");
                return response;
            }

        } else {
            orderSn = unifiedSnConfigService.getSnQuoteDatabase(unifiedLnssOrderAdd.getServiceNo());
        }

        /****************************************** 青章银 订单 问题改的逻辑 mark by linjinyu at 20201209   end ******************************************/


        if (StringUtils.isEmpty(orderSn)) {
            response.put("code", UnifiedCode.SERVICENO_ERROR.getCode());
            response.put("msg", UnifiedCode.SERVICENO_ERROR.getMsg());
            return response;
        }

        if (AnCollectionUtils.isEmpty(unifiedLnssOrderAdd.getGoods())) {
            response.put("code", UnifiedCode.GOODS_EMPTY.getCode());
            response.put("msg", UnifiedCode.GOODS_EMPTY.getMsg());
            return response;
        }

        try {
            unifiedOrderEntity.setOrderSn(orderSn);
            // TODO 写死 这个是什么业务逻辑呀 初始为 2 的 invoiceStatus 没有根源
            unifiedOrderEntity.setInvoiceStatus(2);
            unifiedOrderEntity.setOrderLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
            unifiedOrderEntity.setOrderLockingSupplier(CommonAccountingLockingEnum.正常.getKey());
            unifiedOrderEntity.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
            unifiedOrderEntity.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());

            // 楼闪送-评价状态
            if (StringUtils.isNotEmpty(unifiedLnssOrderAdd.getAppraiseState())) {
                unifiedOrderEntity.setAppraiseState(Integer.valueOf(unifiedLnssOrderAdd.getAppraiseState()));
            } else {
                // TODO 写死
                unifiedOrderEntity.setAppraiseState(2);
            }

            unifiedOrderEntity.setCompletState(UnifiedOrderCompletStateEnum.未完成.getKey());


            // 销售金额
            unifiedOrderEntity.setAmount(unifiedLnssOrderAdd.getAmount());
            // 成本金额
            unifiedOrderEntity.setCostAmount(unifiedLnssOrderAdd.getCostAmount());

            unifiedOrderEntity.setCreateTime(DateUtil.date());

            // TODO 未确认 linjinyu 订单状态 start
            unifiedOrderEntity.setOrderState(Integer.valueOf(unifiedLnssOrderAdd.getOrderState()));
            unifiedOrderEntity.setOrderStateName(unifiedLnssOrderAdd.getOrderStateName());
            // TODO 未确认 linjinyu 订单状态 end


            /**
             *
             * jsonParam.put("service_no", "LNSS");
             */
            unifiedOrderEntity.setServiceNo(unifiedLnssOrderAdd.getServiceNo());
            // TODO 楼内送 的 order_type 直接过来? 20200601 对,就是直接过来的 还是个中文 闪送订单
            unifiedOrderEntity.setServiceName(unifiedLnssOrderAdd.getServiceName());


            unifiedOrderEntity.setOtherParams(unifiedLnssOrderAdd.getOtherParams());
            unifiedOrderEntity.setOrderSnOutTrade(unifiedLnssOrderAdd.getOutSn());

            unifiedOrderEntity.setPayType(Integer.valueOf(unifiedLnssOrderAdd.getPayType()));

            if (StringUtils.isNotEmpty(unifiedLnssOrderAdd.getPayState())) {
                unifiedOrderEntity.setPayState(Integer.valueOf(unifiedLnssOrderAdd.getPayState()));
            } else {
                unifiedOrderEntity.setPayState(2);
            }

            unifiedOrderEntity.setProjectId(Long.parseLong(unifiedLnssOrderAdd.getProjectId()));
            SysOrganization org = sysOrganizationService.getByOutOrgId(unifiedOrderEntity.getProjectId());
            if (org != null) {
                unifiedOrderEntity.setProjectName(org.getOrganizationName());
            } else {
                response.put("code", UnifiedCode.PROJECT_ERROR.getCode());
                response.put("msg", UnifiedCode.PROJECT_ERROR.getMsg());
                return response;
            }

            // 企业判断
            if (StringUtils.isNotEmpty(unifiedLnssOrderAdd.getPurchaseVirt())) {
                String[] purchaseVirt = unifiedLnssOrderAdd.getPurchaseVirt().split("_");
                unifiedOrderEntity.setPurchaseVirtId(Long.parseLong(purchaseVirt[1]));
                unifiedOrderEntity.setPurchaseVirtName(purchaseVirt[0]);
            }

            /**
             * 下单人信息
             * jsonParam.put("purchase_user", String.format("%s_%d", headerParam.getUserName(), headerParam.getUserId()));
             */
            String[] purchaseUser = unifiedLnssOrderAdd.getPurchaseUser().split("_");
            int      length       = purchaseUser.length;
            unifiedOrderEntity.setPurchaseUserId(AnLongUtils.getLong(purchaseUser[length - 1]));
            unifiedOrderEntity.setPurchaseUserName(purchaseUser[0]);


            /****************************************** add by linjinyu 20200903 ******************************************/

            /**
             * 下单人信息
             */
            unifiedOrderEntity.setPurchaseVirtId(unifiedLnssOrderAdd.getPurchaseVirtId());
            unifiedOrderEntity.setPurchaseVirtName(unifiedLnssOrderAdd.getPurchaseVirtName());
            unifiedOrderEntity.setPurchaseUserId(unifiedLnssOrderAdd.getPurchaseUserId());
            unifiedOrderEntity.setPurchaseUserName(unifiedLnssOrderAdd.getPurchaseUserName());
            unifiedOrderEntity.setPurchasePhone(unifiedLnssOrderAdd.getPurchasePhone());

            /**
             * 收货人信息
             */
            unifiedOrderEntity.setRecUserId(unifiedLnssOrderAdd.getRecUserId());
            unifiedOrderEntity.setRecUserName(unifiedLnssOrderAdd.getRecUserName());
            unifiedOrderEntity.setRecAddress(unifiedLnssOrderAdd.getRecAddress());
            unifiedOrderEntity.setRecUserPhone(unifiedLnssOrderAdd.getRecUserPhone());

            /****************************************** add by linjinyu 20200903 ******************************************/


            /**
             * 卖方 销售方 信息
             * jsonParam.put("sale", String.format("%s_%d", saleParam.getSaleName(), saleParam.getSaleId()));
             */
            String[] sale = unifiedLnssOrderAdd.getSale().split("_");
            unifiedOrderEntity.setSaleId(Long.parseLong(sale[1]));
            unifiedOrderEntity.setSaleName(sale[0]);


            /**
             * jsonParam.put("settlement_type", "");
             */
            if (StringUtils.isNotEmpty(unifiedLnssOrderAdd.getSettlementType())) {
                unifiedOrderEntity.setSettlementType(Integer.valueOf(unifiedLnssOrderAdd.getSettlementType()));
            } else {
                // TODO 写死
                unifiedOrderEntity.setSettlementType(2);
            }

            unifiedOrderEntity.setSourceChannel(Integer.valueOf(unifiedLnssOrderAdd.getSourceChannel()));
            unifiedOrderEntity.setTransportAmount(unifiedLnssOrderAdd.getTransportAmount());

            unifiedOrderEntity.setUpdateTime(DateUtil.date());
            unifiedOrderEntity.setUserName(unifiedLnssOrderAdd.getUserName());
            unifiedOrderEntity.setUserType(unifiedLnssOrderAdd.getUserType());

            List<UnifiedOrderGoods> unifiedOrderGoodsList = new ArrayList<>();

            for (UnifiedLnssOrderGoodsAdd item : unifiedLnssOrderAdd.getGoods()) {

                UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();

                unifiedOrderGoods.setOrderSn(unifiedOrderEntity.getOrderSn());

                unifiedOrderGoods.setDirection(CommonDirectionEnum.正向.getKey());// 1 为正向 -1 为负向

                unifiedOrderGoods.setGoodsLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
                unifiedOrderGoods.setGoodsLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

                unifiedOrderGoods.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
                unifiedOrderGoods.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());

                /**
                 * jsonGood.put("goods_name", String.format("%s_%d", productEntity.getProductName(), productEntity.getId()));
                 */
                String[] goods = item.getGoods_name().split("_");
                unifiedOrderGoods.setGoodsId(Long.parseLong(goods[1]));
                unifiedOrderGoods.setGoodsName(goods[0]);

                unifiedOrderGoods.setGoodsParams(item.getGoods_params());

                unifiedOrderGoods.setPrice(new BigDecimal(item.getPrice()));
                unifiedOrderGoods.setCostPrice(new BigDecimal(item.getCost_price()));

                unifiedOrderGoods.setQuantity(Integer.parseInt(item.getQuantity()));

                unifiedOrderGoods.setCreateTime(DateUtil.date());
                unifiedOrderGoods.setUpdateTime(DateUtil.date());

                unifiedOrderGoodsList.add(unifiedOrderGoods);
            }

            UnifiedOrder resUnifiedOrder = unifiedOrderService.addObjTran(unifiedOrderEntity, unifiedOrderGoodsList);

            if (resUnifiedOrder.getId() > 0) {
                response.put("code", 1);
                response.put("sn", resUnifiedOrder.getOrderSn());
                return response;
            } else {
                response.put("code", UnifiedCode.OTHER_ERROR.getCode());
                response.put("msg", UnifiedCode.OTHER_ERROR.getMsg());
                return response;
            }

        } catch (Exception e) {

            e.printStackTrace();

            response.put("code", UnifiedCode.OTHER_ERROR.getCode());
            response.put("msg", "请检查参数");

            return response;
        }
    }

    @Override
    public void updateObj(UnifiedOrder unifiedOrder) {
        unifiedOrderService.updateByPrimaryKeySelective(unifiedOrder);
    }


    /****************************************** 客户结算 对账单 详情 start ******************************************/

//	accountingUnifiedCustomerDubboConsumerService.getCustomerStatementOfAccountDetailDimOrder2Goods(id);
//	accountingUnifiedCustomerDubboConsumerService.getCustomerStatementOfAccountDetailDimGoods2Goods(id);
    public String exportCustomerStatementOfAccountDetailCompatible(ExportCustomerStatementOfAccountDetailCriteria criteria, LoginSysUser loginSysUser) {

        log.info("\n异步操作 包裹 外层 exportCustomerStatementOfAccountDetailCompatible params: \n{}", AnJsonUtils.toJson(criteria));

        CompletableFuture.runAsync(() -> {
            try {

                // 三步走
                // 1. 数据
                AccountingUnifiedCustomer accountingUnifiedCustomer = accountingUnifiedCustomerService.findById(criteria.getAccountingOrderId());

                CustomerStatementOfAccountDetailVo exportData = null;

                if (null != accountingUnifiedCustomer) {
                    switch (AccountingOrderDimCreateByEnum.get(accountingUnifiedCustomer.getDimCreateBy())) {
                        case 订单:
                            exportData = accountingUnifiedCustomerServiceCommon.getCustomerStatementOfAccountDetailDimOrder2Goods(criteria.getAccountingOrderId());
                            break;
                        case 商品:
                            exportData = accountingUnifiedCustomerServiceCommon.getCustomerStatementOfAccountDetailDimGoods2Goods(criteria.getAccountingOrderId());
                            break;
                        case 流水:
                            log.info("case 流水 exportData 未支持");
                            break;
                        default:
                            log.info("default exportData 未支持");
                            break;
                    }
                }

                if (null != exportData.getBankInfo()) {
                    exportData.setBankInfoCompanyName(exportData.getBankInfo().getCompanyName());
                    exportData.setBankInfoBankAccount(exportData.getBankInfo().getBankAccount());
                    exportData.setBankInfoBankName(exportData.getBankInfo().getBankName());
                    exportData.setBankInfoSupplyName(exportData.getBankInfo().getSupplyName());
                    exportData.setBankInfoTel(exportData.getBankInfo().getTel());
                    exportData.setBankInfoAddress(exportData.getBankInfo().getAddress());
                }

                exportData.setAccountingAmountStr(new DecimalFormat("###,###.00").format(exportData.getAccountingAmount()));

                // yyyy-MM-dd HH:mm:ss
                exportData.setStartTimeStr(AnDateUtils.format(exportData.getStartTime(), "yyyy年MM月dd日"));
                exportData.setEndTimeStr(AnDateUtils.format(exportData.getEndTime(), "yyyy年MM月dd日"));
                exportData.setCreateTimeStr(AnDateUtils.format(exportData.getCreateTime(), "yyyy年MM月dd日 HH:mm:ss"));


                // 2. 生成excel
                SysNotify sysNotify = unifiedOrderExportExcelService.exportCustomerStatementOfAccountDetailCompatible(accountingUnifiedCustomer.getAccountingOrderSn(), exportData);

                // 3. 通知
                dubboSysNotifyService.notifyExportCustomerStatementOfAccountDetailCompatible(sysNotify, loginSysUser);

            } catch (Exception e2) {
                log.error("\n异步操作 包裹 内层 exportCustomerStatementOfAccountDetailCompatible{} -> 执行 异常:{}", AnJsonUtils.toJson(criteria), e2);
            }
        });

        return "导出任务已经接收,正在处理中...";
    }

    /****************************************** 客户结算 对账单 详情   end ******************************************/

    /****************************************** 供应商结算 对账单 详情 start ******************************************/

    /**
     * 已添加 数据脱敏逻辑 20211203
     *
     * @param queryCriteria
     * @param loginSysUser
     * @return
     */
    @Override
    public List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo> getSupplierStatementOfAccountDetailDimOrder2Goods(SuplierStatementOfAccountDetailQueryCriteria queryCriteria, LoginSysUser loginSysUser) {

        return unifiedOrderService.getSupplierStatementOfAccountDetailDimOrder2Goods(queryCriteria, loginSysUser);
    }

    /**
     * 已添加 数据脱敏逻辑 20211203
     * input accountingOrderSn (供应商结算对账 对账单编号)
     *
     * @param queryCriteria
     * @param loginSysUser
     * @return
     */
    @Override
    public List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo> getSupplierStatementOfAccountDetailDimGoods2Goods(
            /* 实际上只有 String accountingOrderSn */SuplierStatementOfAccountDetailQueryCriteria queryCriteria,
                                                LoginSysUser loginSysUser) {

        // 已添加 数据脱敏逻辑 20211203
        List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo> resultList = unifiedOrderService.getSupplierStatementOfAccountDetailDimGoods2Goods(queryCriteria.getAccountingOrderSn(), loginSysUser);

        return resultList;
    }

    /**
     * 已添加 数据脱敏逻辑 20211203
     *
     * @param queryCriteria
     * @param loginSysUser
     * @return
     */
    @Override
    public String exportSupplierStatementOfAccountDetailCompatible(SuplierStatementOfAccountDetailQueryCriteria queryCriteria, LoginSysUser loginSysUser) {

        log.info("\n异步操作 包裹 外层 exportSupplierStatementOfAccountDetailCompatible params: \n{}", AnJsonUtils.toJson(queryCriteria));


        CompletableFuture.runAsync(() -> {

            try {

                // 三步走
                // 1. 数据
                // 2. 生成excel
                // 3. 通知

                // 已添加 数据脱敏逻辑 20211203
                List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo> exportData = getSupplierStatementOfAccountDetailDimGoods2Goods(queryCriteria, loginSysUser);

                // 随便写个 【【结算中心-测试环境】 供应商结算 > 对账单 > 对账单详情-订单未按照下单时间升序排列】https://www.tapd.cn/33003868/bugtrace/bugs/view?bug_id=1133003868001004808
                List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo> exportDataSortByOrderCreateTimeOrderSn = exportData.stream()
                        .sorted(
                                Comparator
                                        .comparing(UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo::getCreateTime)
                                        .thenComparing(UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo::getOrderSn)
                        )
                        .collect(Collectors.toList());

                SysNotify sysNotify = unifiedOrderExportExcelService.exportSupplierStatementOfAccountDetailCompatible(queryCriteria.getAccountingOrderSn(), exportDataSortByOrderCreateTimeOrderSn);

                // 通知
                dubboSysNotifyService.notifyExportSupplierStatementOfAccountDetailCompatible(sysNotify, loginSysUser);

            } catch (Exception e2) {
                log.error("\n异步操作 包裹 内层 exportSupplierStatementOfAccountDetailCompatible{} -> 执行 异常:{}", AnJsonUtils.toJson(queryCriteria), e2);
            }
        });

        return "导出任务已经接收,正在处理中...";
    }

    /****************************************** 供应商结算 对账单 详情   end ******************************************/


    @Override
    public UnifiedOrder findByOrderSn(String orderSn) {

        return unifiedOrderService.findByOrderSn(orderSn);
    }


    /****************************************** 订单管理 start ******************************************/
    @Override
    public UnifiedOrderCommonHeadSum getOrderManagerGoodsPageHead(Map<String, Object> params) {

        return unifiedOrderService.getOrderManagerGoodsPageHead(params);
    }

    @Override
    public List<UnifiedOrderGoodsVo> getOrderManagerGoodsView(Map<String, Object> params) {

        return unifiedOrderService.getOrderManagerGoodsView(params);
    }

    /****************************************** 订单管理-列表数据导出 export excel start ******************************************/

    @Override
    public String exportExcelOrderManagerGoodsData(Map<String, Object> params, LoginSysUser loginSysUser) {

        // 异步操作 包裹 mark by linjinyu at 20210305
        log.info("\n异步操作 包裹 外层 exportExcelOrderManagerGoodsData params: \n{}", AnJsonUtils.toJson(params));

        CompletableFuture.runAsync(() -> {

            try {

                // 三步走 mark by linjinyu at 20210305
                // 1. 数据
                // 2. 生成excel
                // 3. 通知
                // TODO 排序 订单 create_time 升
                params.put("orderBy", "uo.create_time asc , uo.order_sn asc, uog.id asc");
                List<UnifiedOrderGoodsVo> exportData = getOrderManagerGoodsView(params);

                SysNotify sysNotify = unifiedOrderExportExcelService.exportExcelOrderManagerGoodsData(exportData);

                // 通知
                dubboSysNotifyService.notifyExportExcelOrderManagerGoodsData(sysNotify, loginSysUser);


            } catch (Exception e2) {
                log.error("\n异步操作 包裹 内层 exportExcelOrderManagerGoodsData{} -> 执行 异常:{}", AnJsonUtils.toJson(params), e2);
            }
        });

        return "导出任务已经接收,正在处理中...";
    }

    @Override
    public String exportExcelOrderManagerGoodsCostPrice(Map<String, Object> params, LoginSysUser loginSysUser) {

        // 异步操作 包裹 mark by linjinyu at 20210305
        log.info("\n异步操作 包裹 外层 exportExcelOrderManagerGoodsCostPrice params: \n{}", AnJsonUtils.toJson(params));

        CompletableFuture.runAsync(() -> {

            try {

                // 三步走 mark by linjinyu at 20210305
                // 1. 数据
                // 2. 生成excel
                // 3. 通知
                // TODO 排序 订单 create_time 升
                params.put("orderBy", "uo.create_time asc , uo.order_sn asc, uog.id asc");
                List<UnifiedOrderGoodsVo> exportData = getOrderManagerGoodsView(params);

                SysNotify sysNotify = unifiedOrderExportExcelService.exportExcelOrderManagerGoodsCostPrice(exportData);

                // 通知
                dubboSysNotifyService.notifyExportExcelOrderManagerGoodsCostPrice(sysNotify, loginSysUser);


            } catch (Exception e2) {
                log.error("\n异步操作 包裹 内层 exportExcelOrderManagerGoodsCostPrice{} -> 执行 异常:{}", AnJsonUtils.toJson(params), e2);
            }
        });

        return "导出任务已经接收,正在处理中...";

    }

    /****************************************** 订单管理-列表数据导出 export excel   end ******************************************/

    @Override
    public R<List<Org2VirtStatisticsVo>> getOrg2VirtStatistics(Map<String, Object> params, int pageNum, int pageSize) {

        R<List<Org2VirtStatisticsVo>> response = unifiedOrderService.getOrg2VirtStatistics(params, pageNum, pageSize);

        if (AnCollectionUtils.isNotEmpty(response.getData())) {
            response.getData().forEach(item -> {
                if (null == item.getVirtId() && null == item.getVirtName()) {
                    item.setVirtName("无企业,游客?");
                } else if (null != item.getVirtId() && null == item.getVirtName()) {
                    item.setVirtName(StrUtil.format("企业[{}]数据异常", item.getVirtId()));
                }
            });
        }

        return response;
    }


    /**
     * 一般订单 得未结算数据 商品维度
     *
     * @param params
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public R<List<UnifiedOrderGoodsVo>> getOrderManagerGoodsByPage(Map<String, Object> params, int pageNum, int pageSize) {

        return unifiedOrderService.getOrderManagerGoodsByPage(params, pageNum, pageSize);
    }
    /****************************************** 订单管理   end ******************************************/


    /****************************************** 客户结算 dim order 未对账 订单 start ******************************************/
    @Override
    public UnifiedOrderCommonHeadSum getCustomerUnAccountingDimOrderHeadSum(Map<String, Object> params) {

        return unifiedOrderService.getCustomerUnAccountingDimOrderHeadSum(params);
    }

    @Override
    public R<List<UnifiedOrderCustomerNotCheckVo>> getCustomerUnAccountingDimOrderList(Map<String, Object> params, int pageNum, int pageSize) {

        return unifiedOrderService.getCustomerUnAccountingDimOrderList(params, pageNum, pageSize);
    }

    @Override
    public String exportExcelAccountingCustomerNotYetDimOrder(Map<String, Object> params, LoginSysUser loginSysUser) {

        log.info("\n异步操作 包裹 外层 exportExcelAccountingCustomerNotYetDimOrder params: \n{}", AnJsonUtils.toJson(params));

        CompletableFuture.runAsync(() -> {

            try {

                // 三步走
                // 1. 数据
                // 2. 生成excel
                // 3. 通知
                List<UnifiedOrderJoinGoodsDetailVo> exportData = unifiedOrderGoodsService.getUnifiedOrderJoinGoodsDetailVoList(params);

                SysNotify sysNotify = unifiedOrderExportExcelService.exportExcelAccountingCustomerNotYetDimOrder(exportData);

                // 通知
                dubboSysNotifyService.notifyExportExcelAccountingCustomerNotYetDimOrder(sysNotify, loginSysUser);

            } catch (Exception e2) {
                log.error("\n异步操作 包裹 内层 exportExcelAccountingCustomerNotYetDimOrder {} -> 执行 异常:{}", AnJsonUtils.toJson(params), e2);
            }
        });

        return "导出任务已经接收,正在处理中...";
    }

    /****************************************** 客户结算 dim order 未对账 订单   end ******************************************/

    /****************************************** 客户结算 dim goods 未对账 商品 start ******************************************/
    @Override
    public UnifiedOrderCustomerHeadSumVo getCustomerUnAccountingDimGoodsHeadSum(Map<String, Object> params, String token) {

        LoginSysUser loginSysUser = JwtUtil.getLoginSysUser(token);
        return unifiedOrderService.getCustomerUnAccountingDimGoodsHeadSum(params, loginSysUser);
    }

    @Override
    public List<CustomerUnAccountingDimGoodsVo> getCustomerUnAccountingDimGoodsList(Map<String, Object> params, String token) {

        LoginSysUser loginSysUser = JwtUtil.getLoginSysUser(token);

        // TODO 排序 订单 create_time 倒 默认
//		params.put("orderBy", "uo.create_time desc , uo.order_sn desc, uog.id asc");
        return unifiedOrderService.getCustomerUnAccountingDimGoodsList(params, loginSysUser);
    }

    /**
     * 新版导出
     *
     * @param params
     * @param loginSysUser
     * @return
     */
    @Override
    public String exportExcelAccountingCustomerNotYetDimGoods(Map<String, Object> params, LoginSysUser loginSysUser) {

        log.info("\n异步操作 包裹 外层 exportExcelAccountingCustomerNotYetDimGoods params: \n{}", AnJsonUtils.toJson(params));

        CompletableFuture.runAsync(() -> {

            try {

                // 三步走
                // 1. 数据
                // 2. 生成excel
                // 3. 通知
                // TODO 排序 订单 create_time 升
                params.put("orderBy", "uo.create_time asc , uo.order_sn asc, uog.id asc");
                List<CustomerUnAccountingDimGoodsVo> exportData = unifiedOrderService.getCustomerUnAccountingDimGoodsList(params, loginSysUser);

                SysNotify sysNotify = unifiedOrderExportExcelService.exportExcelAccountingCustomerNotYetDimGoods(exportData);

                // 通知
                dubboSysNotifyService.notifyExportExcelAccountingCustomerNotYetDimGoods(sysNotify, loginSysUser);

            } catch (Exception e2) {
                log.error("\n异步操作 包裹 内层 exportExcelAccountingCustomerNotYetDimGoods {} -> 执行 异常:{}", AnJsonUtils.toJson(params), e2);
            }
        });

        return "导出任务已经接收,正在处理中...";
    }

    @Override
    public R<List<CustomerUnAccountingDimGoodsVo>> getCustomerUnAccountingDimGoodsList(
            Map<String, Object> params,
            int pageNo,
            int pageSize,
            String token) {
        LoginSysUser loginSysUser = JwtUtil.getLoginSysUser(token);
        return unifiedOrderService.getCustomerUnAccountingDimGoodsList(params, pageNo, pageSize, loginSysUser);
    }

    /****************************************** 客户结算 dim goods 未对账 商品   end ******************************************/


    /****************************************** 积分结算 dim credit 未对账 流水 start ******************************************/

    public ScoreOrderReconciliationNotYetHeadVo getScoreOrderReconciliationNotYetHeadSum(AccountingOrderScoreCustomerNotYetDimCreditQueryCriteria queryCriteria, LoginSysUser loginSysUser) {

        return scoreOrderService.getScoreOrderReconciliationNotYetHeadSum(queryCriteria, loginSysUser);
    }

    /**
     * 积分订单 得未结算数据 积分流水维度
     *
     * @param queryCriteria
     * @param loginSysUser
     * @return
     */
    public R<List<InvoiceApplyDetailDimCreditItemVo>> getScoreOrderReconciliationNotYetByPageQuery(AccountingOrderScoreCustomerNotYetDimCreditQueryCriteria queryCriteria, LoginSysUser loginSysUser) {


        return scoreOrderService.getScoreOrderReconciliationNotYetByPageQuery(queryCriteria, loginSysUser);
    }


    /**
     * 重点关注 积分结算2.1 后封闭 按场景开放
     *
     * @param queryCriteria
     * @param loginSysUser
     * @return
     */
//	public List<InvoiceApplyDetailDimCreditItemVo> getScoreOrderReconciliationNotYet(AccountingScoreCustomerNotYetDimCreditQueryCriteria queryCriteria, LoginSysUser loginSysUser) {
//		return scoreOrderService.getScoreOrderReconciliationNotYet(queryCriteria, loginSysUser);
//	}
    @Override
    public List<InvoiceApplyDetailDimCreditItemVo> getScoreOrderReconciliationNotYetScene1(
            AccountingOrderScoreCustomerNotYetDimCreditScene1QueryCriteria queryCriteria,
            LoginSysUser loginSysUser) {
        return scoreOrderService.getScoreOrderReconciliationNotYetScene1(queryCriteria, loginSysUser);
    }

    @Override
    public List<InvoiceApplyDetailDimCreditItemVo> getScoreOrderReconciliationNotYetScene2(
            AccountingOrderScoreCustomerNotYetDimCreditScene2QueryCriteria queryCriteria,
            LoginSysUser loginSysUser) {
        return scoreOrderService.getScoreOrderReconciliationNotYetScene2(queryCriteria, loginSysUser);
    }

    @Override
    public List<InvoiceApplyDetailDimCreditItemVo> getScoreOrderReconciliationNotYetScene3(
            AccountingOrderScoreCustomerNotYetDimCreditScene3QueryCriteria queryCriteria,
            LoginSysUser loginSysUser) {
        return scoreOrderService.getScoreOrderReconciliationNotYetScene3(queryCriteria, loginSysUser);
    }

    @Override
    public R<List<InvoiceApplyDetailDimCreditItemVo>> getScoreOrderReconciliationNotYetScene4(
            AccountingOrderScoreCustomerNotYetDimCreditScene4QueryCriteria queryCriteria,
            LoginSysUser loginSysUser) {
        return scoreOrderService.getScoreOrderReconciliationNotYetScene4(queryCriteria, loginSysUser);
    }

    @Override
    public String exportExcelScoreOrderReconciliationNotYet(AccountingOrderScoreCustomerNotYetDimCreditScene1QueryCriteria queryCriteria, LoginSysUser loginSysUser) {

        log.info("\n异步操作 包裹 外层 exportExcelScoreOrderReconciliationNotYet params: \n{}", AnJsonUtils.toJson(queryCriteria));

        CompletableFuture.runAsync(() -> {

            try {

                List<InvoiceApplyDetailDimCreditItemVo> exportData = scoreOrderService.getScoreOrderReconciliationNotYetScene1(queryCriteria, loginSysUser);

                SysNotify sysNotify = unifiedOrderExportExcelService.exportExcelScoreOrderReconciliationNotYet(exportData);

                // 通知
                dubboSysNotifyService.notifyExportExcelScoreOrderReconciliationNotYet(sysNotify, loginSysUser);


            } catch (Exception e2) {
                log.error("\n异步操作 包裹 内层 exportExcelScoreOrderReconciliationNotYet {} -> 执行 异常:{}", AnJsonUtils.toJson(queryCriteria), e2);
            }
        });

        return "导出任务已经接收,正在处理中...";
    }

    /****************************************** 积分结算 dim credit 未对账 流水   end ******************************************/


    /****************************************** 供应商结算 dim order 未对账 订单 start ******************************************/

    @Override
    public UnifiedOrderSupplierHeadSumVo getSupplierUnAccountingDimOrderHeadSum(Map<String, Object> params) {

        return unifiedOrderService.getSupplierUnAccountingDimOrderHeadSum(params);
    }

    @Override
    public R<List<UnifiedOrderSupplierDimOrderNotCheckVo>> getSupplierUnAccountingDimOrderList(Map<String, Object> params, int pageNum, int pageSize) {

        return unifiedOrderService.getSupplierUnAccountingDimOrderList(params, pageNum, pageSize);
    }

    @Override
    public List<UnifiedOrderSupplierDimOrderNotCheckVo> getSupplierUnAccountingDimOrderList(Map<String, Object> params) {

        return unifiedOrderService.getSupplierUnAccountingDimOrderList(params);
    }


    @Override
    public List<UnifiedOrderSupplierNotCheckDetail2GoodsVo> getSupplierUnAccountingDetail2Goods(Map<String, Object> params) {

        return unifiedOrderService.getSupplierUnAccountingDetail2Goods(params);
    }

    /****************************************** 供应商结算 dim order 未对账 订单   end ******************************************/


    /****************************************** 供应商结算 dim goods 未对账 商品 start ******************************************/

    @Override
    public UnifiedOrderSupplierHeadSumVo getSupplierUnAccountingDimGoodsHeadSum(AccountingSupplierNotYetDimGoodsQueryCriteria criteria) {
        return unifiedOrderService.getSupplierUnAccountingDimGoodsHeadSum(criteria);
    }

    /**
     * 已添加 数据脱敏逻辑 20211203
     *
     * @param criteria
     * @param loginSysUser
     * @return
     */
    @Override
    public List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo> getSupplierUnAccountingDimGoodsList(
            AccountingSupplierNotYetDimGoodsQueryCriteria criteria,
            LoginSysUser loginSysUser) {

        // 已添加 数据脱敏逻辑 20211203
        List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo> resultList = unifiedOrderService.getSupplierUnAccountingDimGoodsList(criteria, loginSysUser);

        return resultList;
    }

    /**
     * 已添加 数据脱敏逻辑 20211203
     *
     * @param criteria
     * @param loginSysUser
     * @return
     */
    public R<List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo>> getSupplierUnAccountingDimGoodsListByPageQuery(
            AccountingSupplierNotYetDimGoodsQueryCriteria criteria,
            LoginSysUser loginSysUser) {

        // 已添加 数据脱敏逻辑 20211203
        R<List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo>> response = unifiedOrderService.getSupplierUnAccountingDimGoodsListByPageQuery(criteria, loginSysUser);

        return response;
    }

    /**
     * 已添加 数据脱敏逻辑 20211203
     *
     * @param criteria
     * @param loginSysUser
     * @return
     */
    @Override
    public String exportExcelAccountingSupplierNotYetDimGoods(AccountingSupplierNotYetDimGoodsQueryCriteria criteria, LoginSysUser loginSysUser) {

        log.info("\n异步操作 包裹 外层 exportExcelAccountingSupplierNotYetDimGoods params: \n{}", AnJsonUtils.toJson(criteria));

        CompletableFuture.runAsync(() -> {

            try {

                // 三步走 mark by linjinyu at 20210305
                // 1. 数据
                // 2. 生成excel
                // 3. 通知

                // 已添加 数据脱敏逻辑 20211203
                List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo> exportData = getSupplierUnAccountingDimGoodsList(criteria, loginSysUser);

                SysNotify sysNotify = unifiedOrderExportExcelService.exportExcelAccountingSupplierNotYetDimGoods(exportData);

                // 通知
                dubboSysNotifyService.notifyExportExcelAccountingSupplierNotYetDimGoods(sysNotify, loginSysUser);


            } catch (Exception e2) {
                log.error("\n异步操作 包裹 内层 exportExcelAccountingSupplierNotYetDimGoods{} -> 执行 异常:{}", AnJsonUtils.toJson(criteria), e2);
            }
        });

        return "导出任务已经接收,正在处理中...";
    }
    /****************************************** 供应商结算 dim goods 未对账 商品   end ******************************************/


    /**
     * 这个有个报错 , 数据问题, 里边的东西有可能为空 大概是goods的问题
     *
     * @param id
     * @return
     */
    @Override
    public UnifiedOrderGoodsDetailVo getGoodsDetail(Long id) {

        UnifiedOrderGoods orderGoods = unifiedOrderGoodsService.findById(id);

        UnifiedOrder order = unifiedOrderService.findByOrderSn(orderGoods.getOrderSn());

        UnifiedOrderGoodsDetailVo unifiedOrderGoodsDetail = AnConvertBeanUtil.copyBean(order, UnifiedOrderGoodsDetailVo.class);

        unifiedOrderGoodsDetail.setGoodsName(orderGoods.getGoodsName());
        unifiedOrderGoodsDetail.setGoodsParams(orderGoods.getGoodsParams());
        unifiedOrderGoodsDetail.setPrice(orderGoods.getPrice());
        unifiedOrderGoodsDetail.setQuantity(orderGoods.getQuantity());

        return unifiedOrderGoodsDetail;
    }

    /****************************************** 1. 页面-客户结算对账 未对账商品 start ******************************************/
    /**
     * 列表
     *
     * @param params
     * @return
     */
    @Override
    public List<UnifiedOrderJoinGoodsDetailVo> getUnifiedOrderJoinGoodsDetailVoList(Map<String, Object> params) {

        return unifiedOrderGoodsService.getUnifiedOrderJoinGoodsDetailVoList(params);
    }


    /****************************************** 1. 页面-客户结算对账 未对账商品   end ******************************************/

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

        return unifiedOrderService.findAll(queryMap);
    }


    @Override
    public Integer countAll(Map<String, Object> queryMap) {
        return unifiedOrderService.countAll(queryMap);
    }

    @Override
    public List<WxBillOrder> getVirtOrder(Map<String, Object> params) {
        return unifiedOrderService.getVirtOrder(params);
    }


    @Override
    public BigDecimal getAmount(Map<String, Object> amountQuery) {

        return unifiedOrderService.getAmount(amountQuery);
    }

    @Override
    public WxBillVirt getVirtBill(Long virtId, int year) {

        Map<String, Object> params = new HashMap<>();
        params.put("virtId", virtId);
        params.put("syear", year);
        WxBillVirt wxBillVirt = unifiedStatisticsVirtService.getVirtBill(params);

        SysEnterprise sysEnterprise = sysEnterpriseService.findByOutVirtId(virtId);

        if (wxBillVirt == null) {
            wxBillVirt = new WxBillVirt();
            wxBillVirt.setAmount(new BigDecimal(0));
            wxBillVirt.setUpayamount(new BigDecimal(0));
            wxBillVirt.setVirtId(virtId);

        }

        wxBillVirt.setVirtName(sysEnterprise.getEnterpriseName());

        List<WxBillVirtItem> items = unifiedStatisticsVirtService.getVirtItemBill(params);
        wxBillVirt.setItems(items);

        return wxBillVirt;
    }

    @Override
    public BigDecimal getPayAmount(Map<String, Object> unPayMap) {

        return unifiedOrderService.getPayAmount(unPayMap);
    }

    @Override
    public Integer getOrderCount(Map<String, Object> queryMap) {
        return unifiedOrderService.getOrderCount(queryMap);
    }


}
