package com.gic.haoban.manage.service.service.out.impl.content.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.Week;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.hologres.client.HoloClient;
import com.alibaba.hologres.client.Put;
import com.alibaba.hologres.client.model.TableSchema;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.enterprise.api.constant.EnterpriseServiceEnum;
import com.gic.enterprise.api.dto.enterprise.EnterpriseUsingStatusDTO;
import com.gic.enterprise.api.service.EnterpriseUseForbidService;
import com.gic.haoban.manage.api.dto.content.log.TriggerCustomerDetailLogDTO;
import com.gic.haoban.manage.api.dto.content.report.MaterialReportDTO;
import com.gic.haoban.manage.api.enums.content.MaterialReportType;
import com.gic.haoban.manage.api.enums.content.TriggerCustomerChannelType;
import com.gic.haoban.manage.api.service.content.task.QywxGroupMsgTaskApiService;
import com.gic.haoban.manage.service.dao.mapper.content.holo.HoloDataSource;
import com.gic.haoban.manage.service.pojo.bo.content.GroupMessageInfoBo;
import com.gic.haoban.manage.service.pojo.bo.content.binlog.MemberOrderBo;
import com.gic.haoban.manage.service.pojo.bo.content.context.PotentialCustomerNotifyContext;
import com.gic.haoban.manage.service.pojo.bo.content.holo.MemberOrderHoloBo;
import com.gic.haoban.manage.service.pojo.bo.content.holo.MemberOrderItemHoloBo;
import com.gic.haoban.manage.service.pojo.bo.content.message.OrderConvertBo;
import com.gic.haoban.manage.service.service.StaffService;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.haoban.manage.service.service.content.GroupMessageService;
import com.gic.haoban.manage.service.service.content.MaterialReportService;
import com.gic.haoban.manage.service.service.content.PotentialCustomerService;
import com.gic.haoban.manage.service.service.content.adaptor.MaterialDataAdaptor;
import com.gic.haoban.manage.service.service.content.adaptor.MaterialEnterpriseAdaptor;
import com.gic.haoban.manage.service.task.KafkaMessageServiceImpl;
import com.gic.haoban.manage.service.task.RouterConstant;
import com.gic.order.api.dto.OrderDTO;
import com.gic.order.api.dto.req.MemberOrderOptional;
import com.gic.order.api.service.member.MemberOrderReadApiService;
import com.gic.orderecommerce.api.dto.EorderDTO;
import com.gic.orderecommerce.api.service.EcommerceOrderOutputApiService;
import com.gic.redis.data.util.RedisUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author MUSI
 * @Date 2023/3/19 8:33 PM
 * @Description
 * @Version
 **/
@Component("qywxGroupMsgTaskApiServiceImpl")
public class QywxGroupMsgTaskApiServiceImpl implements QywxGroupMsgTaskApiService {

    private static final Logger log = LoggerFactory.getLogger(QywxGroupMsgTaskApiServiceImpl.class);
    @Autowired
    private GroupMessageService groupMessageService;
    @Autowired
    private MaterialReportService materialReportService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private WxEnterpriseService wxEnterpriseService;
    @Autowired
    private PotentialCustomerService potentialCustomerService;

    @Autowired
    private EcommerceOrderOutputApiService ecommerceOrderOutputApiService;
    @Autowired
    private MemberOrderReadApiService memberOrderReadApiService;
    @Autowired
    private HoloDataSource holoDataSource;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private MaterialDataAdaptor materialDataAdaptor;

    @Autowired
    EnterpriseUseForbidService enterpriseUseForbidService;

    private static final Long cache_hour_sec =  300L;

