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

import com.google.common.collect.Lists;
import com.zm.order.tool.server.component.ShardingKeyGenerator;
import com.zm.order.tool.server.constants.CommonConstants;
import com.zm.order.tool.server.dao.OrderIndexDao;
import com.zm.order.tool.server.dao.UpdateUserIdDao;
import com.zm.order.tool.server.dto.OrderAddrDTO;
import com.zm.order.tool.server.manager.SearchManager;
import com.zm.order.tool.server.model.*;
import com.zm.order.tool.server.query.OrderDiscountQuery;
import com.zm.order.tool.server.query.OrderQuery;
import com.zm.order.tool.server.service.ExceptionConstants;
import com.zm.order.tool.server.utils.ConvertUtils;
import com.zm.util.dto.ExceptionInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author 陈标
 * @Date 2020/3/26 10:02
 */
@Component
public class TemporaryHelp {

    private static final Logger logger = LoggerFactory.getLogger(TemporaryHelp.class);
    private static final String ORDER_INDEX_NAME = "order";

    @Autowired
    private ShardingKeyGenerator shardingKeyGenerator;

    @Autowired
    private UpdateUserIdDao updateUserIdDao;

    @Autowired
    private SearchManager searchManager;
    @Autowired
    private OrderIndexDao orderIndexDao;

    private static final String BEFORE_COMPLETE_AT = "beforeCompleteAt";
    private static final String AFTER_COMPLETE_AT = "afterCompleteAt";
    private static final String UPDATE_BIZ_TYPE = "updateBizType";

    public ExceptionInfo checkTemporaryParam(OrderDiscountQuery query) {
        if (Objects.isNull(query)) {
            return ExceptionConstants.PARAM_IS_EMPTY;
        }
        if (Objects.isNull(query.getStartId()) || Objects.isNull(query.getEndId())) {
            return ExceptionConstants.PARAM_TEMPORARY_TASK_IS_EMPTY;
        }
        return ExceptionConstants.OK;
    }

    public Order buildOrder(Order order) {

        Map<String, Object> extraMap = order.getExtraMap();
        extraMap.put(UPDATE_BIZ_TYPE, 0);
        order.setExtraMap(extraMap);
        return order;

    }

    public ExceptionInfo checkUpdateBizTypeParam(OrderQuery orderQuery) {
        if (Objects.isNull(orderQuery)) {
            return ExceptionConstants.PARAM_IS_EMPTY;
        }
       /* if (Objects.isNull(orderQuery.getDbIndex())) {
            return ExceptionConstants.PARAM_DB_INDEX_IS_EMPTY;
        }
        if (Objects.isNull(orderQuery)) {
            return ExceptionConstants.PARAM_TB_INDEX_IS_EMPTY;
        }*/
        return ExceptionConstants.OK;
    }

    public ExceptionInfo checkHandleUserIdParam(OrderQuery orderQuery) {
        if (Objects.isNull(orderQuery)) {
            return ExceptionConstants.PARAM_IS_EMPTY;
        }
        if (Objects.isNull(orderQuery.getIsRun())) {
            return ExceptionConstants.PARAM_RUN_IS_EMPTY;
        }
        return ExceptionConstants.OK;
    }

    public void createLog(Order order, Long newUserId) {
        UpdateUserId updateUserId = new UpdateUserId();
        updateUserId.setId(shardingKeyGenerator.generateSnowflakeNumKey());
        updateUserId.setOrderNo(order.getOrderNo());
        updateUserId.setUserId(order.getUserId());
        updateUserId.setBeforeUserId(order.getUserId());
        updateUserId.setAfterUserId(newUserId);
        updateUserIdDao.insert(updateUserId);

    }

    public void updateIndex(Order order, Long newUserId) {
        OrderIndex orderIndex = orderIndexDao.selectOne(order.getOrderNo());
        if (Objects.isNull(orderIndex)) {
            logger.warn("orderIndex is null, orderNo:{}", order.getOrderNo());
            return;
        }
        OrderIndex update = new OrderIndex();
        update.setId(orderIndex.getId());
        update.setOrderNo(orderIndex.getOrderNo());
        update.setUserId(newUserId);
        orderIndexDao.update(update);
    }

    public UpdateUserId buildOrderLog(Order order, Map<Long, String> map) {
        UpdateUserId updateUserId = new UpdateUserId();
        updateUserId.setId(shardingKeyGenerator.generateSnowflakeNumKey());
        updateUserId.setUserId(order.getUserId());
        updateUserId.setOrderNo(order.getOrderNo());
        updateUserId.setBeforeUserId(order.getUserId());
        updateUserId.setAfterUserId(null);
        updateUserId.setStatus(0);
        updateUserId.setPhone(map.get(order.getUserId()));
        return updateUserId;
    }

    public List<OrderExtra> buildOrderExtra(OrderAddrDTO orderAddrDTO, Order order) throws IllegalAccessException {
        List<OrderExtra> orderExtraList = Lists.newArrayList();
        if (Objects.nonNull(orderAddrDTO)) {
            Class<?> clazz = orderAddrDTO.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object value = field.get(orderAddrDTO);
                if (!StringUtils.isEmpty(value)) {
                    OrderExtra orderExtra = new OrderExtra();
                    orderExtra.setExtraGroup(CommonConstants.ADDR_EXTRA_GROUP);
                    orderExtra.setExtraKey(fieldName);
                    orderExtra.setExtraValue(Objects.isNull(value) ? null : value.toString());
                    orderExtra.setOrderNo(order.getOrderNo());
                    orderExtra.setUserId(order.getUserId());
                    orderExtra.setId(shardingKeyGenerator.generateSnowflakeNumKey());
                    orderExtraList.add(orderExtra);
                }
            }
        }
        return orderExtraList;
    }

    public OrderAddr buildOrderAddr(Addresses addresses, Order order) {
        OrderAddr orderAddr = ConvertUtils.convertObject(addresses, OrderAddr.class);
        orderAddr.setId(shardingKeyGenerator.generateSnowflakeNumKey());
        orderAddr.setUserId(order.getUserId());
        orderAddr.setOrderNo(order.getOrderNo());
        return orderAddr;

    }


    public Date buildReserveTime(String reserveTime, Date date) {

        try {
            SimpleDateFormat getDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = getDateFormat.format(date);
            format = format + " " + reserveTime;
            SimpleDateFormat returnDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date parse = returnDateFormat.parse(format);
            return parse;
        } catch (ParseException e) {
            logger.error("buildReserveTime is filed  reserveTime{}",reserveTime);
            return null;
        }


    }

    public SourceNoIndex buildSourceNoIndex(Order order) {

        SourceNoIndex sourceNoIndex = new SourceNoIndex();
        sourceNoIndex.setBizType(order.getBizType());
        sourceNoIndex.setOrderId(order.getId());
        sourceNoIndex.setSellerId(order.getSellerId());
        sourceNoIndex.setSourceNo(order.getSourceNo());
        sourceNoIndex.setUserId(order.getUserId());
        return sourceNoIndex;
    }
}
