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


import com.alibaba.fastjson.JSON;
import com.github.dozermapper.core.Mapper;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.zm.order.tool.server.component.ShardingKeyGenerator;
import com.zm.order.tool.server.dto.*;
import com.zm.order.tool.server.manager.SearchManager;
import com.zm.order.tool.server.model.*;
import com.zm.order.tool.server.query.*;
import com.zm.order.tool.server.service.ExceptionConstants;
import com.zm.util.dto.ExceptionInfo;
import com.zm.util.dto.Result;
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.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 管理员辅助类
 *
 * @Author 陈标
 * @Date 2019/12/20 14:57
 */

@Component
public class AdminHelper {

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


    @Autowired
    private Mapper mapper;
    @Autowired
    private SearchManager searchManager;
    @Autowired
    private ShardingKeyGenerator shardingKeyGenerator;
    @Autowired
    private AdminHelper helper;

    public ExceptionInfo checkGetRefundDetailParam(RefundQuery query) {
        if (Objects.isNull(query)) {
            return ExceptionConstants.PARAM_IS_EMPTY;
        }
        if (StringUtils.isEmpty(query.getRefundNo()) && StringUtils.isEmpty(query.getOrderNo()) && StringUtils.isEmpty(query.getSourceNo())) {
            return ExceptionConstants.PARAM_REFUND_SELECT_IS_EMPTY;
        }
        return ExceptionConstants.OK;
    }


    public RefundDetailDTO convertByRefundItemList(Refund refund, List<RefundItem> refundItemList) {
        RefundDetailDTO refundDetailDTO = mapper.map(refund, RefundDetailDTO.class);
        if (!CollectionUtils.isEmpty(refundItemList)) {
            List<RefundItemDTO> refundItemDtoList = Lists.newArrayListWithCapacity(refundItemList.size());
            refundItemList.forEach(refundItem -> {
                RefundItemDTO refundItemDTO = mapper.map(refundItem, RefundItemDTO.class);
                refundItemDtoList.add(refundItemDTO);
            });
            refundDetailDTO.setRefundItemList(refundItemDtoList);
            if (!StringUtils.isEmpty(refund.getRefundAmountDetails())) {
                refundDetailDTO.setRefundAmountDetailsMap(JSON.parseObject(refund.getRefundAmountDetails(), Map.class));
            }
        }
        return refundDetailDTO;
    }

    public RefundDetailDTO convertByOrderItemList(Refund refund, List<OrderItem> orderItemList) {
        RefundDetailDTO refundDetailDTO = mapper.map(refund, RefundDetailDTO.class);
        if (!CollectionUtils.isEmpty(orderItemList)) {
            List<RefundItemDTO> refundItemDtoList = Lists.newArrayListWithCapacity(orderItemList.size());
            orderItemList.forEach(orderItem -> {
                RefundItemDTO refundItemDTO = mapper.map(orderItem, RefundItemDTO.class);
                refundItemDTO.setOrderItemId(orderItem.getId());
                refundItemDtoList.add(refundItemDTO);
            });
            refundDetailDTO.setRefundItemList(refundItemDtoList);
            if (!StringUtils.isEmpty(refund.getRefundAmountDetails())) {
                refundDetailDTO.setRefundAmountDetailsMap(JSON.parseObject(refund.getRefundAmountDetails(), Map.class));
            }
        }
        return refundDetailDTO;
    }


    public ExceptionInfo checkOrderOperationQueryParam(OrderOperationQuery query) {
        if (Objects.isNull(query)) {
            return ExceptionConstants.PARAM_IS_EMPTY;
        }
        if (CollectionUtils.isEmpty(query.getOrderNoList()) && StringUtils.isEmpty(query.getOrderNo())) {
            return ExceptionConstants.PARAM_IS_EMPTY;
        }
        return ExceptionConstants.OK;
    }