    @Override
    public ServiceResponse<Void> groupMsgTaskJob(String params) {
        log.info("执行触达客户定时任务 {}", DateUtil.datetimeToString(new Date()));
        // 获取开启【内容】权限的企业id
        List<String> enterpriseIds = groupMessageService.hasMaterialRightEnterprise(MaterialEnterpriseAdaptor.MaterialLevel.LOW.getCode());
        if (CollectionUtils.isEmpty(enterpriseIds)) {
            return ServiceResponse.success();
        }
        // 获取企业 (当前时间 - 30分钟, 当前时间)范围内的 导购分享记录。按创建时间排序
        Date currentTime = new Date();
        for (String enterpriseId : enterpriseIds) {
            GroupMessageInfoBo groupMessageInfoBo = new GroupMessageInfoBo();
            groupMessageInfoBo.setEnterpriseId(enterpriseId);
            groupMessageInfoBo.setStartTime(DateUtil.addNumForMinute(currentTime, -30));
            groupMessageInfoBo.setEndTime(currentTime);
            groupMessageService.handlerGroupMessage(groupMessageInfoBo);
        }
        return ServiceResponse.success();
    }

    /**
     * 处理客户触达日志明细
     *
     * @param params
     * @return
     */
    @Override
    public ServiceResponse<Void> handlerTriggerCustomerDetailLog(String params) {
        log.info("处理客户触达日志 {}", params);
        TriggerCustomerDetailLogDTO customerDetailLog = JSON.parseObject(params, TriggerCustomerDetailLogDTO.class);

        if (customerDetailLog == null) {
            log.info("处理客户触达日志 参数异常 {}", params);
            return ServiceResponse.success();
        }

        GroupMessageInfoBo groupMessageInfoBo = new GroupMessageInfoBo();
        groupMessageInfoBo.setEnterpriseId(customerDetailLog.getEnterpriseId());
        if (TriggerCustomerChannelType.PYQ.getCode().equals(customerDetailLog.getShareType())) {
            if (customerDetailLog.getSharePYQ() == null) {
                log.info("handlerTriggerCustomerDetailLog 分享朋友圈类型 参数异常 {}", params);
                return ServiceResponse.success();
            }
            groupMessageInfoBo.setShareLogId(customerDetailLog.getSharePYQ().getShareLogId());
        }
        groupMessageService.handlerGroupMessage(groupMessageInfoBo);
        return ServiceResponse.success();
    }

    /**
     * 素材周报
     *
     * @param params
     * @return
     */
    @Override
    public ServiceResponse<Void> handlerMaterialWeekReport(String params) {
        log.info("handlerMaterialWeekReport 执行素材周报任务开始 >>>>> params:{} date: {}", params, DateUtil.datetimeToString(new Date()));
        Date now = new Date();
        Week week = cn.hutool.core.date.DateUtil.dayOfWeekEnum(now);
        if (!Week.MONDAY.equals(week)) {
            log.info("handlerMaterialWeekReport 当前时间 不是周一 忽略 》》》 params:{}, date:{}", params, DateUtil.datetimeToString(new Date()));
            return ServiceResponse.success();
        }
        return doHandlerReportInner(MaterialReportType.WEEK.getCode(), params);
    }

    /**
     * 素材月报
     *
     * @param params
     * @return
     */
    @Override
    public ServiceResponse<Void> handlerMaterialMonthReport(String params) {
        log.info("handlerMaterialWeekReport 执行素材月报任务开始 >>>>> {}", DateUtil.datetimeToString(new Date()));
        return doHandlerReportInner(MaterialReportType.MONTH.getCode(), params);
    }

