package com.ms.biz.tool;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.ms.api.dto.dsapi.response.SourceProductInfo;
import com.ms.api.dto.dsapi.response.SourceSkuInfo;
import com.ms.biz.bo.OrderItemSkuInfoBO;
import com.ms.biz.consts.AfterSaleConst;
import com.ms.biz.consts.DsOrderConst;
import com.ms.api.dto.dsapi.response.GetPurchaseOrderItemsAndSourceItemsResponseDTO;
import org.apache.commons.lang3.StringUtils;

public class DsOrderTool {

    public static String getDsRefundStatusByAfterSaleStatus(Integer afterSaleStatus) {
        if (afterSaleStatus == null) {
            return null;
        }

        Map<String, Integer[]> map = new HashMap<>();
        map.put(DsOrderConst.REFUND_STATUS_REFUNDING, new Integer[] {
            AfterSaleConst.AFTERSALE_STATUS_PRE_SALE_ALL_AUDIT,
            AfterSaleConst.AFTERSALE_STATUS_REFUND_AUDIT,
            AfterSaleConst.AFTERSALE_STATUS_RETURN_AUDIT,
            AfterSaleConst.AFTERSALE_STATUS_EXCHANGE_AUDIT,
            AfterSaleConst.AFTERSALE_STATUS_WAIT_BUYER_RETURN_GOODS,
            AfterSaleConst.AFTERSALE_STATUS_AFTER_SALE_AUDIT,
            AfterSaleConst.AFTERSALE_STATUS_RETURN_RECEIVE,
            AfterSaleConst.AFTERSALE_STATUS_AUDIT_REFUNDING,
            AfterSaleConst.AFTERSALE_STATUS_RETURN_SHIP,
            AfterSaleConst.AFTERSALE_STATUS_UPLOAD_REFUND
        });

        map.put(DsOrderConst.REFUND_STATUS_CLOSE, new Integer[] {
            AfterSaleConst.AFTERSALE_STATUS_REFUSE,
            AfterSaleConst.AFTERSALE_STATUS_RECEIVE_REFUSE,
            AfterSaleConst.AFTERSALE_STATUS_REFUSE_AFTER_SALE_APPLY,
            AfterSaleConst.AFTERSALE_STATUS_CLOSE,
            AfterSaleConst.AFTERSALE_STATUS_SELLER_REFUSE_TO_RETURN_GOODS_AFTER
        });

        map.put(DsOrderConst.REFUND_STATUS_FINISH, new Integer[] {
            AfterSaleConst.AFTERSALE_STATUS_WAIT_BUYER_RECEIVE,
            AfterSaleConst.AFTERSALE_STATUS_EXCHANGE_SUCCESS,
            AfterSaleConst.AFTERSALE_STATUS_REFUND_SUCCESS
        });

        String dsRefundStatus = null;
        for (Map.Entry<String, Integer[]> entry : map.entrySet()) {
            String refundStatus = entry.getKey();
            Integer[] afterSaleStatusArr = entry.getValue();

            if (Arrays.asList(afterSaleStatusArr).contains(afterSaleStatus)) {
                dsRefundStatus = refundStatus;
                break;
            }
        }

        return dsRefundStatus;
    }


    public static String build1688OrderUrl(String orderSn){
        return "https://trade.1688.com/order/new_step_order_detail.htm?orderId=".concat(orderSn);
    }