    public ExceptionInfo checkGetAdminOrderIndexParam(AdminOrderItemQuery query) {

        if (StringUtils.isEmpty(query.getOrderNo()) && CollectionUtils.isEmpty(query.getOrderNoList())) {
            return ExceptionConstants.PARAM_ORDER_NO_IS_EMPTY;
        }
        return ExceptionConstants.OK;

    }


    private Map<String, Object> convert(String info) {
        try {
            if (!StringUtils.isEmpty(info)) {
                return JSON.parseObject(info, Map.class);
            }
        } catch (Throwable throwable) {
            logger.error("convertObject info:{} failed, cause by:{}", info, Throwables.getStackTraceAsString(throwable));
        }
        return null;
    }


    public SearchOrderQuery buildSearchOrderQuery(AdminOrderItemQuery adminOrderItemQuery) {
        SearchOrderQuery searchOrderQuery = mapper.map(adminOrderItemQuery, SearchOrderQuery.class);
        return searchOrderQuery;
    }



    public Result<List<BaseIndexOrder>> getBaseIndexOrders(AdminOrderItemQuery query) throws IOException {
        Result<List<BaseIndexOrder>> result = new Result<>();
        SearchOrderQuery searchOrderQuery = this.buildSearchOrderQuery(query);
        SearchOrderDTO searchOrderDTO = searchManager.searchOrder(searchOrderQuery);
        ExceptionInfo exceptionInfo = helper.checkSearchOrderDTO(searchOrderDTO);
        if (ExceptionConstants.OK != exceptionInfo) {
            result.setException(exceptionInfo);
            return result;
        }
        result.setStatus(true);
        result.setData(searchOrderDTO.getOrderList());
        return result;
    }

    public List<BaseIndexOrder> ListBaseIndexOrder(List<String> orderNoList) throws IOException {
        SearchOrderQuery searchOrderQuery = new SearchOrderQuery();
        searchOrderQuery.setOrderNoList(orderNoList);
        SearchOrderDTO searchOrderDTO = searchManager.searchOrder(searchOrderQuery);
        List<BaseIndexOrder> orderList = searchOrderDTO.getOrderList();
        if (CollectionUtils.isEmpty(orderList)) {
            return null;
        }
        return orderList;
    }


    private ExceptionInfo checkSearchOrderDTO(SearchOrderDTO searchOrderDTO) {
        if (Objects.isNull(searchOrderDTO) || CollectionUtils.isEmpty(searchOrderDTO.getOrderList())) {
            return ExceptionConstants.NO_SELECT_ORDER;
        }
        return ExceptionConstants.OK;
    }

    public ExceptionInfo checkOrderSync(AdminOrderQuery query) {

        if (Objects.isNull(query) || Objects.isNull(query.getOrderNo())) {
            return ExceptionConstants.PARAM_IS_EMPTY;
        }
        return ExceptionConstants.OK;

    }


    public ExceptionInfo checkSearchOrderCountParam(SearchOrderQuery searchOrderQuery) {
        if (Objects.isNull(searchOrderQuery)) {
            return ExceptionConstants.PARAM_IS_EMPTY;
        }
        return ExceptionConstants.OK;
    }

    public LineUpRecordQuery buildLineUpRecordQuery(BaseIndexOrder baseIndexOrder) {
        LineUpRecordQuery lineUpRecordQuery = new LineUpRecordQuery();
        lineUpRecordQuery.setSellerId(baseIndexOrder.getSellerId());
        lineUpRecordQuery.setStoreId(baseIndexOrder.getStoreId());
        lineUpRecordQuery.setOrderNo(baseIndexOrder.getOrderNo());
        return lineUpRecordQuery;
    }

    public LineUpRecordQuery buildLineUpRecordOrderQuery(BaseIndexOrder baseIndexOrder) {
        LineUpRecordQuery lineUpRecordQuery = new LineUpRecordQuery();
        lineUpRecordQuery.setSellerId(baseIndexOrder.getSellerId());
        lineUpRecordQuery.setStoreId(baseIndexOrder.getStoreId());
        lineUpRecordQuery.setIsDeleted(0);
        return lineUpRecordQuery;
    }


