package com.zm.order.tool.server.service.impl;

import com.github.dozermapper.core.Mapper;
import com.zm.order.tool.server.constants.CommonConstants;
import com.zm.order.tool.server.dao.OrderDao;
import com.zm.order.tool.server.dao.OrderIndexDao;
import com.zm.order.tool.server.dao.OrderItemCommentDao;
import com.zm.order.tool.server.dao.OrderItemDao;
import com.zm.order.tool.server.helper.OrderDataHandleHelper;
import com.zm.order.tool.server.manager.SearchCommentManager;
import com.zm.order.tool.server.manager.SearchManager;
import com.zm.order.tool.server.model.*;
import com.zm.order.tool.server.newdatasource.NewDataSourceOrderDao;
import com.zm.order.tool.server.query.OrderQuery;
import com.zm.order.tool.server.request.OrderSycRequest;
import com.zm.order.tool.server.service.OrderDataHandleService;
import com.zm.order.tool.server.routing.RoutingOrderDao;
import com.zm.order.tool.server.utils.ConvertUtils;
import com.zm.util.dto.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhuxiaofeng
 * @date 2021/9/15 14:36
 */
@Component
@SuppressWarnings("all")
public class OrderDataHandleServiceImpl implements OrderDataHandleService, InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(OrderDataHandleServiceImpl.class);

    @Autowired
    private Mapper mapper;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private NewDataSourceOrderDao newOrderDao;

    @Autowired
    private OrderIndexDao orderIndexDao;

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private SearchManager searchManager;

    @Autowired
    private OrderItemCommentDao itemCommentDao;

    @Autowired
    private SearchCommentManager commentManager;

    @Autowired
    private OrderDataHandleHelper helper;
    @Autowired
    private RoutingOrderDao routingOrderDao;

    @Override
    public Result orderBaseInfoHandle(OrderDataHandleRequest request) {
        try {
            logger.info("[orderBaseInfoHandle]start!request:{}", request);
            Assert.notNull(request.getOrderNo(), "订单号为空");
            OrderIndex orderIndex = orderIndexDao.selectOne(request.getOrderNo());
            if (Objects.isNull(orderIndex)) {
                return Result.failureData("订单索引不存在");
            }
            Order o = orderDao.selectByOrderNo(request.getOrderNo(), orderIndex.getUserId());
            if (Objects.isNull(o)) {
                return Result.failureData("订单不存在");
            }
            if (Objects.equals(1, o.getMasterDataSource())) {
                Order order = newOrderDao.selectByOrderNo(request.getOrderNo(), orderIndex.getUserId());
                if (Objects.isNull(order)) {
                    return Result.failureData("订单不存在");
                }
                Order update = helper.buildOrderUpdateData(order, request);
                newOrderDao.orderDataUpdate(update);
                Order newOrder = newOrderDao.selectById(order.getId(), order.getUserId());
                searchManager.indexOrder(newOrder, CommonConstants.ES_NEW_INDEX_TOPIC);
            } else {
                Order order = orderDao.selectByOrderNo(request.getOrderNo(), orderIndex.getUserId());
                if (Objects.isNull(order)) {
                    return Result.failureData("订单不存在");
                }
                Order update = helper.buildOrderUpdateData(order, request);
                orderDao.orderDataUpdate(update);
                Order newOrder = orderDao.selectById(order.getId(), order.getUserId());
                searchManager.indexOrder(newOrder, null);
            }
            return Result.successNullData();
        } catch (Throwable e) {
            logger.error("DelEsExpireDataTask[execute] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
    }

    @Override
    public Result rerouting() {
        int count = 0;
        Long lastId = null;
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSize(200);
        try {
            for (;;) {
                // 订单
                orderQuery.setLastId(lastId);
                List<RoutingOrder> orderList = routingOrderDao.selectList(orderQuery);
                if (CollectionUtils.isEmpty(orderList)) {
                    break;
                }
                orderDao.insertList(ConvertUtils.convertList(orderList, Order.class));
                // 商品
                List<String> orderNoList = orderList.stream().map(RoutingOrder::getOrderNo).collect(Collectors.toList());

            }
        } catch (Exception e) {
            logger.error("DelEsExpireDataTask[rerouting] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
        return Result.successNullData();
    }


    @Override
    public void afterPropertiesSet() throws Exception {

    }

    @Override
    public Result syncItemComment(OrderSycRequest request) {
        Result result = new Result();
        try {
            if (StringUtils.isEmpty(request.getOrderNo())) {
                return Result.failureData("订单号不能为空");
            }
            OrderIndex orderIndex = orderIndexDao.selectOne(request.getOrderNo());
            if (Objects.isNull(orderIndex)) {
                return Result.failureData("订单索引不存在");
            }
            Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
            ItemCommentQuery query = new ItemCommentQuery();
            query.setOrderNo(order.getOrderNo());
            query.setSellerId(order.getSellerId());
            List<OrderItemComment> commentList = itemCommentDao.selectList(query);
            commentManager.batchIndex(commentList);
            result.setStatus(true);
        } catch (Throwable e) {
            logger.error("syncItemComment[execute] failed!, cause by:{}", e);
            return Result.failureData("同步失败");
        }
        return result;
    }
}