    /**
     * 发送企业周报/月报素材
     *
     * @param reportType
     * @return
     */
    private ServiceResponse<Void> doHandlerReportInner(Integer reportType, String params) {
        List<String> enterpriseIds = groupMessageService.hasMaterialRightEnterprise(MaterialEnterpriseAdaptor.MaterialLevel.LOW.getCode());
        if (CollectionUtils.isEmpty(enterpriseIds)) {
            return ServiceResponse.success();
        }
        for (String enterpriseId : enterpriseIds) {

            if (StringUtils.isNotBlank(params) && !StringUtils.equals("-1", params)) {
                log.info("执行指定企业的数据 {}", params);
                if (!StringUtils.equals(params, enterpriseId)) {
                    log.info("企业{}非目标企业,忽略", enterpriseId);
                    continue;
                }
            }
            List<String> wxEnterpriseIds = wxEnterpriseService.queryWxEnterpriseWithEnterpriseId(enterpriseId);
            if (CollectionUtils.isEmpty(wxEnterpriseIds)) {
                log.info("企业 {}未关联企微", enterpriseId);
                continue;
            }
            List<String> staffIds = staffService.queryStaffIdsWithEnterpriseId(wxEnterpriseIds);
            if (CollectionUtils.isEmpty(staffIds)) {
                log.info("企业 {} 不存在成员", enterpriseId);
                continue;
            }
            for (String staffId : staffIds) {
                MaterialReportDTO temp = new MaterialReportDTO();
                temp.setStaffId(staffId);
                temp.setEnterpriseId(enterpriseId);
                temp.setReportType(reportType);
                boolean sendMQResult = this.sendMaterialReportMQ(temp);
                log.info("发送企业{}, 成员id: {}, 结果: {}", enterpriseId, staffId, sendMQResult);
            }
        }
        return ServiceResponse.success();
    }

    /**
     * 处理单成员素材使用周报/月报
     *
     * @param params
     * @return
     * @see RouterConstant#DEAL_ONE_STAFF_MATERIAL_REPORT
     */
    @Override
    public ServiceResponse<Void> doHandlerMaterialOneStaffReportMQ(String params) {
        log.info("doHandlerMaterialOneStaffReportMQ 参数: {}", params);
        MaterialReportDTO materialReportDTO = JSON.parseObject(params, MaterialReportDTO.class);
        if (materialReportDTO == null) {
            log.info("参数异常 {}", params);
            return ServiceResponse.success();
        }
        materialReportService.handlerMaterialReport(materialReportDTO.getEnterpriseId(), materialReportDTO.getStaffId(), materialReportDTO.getReportType());
        return ServiceResponse.success();
    }

    /**
     * 发送成员使用素材消息MQ
     *
     * @param materialReportDTO
     * @return
     */
    private boolean sendMaterialReportMQ(MaterialReportDTO materialReportDTO) {
        try {
            GICMQClientUtil.getClientInstance()
                    .sendMessage(RouterConstant.DEAL_ONE_STAFF_MATERIAL_REPORT, JSON.toJSONString(materialReportDTO));
            return true;
        } catch (Exception ex) {
            log.warn("发送成员使用素材周报/月报MQ异常, 参数: {}", JSON.toJSONString(materialReportDTO), ex);
        }
        return false;
    }

    /**
     * 销售线索 通知job
     *
     * @param params
     * @return 每半小时通知一次，提醒时间段：当天 8:00~23:00
     * 当天23:00~第二天8:00产生的线索动态，第二天 8:00 提醒
     * 区经不发应用、小程序消息
     * 导购、店长 应用只发主门店数据的应用消息
     */
    @Override
    public ServiceResponse<Void> potentialCustomerJob(String params) {
        Date now = new Date();
        log.info("potentialCustomerJob 执行销售线索通知 {}", cn.hutool.core.date.DateUtil.format(now, "yyyy-MM-dd HH:mm:ss"));
        int currentHour = cn.hutool.core.date.DateUtil.hour(now, true);
        if (currentHour >= 23 || currentHour < 8) {
            log.info("当前时间处于消息禁发时间, 忽略{}", cn.hutool.core.date.DateUtil.format(now, "yyyy-MM-dd HH:mm:ss"));
            return ServiceResponse.success();
        }
        List<String> enterpriseIds = groupMessageService.hasMaterialRightEnterprise(MaterialEnterpriseAdaptor.MaterialLevel.LOW.getCode());
        if (CollectionUtils.isEmpty(enterpriseIds)) {
            log.info("开通内容权限的企业为空");
            return ServiceResponse.success();
        }
        Date startTime = cn.hutool.core.date.DateUtil.offsetMinute(now, -30).toJdkDate();
        // 如果是8点那次的执行 需要获取 23 ～ 8点的数据
        if (checkIsTodayFirst(now)) {
            log.info("本次执行为当天第一次执行 {}", cn.hutool.core.date.DateUtil.format(now, "yyyy-MM-dd HH:mm:ss"));
            Date yesterday = cn.hutool.core.date.DateUtil.yesterday().toJdkDate();
            Calendar calendar = Calendar.getInstance();
            calendar.clear();
            calendar.setTime(yesterday);
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            startTime = calendar.getTime();
        }
        for (String enterpriseId : enterpriseIds) {
            PotentialCustomerNotifyContext context = PotentialCustomerNotifyContext.builder()
                    .enterpriseId(enterpriseId)
                    .startTime(startTime)
                    .endTime(now)
                    .build();
            potentialCustomerService.sendPotentialCustomerNotice(context);
        }
        return ServiceResponse.success();
    }