    public static String getDsAutoPurchaseOrderBufferGmtExec(Integer delayPurchaseMinute, Date orderGmtPayTime) {

        long time = System.currentTimeMillis() / 1000;

        long orderPayTime = (orderGmtPayTime != null) ? orderGmtPayTime.getTime() / 1000 : 0;
        long payDiff = time - orderPayTime;
        int delayPurchaseSecond = delayPurchaseMinute * 60;
        int baseSecond = new Random().nextInt(96) + 5;
        if (payDiff < delayPurchaseSecond) {
            baseSecond += delayPurchaseSecond - payDiff;
        }
        long execTime = time + baseSecond;
        LocalDateTime dateTime = LocalDateTime.ofEpochSecond(execTime, 0, ZoneOffset.UTC);
        int h = dateTime.getHour();

        if (h >= 23) {
            execTime += 8 * 3600;
        } else if (h < 8) {
            execTime += (8 - h) * 3600;
        }
        return LocalDateTime.ofEpochSecond(execTime, 0, ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    public static String filterSpecialString(String skuSubName) {
        return skuSubName.replace("（", "(")
                .replace("）", ")")
                .replace("：", ":")
                .replace("【", "[")
                .replace("】", "]")
                .replace("，", ",")
                .replace("；", ";")
                .replace("|", " ");
    }

    public static boolean isSkuSubNameEqual(String platformSkuSubName, String sourceSkuSubName) {
        String[] platformSkuSubNames = filterSpecialString(platformSkuSubName).split(" ");
        String[] sourceSkuSubNames = filterSpecialString(sourceSkuSubName).split(" ");
        int platformSkuSubNameLength = 0;
        int sourceSkuSubNameLength = 0;
        int findCount = 0;
        for (int i = 0; i < platformSkuSubNames.length; i++) {
            platformSkuSubName = platformSkuSubNames[i];
            if (StringUtils.isEmpty(platformSkuSubName)) {
                continue;
            }
            platformSkuSubNameLength++;
            for (int j = 0; j < sourceSkuSubNames.length; j++) {
                sourceSkuSubName = sourceSkuSubNames[j];
                if (Objects.equals(sourceSkuSubName, platformSkuSubName)) {
                    findCount++;
                    break;
                }
            }
        }
        for (int i = 0; i < sourceSkuSubNames.length; i++) {
            sourceSkuSubName = sourceSkuSubNames[i];
            if (StringUtils.isEmpty(sourceSkuSubName)) {
                continue;
            }
            sourceSkuSubNameLength++;
        }
        return (sourceSkuSubNameLength == platformSkuSubNameLength && platformSkuSubNameLength == findCount);
    }

    public static SourceSkuInfo getMatchSourceSkuInfo(OrderItemSkuInfoBO platformItem, Map<String, String> platformSkuIdAndSourceSkuIdMap, SourceProductInfo productInfo) {
        if (platformItem == null || productInfo == null) {
            return null;
        }
        String platformSkuSubName = platformItem.getSkuSubName();
        platformSkuSubName = platformSkuSubName.replaceAll("\\d+(小时内发货|天内发货)", "");

        String manualRelateSourceSkuId = platformSkuIdAndSourceSkuIdMap.get(platformItem.getSkuId());
        Long sourceItemId = productInfo.getSourceItemId();

        SourceSkuInfo manualRelateSkuInfo = null;
        SourceSkuInfo matchSkuInfo = null;
        for (SourceSkuInfo skuInfo : productInfo.getSkus()) {
            if (!StringUtils.isEmpty(manualRelateSourceSkuId) && manualRelateSourceSkuId.equals(skuInfo.getSourceSkuId().toString())) {
                manualRelateSkuInfo = skuInfo;
                break;
            }
            if (Objects.equals(skuInfo.getSourceSkuId(), sourceItemId) && StringUtils.isEmpty(manualRelateSourceSkuId)) {
                matchSkuInfo = skuInfo;
                break;
            }
            if (DsOrderTool.isSkuSubNameEqual(platformSkuSubName, skuInfo.getSkuSubName())) {
                matchSkuInfo = skuInfo;
            }
        }

        return manualRelateSkuInfo != null ? manualRelateSkuInfo : matchSkuInfo;
    }

    public static int getRealSourceSkuPurchaseQuantity(Long platformSkuId, Integer platformItemTotal, SourceSkuInfo matchSourceSkuInfo, Map<String, GetPurchaseOrderItemsAndSourceItemsResponseDTO.SourceItemSkuRelation> platformSkuIdAndSourceSkuInfoMap) {
        if (platformSkuIdAndSourceSkuInfoMap == null || platformSkuIdAndSourceSkuInfoMap.isEmpty() || matchSourceSkuInfo == null) {
            return platformItemTotal;
        }

        int purchaseQuantity = platformItemTotal;

        GetPurchaseOrderItemsAndSourceItemsResponseDTO.SourceItemSkuRelation manualSourceSkuInfo = platformSkuIdAndSourceSkuInfoMap.get(platformSkuId);
        boolean isSourceItemNoSkuFlag = (matchSourceSkuInfo.getSourceItemId().equals(matchSourceSkuInfo.getSourceSkuId()));
        if (manualSourceSkuInfo != null && ((manualSourceSkuInfo.getSourceSkuId().equals(matchSourceSkuInfo.getSourceSkuId())) || (isSourceItemNoSkuFlag && (matchSourceSkuInfo.getSourceItemId().equals(manualSourceSkuInfo.getSourceItemId()))))) {
            purchaseQuantity = (manualSourceSkuInfo.getSourceNum() != null && manualSourceSkuInfo.getSourceNum() != 0) ? (platformItemTotal * manualSourceSkuInfo.getSourceNum()) : platformItemTotal;
        }

        return purchaseQuantity;
    }

}
