package com.zm.order.tool.server.handler;

import com.alibaba.fastjson.JSON;
import com.github.dozermapper.core.Mapper;
import com.google.common.collect.Lists;
import com.zm.order.tool.server.builder.SearchRequestBuilder;
import com.zm.order.tool.server.dto.OrderDTO;
import com.zm.order.tool.server.dto.RefundDTO;
import com.zm.order.tool.server.enums.BizTypeEnum;
import com.zm.order.tool.server.helper.OrderWriteServiceHelper;
import com.zm.order.tool.server.model.BaseIndexOrder;
import com.zm.order.tool.server.model.Order;
import com.zm.order.tool.server.model.OrderItem;
import com.zm.order.tool.server.model.UstoreIndexOrder;
import com.zm.order.tool.server.query.SearchOrderQuery;
import com.zm.order.tool.server.utils.OrderCommonUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 企迈友店业务处理器
 *
 * <p>
 *
 * </p>
 *
 * @author nianchang
 * @date 2023/10/07 2:31 下午
 */
@Component
public class UstoreBusinessHandler implements BusinessHandler {

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

    @Autowired
    private Mapper mapper;

    @Autowired
    private OrderWriteServiceHelper helper;

    @Override
    public Integer bizType() {
        return BizTypeEnum.U_STORE.getType();
    }

    @Override
    public BaseIndexOrder buildIndexOrder(Order order) {
        UstoreIndexOrder indexOrder = mapper.map(order, UstoreIndexOrder.class);
        buildBaseInfo(indexOrder, order);
        buildExtInfo(indexOrder, order);
        buildItemInfo(indexOrder, order);
        return indexOrder;
    }

    private void buildExtInfo(UstoreIndexOrder indexOrder, Order order) {
        Map<String, Object> extraMap = order.getExtraMap();
        if (!CollectionUtils.isEmpty(extraMap)) {
            Object platformSeller = extraMap.get("platformSellerId");
            if (platformSeller != null) {
                try {
                    indexOrder.setPlatformSellerId(Long.parseLong(platformSeller.toString()));
                } catch (Exception e) {
                    logger.error("UstoreBusinessHandler[set_platform_seller_id]failed! order:{}, cause by:{}",
                            order, e);
                }
            }
        }
    }

    private void buildBaseInfo(UstoreIndexOrder indexOrder, Order order) {
        indexOrder.setOrderId(order.getId());
        indexOrder.setSearchPayer(order.getPayer());
        if (Objects.nonNull(order.getActualAmount())) {
            indexOrder.setSearchActualAmount(order.getActualAmount());
        }
        if (Objects.nonNull(order.getCompletedAt())) {
            indexOrder.setSearchCompletedAt(order.getCompletedAt());
        }
        indexOrder.setRefundCompleted(1);

    }

    private void buildItemInfo(UstoreIndexOrder indexOrder, Order order) {
        List<OrderItem> itemList = helper.getItemList(order);
        List<String> searchCondition = new ArrayList<>();
        this.parseItemAttribute(indexOrder, itemList, searchCondition);
        this.setSearchAttribute(indexOrder, order, searchCondition);
    }

    /**
     * 全局搜索
     *
     * <p>
     *      多个条件拼接在一起，用','分割，多条件精准搜索
     *      现有条件：订单号、手机号、取餐号、三方单号、商品名称、商品id、桌台号
     *      后续可能还会增加
     * </p>
     *
     * @param indexOrder ES mapping文档
     * @param order 订单详情
     * @param searchCondition 全局搜索条件
     */
    private void setSearchAttribute(UstoreIndexOrder indexOrder, Order order, List<String> searchCondition) {
        searchCondition.add(order.getMobile());
        searchCondition.add(order.getOrderNo());
        if (!StringUtils.isEmpty(order.getSourceNo())) {
            searchCondition.add(order.getSourceNo());
        }
        if (!StringUtils.isEmpty(order.getStoreOrderNo())) {
            searchCondition.add(order.getStoreOrderNo());
        }
        indexOrder.setGlobalSearch(OrderCommonUtils.join(",", searchCondition));
    }

    /**
     * 解析商品属性赋值
     *
     * <p>
     *      获取商品type支持检索
     *      获取商品名称、itemId支持检索
     * </p>
     *
     * @param index	ES mapping文档
     * @param itemList 商品列表
     * @param searchCondition 全局搜索条件
     */
    private void parseItemAttribute(UstoreIndexOrder index, List<OrderItem> itemList, List<String> searchCondition) {
        if (CollectionUtils.isEmpty(itemList)) {
            return;
        }
        final int size = itemList.size();
        Set<Integer> itemTypeSet = new HashSet<>(size);
        Set<String> itemIdList = new HashSet<>(size);
        Set<String> itemNameList = new HashSet<>(size);
        Set<String> itemBarcodeList = new HashSet<>(size);
        helper.parseItem(itemList, searchCondition, itemTypeSet, itemIdList, itemNameList, itemBarcodeList);

        index.setItemIdList(Lists.newArrayList(itemIdList));
        index.setItemBarcodeList(Lists.newArrayList(itemBarcodeList));
        index.setItemTypeList(Lists.newArrayList(itemTypeSet));
        index.setItemNamesKeyword(Lists.newArrayList(itemNameList));
    }

    @Override
    public SearchSourceBuilder buildSearchSourceBuilder(SearchOrderQuery query) {
        SearchSourceBuilder builder = SearchRequestBuilder.buildOrderSearchBuilder(query);
        BoolQueryBuilder boolBuilder = (BoolQueryBuilder) builder.query();
        buildBaseSearchInfo(query, boolBuilder);
        return builder;
    }

    private void buildBaseSearchInfo(SearchOrderQuery searchOrderQuery, BoolQueryBuilder boolQueryBuilder) {

    }

    @Override
    public List<BaseIndexOrder> parseIndexOrder(SearchHit[] searchHits) {
        List<BaseIndexOrder> list = Lists.newArrayListWithCapacity(searchHits.length);
        for (SearchHit searchHit : searchHits) {
            UstoreIndexOrder each = JSON.parseObject(searchHit.getSourceAsString(), UstoreIndexOrder.class);
            list.add(each);
        }
        return list;
    }

    @Override
    public Integer getRefundAmount(RefundDTO refundDTO) {
        return 0;
    }

    @Override
    public BaseIndexOrder getOrderDto(BaseIndexOrder baseIndexOrder, OrderDTO orderDTO, Order order) {
        return null;
    }

    private List<RefundDTO> queryRefundList(OrderDTO orderDTO) {
        return null;
    }


}