    /**
     * 判断是否是当天第一次
     * 执行时间处于 8:00 ~ 8:30
     *
     * @param now
     * @return
     */
    int hour_sec = 30 * 60;

    private boolean checkIsTodayFirst(Date now) {
        DateTime temp = cn.hutool.core.date.DateUtil.offsetSecond(now, -(hour_sec));
        return cn.hutool.core.date.DateUtil.hour(temp, true) < 8;
    }


    /**
     * 记录会员订单为数组
     *
     * @param params
     * @return
     */
    @Override
    public ServiceResponse<Void> recordMemberOrderForData(String params) {

        // 冗余订单数据到基础侧
        MemberOrderBo memberOrderBo = JSON.parseObject(params, MemberOrderBo.class);
        if (memberOrderBo == null) {
            return ServiceResponse.success();
        }
        String enterpriseId = memberOrderBo.getEnterpriseId();
        String key = "haoban_enterprise_content:" + enterpriseId;
        String cache = RedisUtil.getCache(key, String.class);
        if (StringUtils.isBlank(cache)) {
            cache = "0";
            ServiceResponse<List<EnterpriseUsingStatusDTO>> tempServiceResponse = enterpriseUseForbidService.getUseEnterpriseByCode(EnterpriseServiceEnum.CONTENT.getRightMenuCode(), enterpriseId);
            if (!tempServiceResponse.isSuccess() || CollectionUtils.isEmpty(tempServiceResponse.getResult())) {
                log.info("企业 {} 没有内容权限 {}", enterpriseId, JSON.toJSONString(tempServiceResponse));
                RedisUtil.setCache(key, cache, cache_hour_sec, TimeUnit.SECONDS);
                return ServiceResponse.success();
            }
            EnterpriseUsingStatusDTO enterpriseUsingStatusDTO = tempServiceResponse.getResult().get(0);
            if (!Boolean.TRUE.equals(enterpriseUsingStatusDTO.getVaild())) {
                log.info("企业 {} 内容权限已失效 {}", enterpriseId, JSON.toJSONString(tempServiceResponse));
                RedisUtil.setCache(key, cache, cache_hour_sec, TimeUnit.SECONDS);
                return ServiceResponse.success();
            }
            cache = "1";
            RedisUtil.setCache(key, cache, cache_hour_sec, TimeUnit.SECONDS);
        }
        if (!StringUtils.equals(cache, "1")) {
            log.info("企业 {} 没有内容权限", enterpriseId);
            return ServiceResponse.success();
        }
        // 订单纬度
        MemberOrderHoloBo orderHoloBo = new MemberOrderHoloBo();
        // 订单项纬度
        List<MemberOrderItemHoloBo> orderItemHoloBos = new ArrayList<>();
        // 订单纬度
        // enterprise_id, clerk_id, store_id, pay_amount, biz_id,
        // 订单项纬度
        if (KafkaMessageServiceImpl.tab_gic_eorder.equals(memberOrderBo.getTableName())) {
            EorderDTO eorderDTO = ecommerceOrderOutputApiService.getEorderWholeByMemberIdAndOrderId(memberOrderBo.getMemberId(), memberOrderBo.getOrderId());
            if (eorderDTO == null) {
                log.info("订单不存在 {}", params);
                return ServiceResponse.success();
            }
            this.buildMemberEorder(orderHoloBo, orderItemHoloBos, eorderDTO);
        }
        if (KafkaMessageServiceImpl.tab_gic_order.equals(memberOrderBo.getTableName())) {
            ServiceResponse<OrderDTO> serviceResponse = memberOrderReadApiService.queryById(memberOrderBo.getEnterpriseId(),
                    memberOrderBo.getMemberId(), memberOrderBo.getOrderId(), MemberOrderOptional.item());
            if (!serviceResponse.isSuccess() || serviceResponse.getResult() == null) {
                log.info("查询订单异常 params:{} {}", params, JSON.toJSONString(serviceResponse));
                return ServiceResponse.success();
            }

            this.buildMemberOrder(orderHoloBo, orderItemHoloBos, serviceResponse);
        }
        List<OrderConvertBo> orderConvertBos = new ArrayList<>();
        try {
            HoloClient client = holoDataSource.getClient();
            if (client == null) {
                log.error("recordMemberOrderForData 数仓数据源链接异常, 请检查！！！！{}", JSON.toJSONString(orderConvertBos));
                return ServiceResponse.success();
            }
            SerializeConfig serializeConfig = new SerializeConfig();
            serializeConfig.setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCase);
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(orderHoloBo, serializeConfig));
            if (Objects.nonNull(orderHoloBo.getContentMaterialId())) {
                TableSchema tableSchema = client.getTableSchema("tab_gic_cms_order");
                Put temp = new Put(tableSchema);
                for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                    temp.setObject(entry.getKey(), entry.getValue());
                }
                client.put(Collections.singletonList(temp));
            }

            orderItemHoloBos = orderItemHoloBos
                    .stream()
                    .filter(item -> Objects.nonNull(item.getContentMaterialId()))
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(orderItemHoloBos)) {
                TableSchema cmsOrderItem = client.getTableSchema("tab_gic_cms_order_item");
                List<Put> puts = orderItemHoloBos.stream()
                        .map(item -> {
                            Put _temp = new Put(cmsOrderItem);
                            JSONObject tempJsonObject = JSON.parseObject(JSON.toJSONString(item, serializeConfig));
                            for (Map.Entry<String, Object> entry : tempJsonObject.entrySet()) {
                                _temp.setObject(entry.getKey(), entry.getValue());
                            }
                            return _temp;
                        })
                        .collect(Collectors.toList());
                client.put(puts);
            }
            log.info("recordMemberOrderForData 会员订单数据组写入完成 >>>>>");
        } catch (Exception ex) {
            log.info("recordMemberOrderForData 数据组写入异常 {}", JSON.toJSONString(orderConvertBos), ex);
        }
        return ServiceResponse.success();
    }

    private void buildMemberOrder(MemberOrderHoloBo orderHoloBo, List<MemberOrderItemHoloBo> orderItemHoloBos, ServiceResponse<OrderDTO> serviceResponse) {
        OrderDTO orderDTO = serviceResponse.getResult();
        orderHoloBo.setOrderId(orderDTO.getOrderId());
        orderHoloBo.setEnterpriseId(orderDTO.getEnterpriseId());
        orderHoloBo.setMemberId(orderDTO.getMemberId());
        orderHoloBo.setOrderNumber(orderDTO.getOrderNumber());
        orderHoloBo.setOorderNumber(orderDTO.getOorderNumber());
        orderHoloBo.setPaidAmount(BigDecimal.valueOf(orderDTO.getPaidAmount()));
        orderHoloBo.setPayAmount(BigDecimal.valueOf(orderDTO.getPayAmount()));
        orderHoloBo.setReceiptsDate(DateUtil.dateToStr(orderDTO.getOrderTime(), DateUtil.FORMAT_DATETIME_19));
        orderHoloBo.setPayTime(DateUtil.dateToStr(orderDTO.getOrderTime(), DateUtil.FORMAT_DATETIME_19));
        orderHoloBo.setChannelCode(orderDTO.getChannelCode());
        if (StringUtils.isBlank(orderHoloBo.getChannelCode())) {
            orderHoloBo.setChannelCode(MemberOrderBo.weimo);
        }
        orderHoloBo.setClerkId(orderDTO.getClerkId());
        orderHoloBo.setClerkCode(orderDTO.getClerkCode());
        ClerkDTO clerkDTO = clerkService.getClerkByClerkId(orderDTO.getClerkId());
        if (clerkDTO != null) {
            orderHoloBo.setClerkName(clerkDTO.getClerkName());
        }
        orderHoloBo.setStoreId(orderDTO.getStoreId());
        orderHoloBo.setStoreCode(orderDTO.getStoreCode());
        orderHoloBo.setStoreName(orderDTO.getStoreName());
        orderHoloBo.setProductCount(orderDTO.getGoodsCount());
        orderHoloBo.setCreateTime(DateUtil.dateToStr(orderDTO.getCreateTime(), DateUtil.FORMAT_DATETIME_19));
        orderHoloBo.setUpdateTime(DateUtil.dateToStr(orderDTO.getCreateTime(), DateUtil.FORMAT_DATETIME_19));
        orderHoloBo.setDeleteFlag(0);
        MaterialDataAdaptor.MaterialBizInfo materialBizInfo = materialDataAdaptor.queryMaterialBizInfo(orderDTO.getEnterpriseId(), orderDTO.getMemberId(), orderDTO.getOrderTime(), null);
        if (materialBizInfo != null) {
            orderHoloBo.setContentMaterialId(Long.parseLong(materialBizInfo.getBizId()));
            orderHoloBo.setShareClerkId(materialBizInfo.getClerkId());
            orderHoloBo.setShareStoreId(materialBizInfo.getStoreId());
        }
        // 组装order_item
        if (CollectionUtils.isNotEmpty(orderDTO.getList())) {
            List<MemberOrderItemHoloBo> itemHoloBos = orderDTO.getList()
                    .stream()
                    .map(item -> {
                        MemberOrderItemHoloBo orderItemHoloBo = new MemberOrderItemHoloBo();
                        orderItemHoloBo.setOrderItemId(item.getOrderItemId());
                        orderItemHoloBo.setOrderId(item.getOrderId());
                        orderItemHoloBo.setOrderNumber(orderDTO.getOrderNumber());
                        orderItemHoloBo.setOorderNumber(orderDTO.getOorderNumber());
                        orderItemHoloBo.setReceiptsDate(DateUtil.dateToStr(orderDTO.getOrderTime(), DateUtil.FORMAT_DATETIME_19));
                        orderItemHoloBo.setEnterpriseId(orderDTO.getEnterpriseId());
                        orderItemHoloBo.setMemberId(item.getMemberId());
                        orderItemHoloBo.setChannelCode(orderHoloBo.getChannelCode());
                        orderItemHoloBo.setStoreId(orderItemHoloBo.getStoreId());
                        orderItemHoloBo.setProductCode(item.getProductCode());
                        orderItemHoloBo.setProductName(item.getProductName());
                        orderItemHoloBo.setSkuCode(item.getSkuCode());
                        orderItemHoloBo.setSkuNum(item.getNumber());
                        orderItemHoloBo.setPayAmount(BigDecimal.valueOf(item.getItemPrice()));
                        orderItemHoloBo.setPaidAmount(BigDecimal.valueOf(item.getItemPriceActual()));
                        orderItemHoloBo.setCreateTime(orderItemHoloBo.getCreateTime());
                        orderItemHoloBo.setUpdateTime(orderItemHoloBo.getUpdateTime());
                        orderItemHoloBo.setDeleteFlag(0);

                        MaterialDataAdaptor.MaterialBizInfo tempMaterialInfo
                                = materialDataAdaptor.queryMaterialBizInfo(orderItemHoloBo.getEnterpriseId(), item.getMemberId(), orderDTO.getOrderTime(), item.getProductCode());
                        if (tempMaterialInfo != null) {
                            orderItemHoloBo.setContentMaterialId(Long.parseLong(tempMaterialInfo.getBizId()));
                            Long materialBaseId = materialDataAdaptor.queryMaterialBaseId(orderItemHoloBo.getEnterpriseId(), orderItemHoloBo.getContentMaterialId());
                            orderItemHoloBo.setAuditMaterialId(materialBaseId);
                        }
                        return orderItemHoloBo;
                    })
                    .collect(Collectors.toList());
            orderItemHoloBos.addAll(itemHoloBos);
        }
    }

    private void buildMemberEorder(MemberOrderHoloBo orderHoloBo, List<MemberOrderItemHoloBo> orderItemHoloBos, EorderDTO eorderDTO) {
        orderHoloBo.setOrderId(eorderDTO.getEorderId());
        orderHoloBo.setEnterpriseId(eorderDTO.getEnterpriseId());
        orderHoloBo.setMemberId(eorderDTO.getMemberId());
        orderHoloBo.setOrderNumber(eorderDTO.getOrderNo());
        orderHoloBo.setOorderNumber(eorderDTO.getOriginalOrderNo());
        orderHoloBo.setPaidAmount(BigDecimal.valueOf(eorderDTO.getTotalAmount()));
        orderHoloBo.setPayAmount(BigDecimal.valueOf(eorderDTO.getPaymentAmount()));
        orderHoloBo.setReceiptsDate(DateUtil.dateToStr(eorderDTO.getOrderCreateTime(), DateUtil.FORMAT_DATETIME_19));
        orderHoloBo.setPayTime(DateUtil.dateToStr(eorderDTO.getOrderCreateTime(), DateUtil.FORMAT_DATETIME_19));
        if (eorderDTO.getPayTime() != null) {
            orderHoloBo.setPayTime(DateUtil.dateToStr(eorderDTO.getPayTime(), DateUtil.FORMAT_DATETIME_19));
        }
        orderHoloBo.setChannelCode(eorderDTO.getChannelCode());
        if (StringUtils.isBlank(orderHoloBo.getChannelCode())) {
            orderHoloBo.setChannelCode(MemberOrderBo.weimo);
        }
        orderHoloBo.setClerkId(eorderDTO.getClerkId());
        orderHoloBo.setClerkCode(eorderDTO.getClerkCode());
        ClerkDTO clerkDTO = clerkService.getClerkByClerkId(eorderDTO.getClerkId());
        if (clerkDTO != null) {
            orderHoloBo.setClerkName(clerkDTO.getClerkName());
        }
        orderHoloBo.setStoreId(eorderDTO.getStoreId());
        orderHoloBo.setStoreCode(eorderDTO.getStoreCode());
        orderHoloBo.setStoreName(eorderDTO.getStoreName());
        orderHoloBo.setProductCount(eorderDTO.getGoodsCount());
        orderHoloBo.setCreateTime(DateUtil.dateToStr(eorderDTO.getCreateTime(), DateUtil.FORMAT_DATETIME_19));
        orderHoloBo.setUpdateTime(DateUtil.dateToStr(eorderDTO.getUpdateTime(), DateUtil.FORMAT_DATETIME_19));
        orderHoloBo.setDeleteFlag(0);
        MaterialDataAdaptor.MaterialBizInfo materialBizInfo = materialDataAdaptor.queryMaterialBizInfo(eorderDTO.getEnterpriseId(), eorderDTO.getMemberId(), eorderDTO.getOrderCreateTime(), null);
        if (materialBizInfo != null) {
            orderHoloBo.setContentMaterialId(Long.parseLong(materialBizInfo.getBizId()));
            Long materialBaseId = materialDataAdaptor.queryMaterialBaseId(eorderDTO.getEnterpriseId(), orderHoloBo.getContentMaterialId());
            orderHoloBo.setAuditMaterialId(materialBaseId);
            orderHoloBo.setShareClerkId(materialBizInfo.getClerkId());
            orderHoloBo.setShareStoreId(materialBizInfo.getStoreId());
        }

        // 组装order_item
        if (CollectionUtils.isNotEmpty(eorderDTO.getItem())) {
            List<MemberOrderItemHoloBo> collect = eorderDTO.getItem()
                    .stream()
                    .map(item -> {
                        MemberOrderItemHoloBo orderItemHoloBo = new MemberOrderItemHoloBo();
                        orderItemHoloBo.setOrderItemId(item.getEorderItemId());
                        orderItemHoloBo.setOrderId(item.getEorderId());
                        orderItemHoloBo.setOrderNumber(eorderDTO.getOrderNo());
                        orderItemHoloBo.setOorderNumber(eorderDTO.getOriginalOrderNo());
                        orderItemHoloBo.setReceiptsDate(DateUtil.dateToStr(eorderDTO.getOrderCreateTime(), DateUtil.FORMAT_DATETIME_19));
                        orderItemHoloBo.setEnterpriseId(item.getEnterpriseId());
                        orderItemHoloBo.setMemberId(item.getMemberId());
                        orderItemHoloBo.setChannelCode(orderHoloBo.getChannelCode());
                        orderItemHoloBo.setStoreId(eorderDTO.getStoreId());
                        orderItemHoloBo.setProductId(item.getGoodsId());
                        orderItemHoloBo.setProductCode(item.getGoodsCode());
                        orderItemHoloBo.setProductName(item.getGoodsTitle());
                        orderItemHoloBo.setSkuId(item.getSkuId());
                        orderItemHoloBo.setSkuCode(item.getSkuCode());
                        orderItemHoloBo.setSkuName(item.getSkuName());
                        orderItemHoloBo.setSkuNum(item.getSkuNum());
                        orderItemHoloBo.setPayAmount(BigDecimal.valueOf(item.getPayAmount()));
                        orderItemHoloBo.setPaidAmount(BigDecimal.valueOf(item.getTotalAmount()));
                        orderItemHoloBo.setCreateTime(DateUtil.dateToStr(eorderDTO.getCreateTime(), DateUtil.FORMAT_DATETIME_19));
                        orderItemHoloBo.setUpdateTime(DateUtil.dateToStr(eorderDTO.getUpdateTime(), DateUtil.FORMAT_DATETIME_19));
                        orderItemHoloBo.setDeleteFlag(0);

                        MaterialDataAdaptor.MaterialBizInfo tempMaterialInfo
                                = materialDataAdaptor.queryMaterialBizInfo(item.getEnterpriseId(), item.getMemberId(), eorderDTO.getOrderCreateTime(), item.getGoodsCode());
                        if (tempMaterialInfo != null) {
                            orderItemHoloBo.setContentMaterialId(Long.parseLong(tempMaterialInfo.getBizId()));
                            Long materialBaseId = materialDataAdaptor.queryMaterialBaseId(eorderDTO.getEnterpriseId(), orderItemHoloBo.getContentMaterialId());
                            orderItemHoloBo.setAuditMaterialId(materialBaseId);
                        }
                        return orderItemHoloBo;
                    })
                    .collect(Collectors.toList());
            orderItemHoloBos.addAll(collect);
        }
    }
}