    public List<OrderSimpleDTO> buildOrderSimple(List<BaseIndexOrder> orderList) {
        List<OrderSimpleDTO> orderSimpleDtoList = new ArrayList<>();
        for (BaseIndexOrder baseIndexOrder : orderList) {
            OrderSimpleDTO orderSimpleDTO = mapper.map(baseIndexOrder, OrderSimpleDTO.class);
            orderSimpleDtoList.add(orderSimpleDTO);
        }
        return orderSimpleDtoList;
    }

    public ExceptionInfo checkCreateToolInterface(ToolInterfaceDTO toolInterfaceDTO) {
        if (Objects.isNull(toolInterfaceDTO)) {
            return ExceptionConstants.PARAM_IS_EMPTY;
        }
        if (StringUtils.isEmpty(toolInterfaceDTO.getInterfaceName()) || StringUtils.isEmpty(toolInterfaceDTO.getInterfaceUrl()) || StringUtils.isEmpty(toolInterfaceDTO.getProjectName())) {
            return ExceptionConstants.PARAM_TOOL_INTERFACE_IS_EMPTY;
        }

        return ExceptionConstants.OK;
    }


    public ToolInterface buildToolInterface(ToolInterface toolInterface) {
        toolInterface.setId(shardingKeyGenerator.generateSnowflakeNumKey());
        return toolInterface;
    }

    public List<ToolInterfaceDTO> buildToolInterfaceDTO(List<ToolInterface> toolInterfaces) {

        List<ToolInterfaceDTO> list = new ArrayList<>();
        for (ToolInterface toolInterface : toolInterfaces) {
            ToolInterfaceDTO map = mapper.map(toolInterface, ToolInterfaceDTO.class);
            list.add(map);
        }
        return list;
    }

    public List<LineUpRecordDTO> buildLineUpDto(List<LineUpRecord> lineUpRecords) {
        List<LineUpRecordDTO> list = new ArrayList<>();
        for (LineUpRecord lineUpRecord : lineUpRecords) {
            LineUpRecordDTO lineUpRecordDTO = mapper.map(lineUpRecord, LineUpRecordDTO.class);
            list.add(lineUpRecordDTO);
        }
        return list;
    }

    public AdminOrderItemQuery buildAdminOrderItemQuery(AdminOrderItemQuery adminOrderItemQuery, List<String> orderNoList) {
        adminOrderItemQuery.setOrderNoList(orderNoList);
        adminOrderItemQuery.setOrderNo(null);
        adminOrderItemQuery.setUserId(null);
        return adminOrderItemQuery;
    }

    public ExceptionInfo checkListOrderSync(AdminOrderQuery query) {
        if (Objects.isNull(query) || CollectionUtils.isEmpty(query.getOrderNoList())) {
            return ExceptionConstants.PARAM_IS_EMPTY;
        }
        return ExceptionConstants.OK;

    }

    public ExceptionInfo checkUpdateOrderCompletedAtParam(OrderQuery query) {
        if (Objects.isNull(query)) {
            return ExceptionConstants.PARAM_IS_EMPTY;
        }
        if (CollectionUtils.isEmpty(query.getOrderNoList())) {
            return ExceptionConstants.PARAM_ORDER_NO_IS_EMPTY;
        }
        return ExceptionConstants.OK;
    }

    public OrderQuery buildOrderNo(OrderQuery query) {
        if (!CollectionUtils.isEmpty(query.getOrderNoList())) {
            List<String> orderNos = new ArrayList<>();
            List<String> orderNoList = query.getOrderNoList();
            for (String s : orderNoList) {
                orderNos.add(s.trim());
            }
            query.setOrderNoList(orderNos);

        }
        return query;
    }

    public ExceptionInfo checkDeleteToolInterfaceParam(Long id) {
        if (Objects.isNull(id)) {
            return ExceptionConstants.PARAM_ID_TASK_IS_EMPTY;
        }
        return ExceptionConstants.OK;
    }
}