package com.diaoyun.zion.master.util.spider;

import com.diaoyun.zion.chinafrica.constant.KeyConstant;
import com.diaoyun.zion.chinafrica.entity.TbCfFeeEntity;
import com.diaoyun.zion.chinafrica.enums.PlatformEnum;
import com.diaoyun.zion.chinafrica.service.TbCfFeeService;
import com.diaoyun.zion.chinafrica.vo.*;
import com.diaoyun.zion.master.util.SpringContextUtil;
import com.stripe.model.Product;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;

public class SpiderUtil {

    private static BigDecimal rate;


    static {
        TbCfFeeService tbCfFeeService = (TbCfFeeService) SpringContextUtil.getBean("tbCfFeeService");
        rate = tbCfFeeService.getRateFee().getFeeRate();
    }

    /**
     * 转换汇率
     *
     * @param fullPrice
     * @return
     */
    protected static String exchangeRate(String fullPrice) {
        /* 获取人民币汇率 1美元换取人民币
         * TODO 同步汇率问题
         * 暂时从后台获取人工设置的汇率
         */
        return new BigDecimal(fullPrice).divide(rate, 2, BigDecimal.ROUND_UP).toString();
    }

    /**
     * 去除除了数字之外的所有字符
     *
     * @param str 字符串
     * @return 只有数字的字符串
     */
    public static String retainNumber(String str) {
        str = Pattern.compile("[^0-9]").matcher(str).replaceAll("").trim();
        return str;
    }

    /**
     * 格式化 gap 返回数据
     *
     * @param dataMap
     * @return
     */
    public static ProductResponse formatGapProductResponse(JSONObject dataMap) {
        ProductResponse productResponse = new ProductResponse();
        //原始价
        List<OriginalPrice> originalPriceList = new ArrayList<>();
        //促销价格
        List<ProductPromotion> promotionList = new ArrayList<>();
        Map<String, Set<ProductProp>> productPropSet = new HashMap<>();
        JSONArray productList = dataMap.getJSONArray("productList");
        //商品信息
        ItemInfo itemInfo = new ItemInfo();
        for (int index = 0; index < productList.size(); index++) {
            JSONObject propObj = productList.getJSONObject(index);
            //////////////////获取价格//////////////////
            JSONArray skuList = propObj.getJSONArray("skuList");
            for (int i = 0; i < skuList.size(); i++) {
                JSONObject skuValue = skuList.getJSONObject(i);
                JSONArray attrSaleList = skuValue.getJSONArray("attrSaleList");
                String skuStr = ";";
                for (int m = 0; m < attrSaleList.size(); m++) {
                    JSONObject attrSale = attrSaleList.getJSONObject(m);
                    JSONArray attributeValueList = attrSale.getJSONArray("attributeValueList");
                    skuStr = skuStr + attributeValueList.getJSONObject(0).getString("code") + ";";
                }
                //原始价格
                OriginalPrice originalPrice = new OriginalPrice();
                originalPrice.setSkuStr(skuStr);

                String listPrice = skuValue.getString("listPrice");
                //转换汇率
                listPrice = exchangeRate(listPrice);
                originalPrice.setPrice(listPrice);
                originalPriceList.add(originalPrice);
                //促销价格
                if (StringUtils.isNotBlank(skuValue.getString("salePrice"))) {
                    String salePrice = skuValue.getString("salePrice");
                    //转换汇率
                    salePrice = exchangeRate(salePrice);
                    productResponse.setPromotionFlag(true);
                    ProductPromotion productPromotion = new ProductPromotion();
                    productPromotion.setSkuStr(skuStr);
                    productPromotion.setPrice(salePrice);
                    promotionList.add(productPromotion);
                }

            }
            //////////////////获取价格 END//////////////////
            //////////////////获取商品属性//////////////////
            JSONArray attrSaleList = propObj.getJSONArray("attrSaleList");
            for (int i = 0; i < attrSaleList.size(); i++) {
                JSONArray attributeValueList = attrSaleList.getJSONObject(i).getJSONArray("attributeValueList");
                //商品属性
                Set<ProductProp> propSet = new HashSet<>();
                for (int j = 0; j < attributeValueList.size(); j++) {
                    ProductProp productProp = new ProductProp();
                    //获取图片，拿第一张
                    if (attributeValueList.getJSONObject(j).get("itemAttributeValueImageList") != null && !"null".equalsIgnoreCase(attributeValueList.getJSONObject(j).getString("itemAttributeValueImageList"))) {
                        JSONArray itemAttributeValueImageList = attributeValueList.getJSONObject(j).getJSONArray("itemAttributeValueImageList");
                        productProp.setImage(itemAttributeValueImageList.getJSONObject(0).getString("picUrl"));
                    }
                    productProp.setPropName(attributeValueList.getJSONObject(j).getString("attributeValueName"));
                    productProp.setPropId(attributeValueList.getJSONObject(j).getString("code"));
                    propSet.add(productProp);
                }
                String attributeFrontName = attrSaleList.getJSONObject(i).getString("attributeFrontName");
                if (productPropSet.get(attributeFrontName) == null) {
                    productPropSet.put(attributeFrontName, propSet);
                } else {
                    Set<ProductProp> oldPropSet = productPropSet.get(attributeFrontName);
                    propSet.addAll(oldPropSet);
                    productPropSet.put(attributeFrontName, propSet);
                }

            }

            //////////////////获取商品属性 END//////////////////

            itemInfo.setItemId(propObj.getString("style"));
            if (propObj.get("itemImageList") != null && !"null".equalsIgnoreCase(propObj.getString("itemImageList"))) {

                JSONArray itemImageList = propObj.getJSONArray("itemImageList");
                if (!itemImageList.isEmpty()) {
                    String pic = itemImageList.getJSONObject(0).getString("picUrl");
                    //取第一张当作主图
                    itemInfo.setPic(pic);
                }
            }
            itemInfo.setShopName(PlatformEnum.GAP.getLabel());
            itemInfo.setShopUrl("https://www.gap.cn/");
            itemInfo.setTitle(propObj.getString("title"));

        }

        String minPrice = dataMap.getString("minPrice");
        String maxPrice = dataMap.getString("maxPrice");
        //转换汇率
        minPrice = exchangeRate(minPrice);
        maxPrice = exchangeRate(maxPrice);

        //一口价
        productResponse.setPrice(minPrice + "-" + maxPrice);
        //一口价
        productResponse.setSalePrice(minPrice + "-" + maxPrice);
        //没有库存信息 需要另外获取
        productResponse.setStockFlag(false);
        //有商品属性
        productResponse.setPropFlag(true);
        productResponse.setOriginalPriceList(originalPriceList);
        productResponse.setPromotionList(promotionList);
        productResponse.setItemInfo(itemInfo);
        productResponse.setPlatform(PlatformEnum.GAP.getValue());
        productResponse.setProductPropSet(productPropSet);
        return productResponse;
    }

    /**
     * 格式化 nike 返回数据
     *
     * @param dataMap
     * @return
     */
    public static ProductResponse formatNikeProductResponse(JSONObject dataMap) {

        ProductResponse productResponse = new ProductResponse();
        //nike 基本是 颜色、尺码属性
        Map<String, Set<ProductProp>> productPropSet = new HashMap<>(16);
        //原始价
        List<OriginalPrice> originalPriceList = new ArrayList<>();
        //促销价格
        List<ProductPromotion> promotionList = new ArrayList<>();
        //库存
        DynStock dynStock = new DynStock();
        //其实数据没有包含确切的库存数，这里默认给足量的库存
        dynStock.setSellableQuantity(9999);
        //商品基本信息
        ItemInfo itemInfo = new ItemInfo();
        JSONObject threadObj = dataMap.getJSONObject("Threads");
        JSONObject productsObj = threadObj.getJSONObject("products");
        Set es = productsObj.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry<String, JSONObject> entry = (Map.Entry) it.next();
            String skuStr = ";";
            String modelCode = entry.getKey();
            skuStr = skuStr + modelCode + ";";
            JSONObject itemDetail = entry.getValue();
            ////////////////////////////////////获取价格和商品属性////////////////////////////////////////////
            String fullPrice = itemDetail.getString("fullPrice");
            //转换汇率
            fullPrice = exchangeRate(fullPrice);
            String currentPrice = itemDetail.getString("currentPrice");
            //转换汇率
            currentPrice = exchangeRate(currentPrice);
            productResponse.setPrice(fullPrice);
            JSONArray skusArr = itemDetail.getJSONArray("skus");
            //获取商品尺码属性，同时记录下skuid和尺码关系
            Map<String, String> sizeSkuIdMapping = new HashMap<>(16);
            for (int i = 0; i < skusArr.size(); i++) {
                String skuId = skusArr.getJSONObject(i).getString("skuId");
                /////////////////////////获取商品尺码属性////////////////////
                //商品属性
                Set<ProductProp> sizePropSet = new HashSet<>();
                ProductProp productProp = new ProductProp();
                String localizedSize = skusArr.getJSONObject(i).getString("localizedSize");
                String localizedSizePrefix = skusArr.getJSONObject(i).getString("localizedSizePrefix");
                //因为尺码一样的时候skuid却不一样，这里只能赋予一个propid，否则后面去重不了
                String customizeId = KeyConstant.CUSTOMIZE_ID + localizedSize + localizedSizePrefix;
                sizeSkuIdMapping.put(skuId, customizeId);
                productProp.setPropId(customizeId);
                productProp.setPropName(localizedSizePrefix + " " + localizedSize);
                sizePropSet.add(productProp);
                if (productPropSet.get("尺码") == null) {
                    productPropSet.put("尺码", sizePropSet);
                } else {
                    Set<ProductProp> oldPropSet = productPropSet.get("尺码");
                    sizePropSet.addAll(oldPropSet);
                    productPropSet.put("尺码", sizePropSet);
                }
                /////////////////////////获取商品尺码属性 END////////////////////

            }

            ////////////////////////////////////获取价格//////////////////////////////////
            for (int i = 0; i < skusArr.size(); i++) {
                String skuId = skusArr.getJSONObject(i).getString("skuId");
                String customizeId = sizeSkuIdMapping.get(skuId);
                OriginalPrice originalPrice = new OriginalPrice();
                originalPrice.setSkuStr(skuStr + customizeId + ";");
                originalPrice.setPrice(fullPrice);
                originalPriceList.add(originalPrice);
                if (itemDetail.getBoolean("discounted")) {
                    productResponse.setPromotionFlag(true);
                    productResponse.setSalePrice(currentPrice);
                    ProductPromotion productPromotion = new ProductPromotion();
                    productPromotion.setSkuStr(skuStr + customizeId + ";");
                    productPromotion.setPrice(fullPrice);
                    promotionList.add(productPromotion);
                }
            }
            ////////////////////////////////////获取价格 END//////////////////////////////////

            /////////////////////////////////////获取价格和商品属性 END////////////////////////////////////////////
            ////////////////////////////////////获取库存 ////////////////////////////////////////////
            productResponse.setStockFlag(true);
            List<ProductSkuStock> productSkuStockList = dynStock.getProductSkuStockList();
            if (productSkuStockList == null) {
                productSkuStockList = new ArrayList<>();
            }
            JSONArray availableSkusArr = itemDetail.getJSONArray("availableSkus");
            for (int i = 0; i < availableSkusArr.size(); i++) {
                String skuId = availableSkusArr.getJSONObject(i).getString("skuId");
                String customizeId = sizeSkuIdMapping.get(skuId);
                ProductSkuStock productSkuStock = new ProductSkuStock();
                productSkuStock.setSellableQuantity(999);
                productSkuStock.setSkuStr(skuStr + customizeId + ";");
                productSkuStockList.add(productSkuStock);
            }
            dynStock.setProductSkuStockList(productSkuStockList);

            ////////////////////////////////////获取库存 END////////////////////////////////////////////
            ////////////////////////////////////获取商品颜色属性////////////////////////////////////////////
            //商品属性
            Set<ProductProp> propSet = new HashSet<>();
            ProductProp productProp = new ProductProp();
            String colorDescription = itemDetail.getString("colorDescription");
            String firstImageUrl = itemDetail.getString("firstImageUrl");
            productProp.setPropId(modelCode);
            productProp.setPropName(colorDescription);
            productProp.setImage(firstImageUrl);
            propSet.add(productProp);
            if (productPropSet.get("颜色") == null) {
                productPropSet.put("颜色", propSet);
            } else {
                Set<ProductProp> oldPropSet = productPropSet.get("颜色");
                propSet.addAll(oldPropSet);
                productPropSet.put("颜色", propSet);
            }
            ////////////////////////////////////获取商品属性 END////////////////////////////////////////////
        }
        JSONObject globalObj = dataMap.getJSONObject("global");
        JSONObject metaTagsObj = globalObj.getJSONObject("metaTags");
        JSONArray metaArr = metaTagsObj.getJSONArray("meta");
        for (int i = 0; i < metaArr.size(); i++) {
            if (metaArr.getJSONObject(i).get("property") != null) {
                String propertyValue = metaArr.getJSONObject(i).getString("property");
                if ("og:title".equalsIgnoreCase(propertyValue)) {
                    itemInfo.setTitle(metaArr.getJSONObject(i).getString("content"));
                }
                if ("og:image".equalsIgnoreCase(propertyValue)) {
                    itemInfo.setPic(metaArr.getJSONObject(i).getString("content"));
                }
            }
        }
        itemInfo.setShopUrl("https://www.nike.com/cn/");
        itemInfo.setShopName(PlatformEnum.NIKE.getLabel());
        productResponse.setPropFlag(true);
        productResponse.setProductPropSet(productPropSet);
        productResponse.setPlatform(PlatformEnum.NIKE.getValue());
        productResponse.setPromotionList(promotionList);
        productResponse.setOriginalPriceList(originalPriceList);
        productResponse.setItemInfo(itemInfo);
        productResponse.setDynStock(dynStock);
        return productResponse;
    }

    /**
     * 格式化 afric-eshop 返回数据
     *
     * @param resultObj
     * @return
     */
    public static ProductResponse formatAfricaShopProductResponse(JSONObject resultObj) {
        ProductResponse productResponse = new ProductResponse();
        //原始价
        List<OriginalPrice> originalPriceList = new ArrayList<>();
        //促销价格
        List<ProductPromotion> promotionList = new ArrayList<>();
        //库存
        DynStock dynStock = new DynStock();
        //其实数据没有包含确切的库存数，这里默认给足量的库存
        dynStock.setSellableQuantity(9999);
        //nike 基本是 颜色、尺码属性
        Map<String, Set<ProductProp>> productPropSet = new HashMap<>();

        //商品基本信息
        ItemInfo itemInfo = new ItemInfo();
        JSONArray variantsArray = resultObj.getJSONArray("variants");
        //属性
        JSONArray optionsArray = resultObj.getJSONArray("options");

        for (int i = 0; i < variantsArray.size(); i++) {
            //属性
            JSONArray itemOptionsArray = variantsArray.getJSONObject(i).getJSONArray("options");
            //没有属性的时候，会返回 Default Title
            if ("Default Title".equalsIgnoreCase(itemOptionsArray.getString(0))) {
                break;
            }
            String skuStr = ";";
            for (int m = 0; m < itemOptionsArray.size(); m++) {
                skuStr = skuStr + KeyConstant.CUSTOMIZE_ID + itemOptionsArray.getString(m) + ";";
            }
            ///////////////////原始价////////////////////////////////////
            OriginalPrice originalPrice = new OriginalPrice();
            String price = variantsArray.getJSONObject(i).getString("price");
            BigDecimal priceOld = new BigDecimal(price);
            BigDecimal div = new BigDecimal("100");
            BigDecimal priceNew = priceOld.divide(div, 2, BigDecimal.ROUND_DOWN);
            originalPrice.setPrice(priceNew.toString());
            originalPrice.setSkuStr(skuStr);
            originalPriceList.add(originalPrice);
            ///////////////////原始价 END////////////////////////////////
            ////////////////////////////////////获取库存 ////////////////////////////////////////////
            productResponse.setStockFlag(true);
            List<ProductSkuStock> productSkuStockList = dynStock.getProductSkuStockList();
            if (productSkuStockList == null) {
                productSkuStockList = new ArrayList<>();
            }

            ProductSkuStock productSkuStock = new ProductSkuStock();
            productSkuStock.setSellableQuantity(999);
            productSkuStock.setSkuStr(skuStr);
            productSkuStockList.add(productSkuStock);
            dynStock.setProductSkuStockList(productSkuStockList);
            ////////////////////////////////////获取库存 END////////////////////////////////////////////
            //获取所有的属性
            for (int j = 0; j < optionsArray.size(); j++) {
                ////////////////////////////////////获取商品属性////////////////////////////////////////////
                //商品属性
                Set<ProductProp> propSet = new HashSet<>();
                ProductProp productProp = new ProductProp();
                productProp.setPropId(KeyConstant.CUSTOMIZE_ID + itemOptionsArray.getString(j));
                productProp.setPropName(itemOptionsArray.getString(j));
                propSet.add(productProp);
                if (productPropSet.get(optionsArray.getString(j)) == null) {
                    productPropSet.put(optionsArray.getString(j), propSet);
                } else {
                    Set<ProductProp> oldPropSet = productPropSet.get(optionsArray.getString(j));
                    propSet.addAll(oldPropSet);
                    productPropSet.put(optionsArray.getString(j), propSet);
                }
                ////////////////////////////////////获取属性 END////////////////////////////////////////////
            }

        }
        itemInfo.setItemId(resultObj.getString("id"));
        //取第一张
        itemInfo.setPic(resultObj.getString("featured_image"));
        itemInfo.setShopName(PlatformEnum.AfriEshop.getValue());
        itemInfo.setShopUrl("https://www.afri-eshop.com/");
        itemInfo.setTitle(resultObj.getString("title"));
        productResponse.setPropFlag(true);
        productResponse.setProductPropSet(productPropSet);
        productResponse.setPlatform(PlatformEnum.AfriEshop.getValue());
        productResponse.setPromotionList(promotionList);
        productResponse.setOriginalPriceList(originalPriceList);
        productResponse.setItemInfo(itemInfo);
        productResponse.setDynStock(dynStock);
        String price = resultObj.getString("price");
        BigDecimal priceOld = new BigDecimal(price);
        BigDecimal div = new BigDecimal("100");
        BigDecimal priceNew = priceOld.divide(div, 2, BigDecimal.ROUND_DOWN);
        productResponse.setPrice(priceNew.toString());
        return productResponse;
    }

    /**
     * 格式化 PullAndBear 返回数据
     *
     * @param dataMap 主要的 json 数据
     * @param pId     商品链接的 id
     * @return 格式化后的数据
     * @see com.diaoyun.zion.chinafrica.bis.impl.PullandbearSpider
     */
    public static ProductResponse formatPullAndBearProductResponse(JSONObject dataMap, String pId) {
        // 声明封装类
        ProductResponse productResponse = new ProductResponse();
        // 属性：的商品属性有颜色、尺码
        Map<String, Set<ProductProp>> productPropSet = new HashMap<>(16);
        // 原始价
        List<OriginalPrice> originalPriceList = new ArrayList<>();
        // 促销价格
        List<ProductPromotion> promotionList = new ArrayList<>();
        // 库存
        DynStock dynStock = new DynStock();
        // 其实数据没有包含确切的库存数，这里默认给足量的库存
        dynStock.setSellableQuantity(9999);
        // 商品基本信息
        ItemInfo itemInfo = new ItemInfo();

        // 取 bundleProductSummaries 的节点对象
        JSONObject bundleProductSummariesObj = dataMap.getJSONArray("bundleProductSummaries").getJSONObject(0);

        //////////////////////////////////// 获取商品基本信息 ////////////////////////////////////////////
        itemInfo.setShopName("PullAndBear");
        itemInfo.setShopUrl("https://www.pullandbear.cn/");
        itemInfo.setItemId(pId);
        itemInfo.setTitle(bundleProductSummariesObj.getString("name"));
        //////////////////////////////////// 获取商品基本信息End(图片下取) ////////////////////////////////////////////

        // 取 colors 数组节点
        JSONArray colorsArr = bundleProductSummariesObj.getJSONObject("detail").getJSONArray("colors");
        Set<ProductProp> propSetColor = new HashSet<>(16);
        Set<ProductProp> sizePropSetSize = new HashSet<>(16);
        List<ProductSkuStock> productSkuStockList = dynStock.getProductSkuStockList();
        productResponse.setStockFlag(true);
        for (int i = 0; i < colorsArr.size(); i++) {
            JSONObject colorsObj = colorsArr.getJSONObject(i);

            //////////////////////////////////// 获取商品颜色与图片属性 ////////////////////////////////////////////
            ProductProp productPropColor = new ProductProp();
            JSONObject imageObj = colorsObj.getJSONObject("image");

            String imageUrl = "https://static.pullandbear.cn/2/photos/"
                    + imageObj.getString("url")
                    + "_2_1_8.jpg?t="
                    + imageObj.getString("timestamp");
            String colorNo = colorsObj.getString("id");
            String color = colorsObj.getString("name");

            productPropColor.setPropId(colorNo);
            productPropColor.setPropName(color);
            productPropColor.setImage(imageUrl);
            if (i == 0) {
                itemInfo.setPic(imageUrl);
            }
            propSetColor.add(productPropColor);

            if (productPropSet.get("颜色") == null) {
                productPropSet.put("颜色", propSetColor);
            } else {
                Set<ProductProp> oldPropSet = productPropSet.get("颜色");
                propSetColor.addAll(oldPropSet);
                productPropSet.put("颜色", propSetColor);
            }
            //////////////////////////////////// 获取商品颜色与图片属性 END ////////////////////////////////////////////

            // 取 siezes 对象数组
            JSONArray sizesArr = colorsObj.getJSONArray("sizes");
            for (int j = 0; j < sizesArr.size(); j++) {
                JSONObject sizesObj = sizesArr.getJSONObject(j);

                ///////////////////////// 获取商品尺码属性 ////////////////////
                ProductProp productPropSize = new ProductProp();

                String sizeNo = sizesObj.getString("sku");
                String size = sizesObj.getString("name");
                productPropSize.setPropName(size);
                productPropSize.setPropId(sizeNo);

                sizePropSetSize.add(productPropSize);

                if (productPropSet.get("尺码") == null) {
                    productPropSet.put("尺码", sizePropSetSize);
                } else {
                    Set<ProductProp> oldPropSet = productPropSet.get("尺码");
                    sizePropSetSize.addAll(oldPropSet);
                    productPropSet.put("尺码", sizePropSetSize);
                }
                ///////////////////////// 获取商品尺码属性 END////////////////////

                // 商品的库存id
                String skuStr = ";" + colorNo + ";" + sizeNo + ";";

                //////////////////////////////////// 获取库存 ////////////////////////////////////////////
                // 设置：商品包含库存信息

                ProductSkuStock productSkuStock = new ProductSkuStock();
                productSkuStock.setSkuStr(skuStr);
                productSkuStock.setSellableQuantity(999);

                if (productSkuStockList == null) {
                    productSkuStockList = new ArrayList<>();
                }
                productSkuStockList.add(productSkuStock);

                //////////////////////////////////// 获取库存 END/////////////////////////////////////////

                //////////////////////////////////// 获取原始价 //////////////////////////////////
                OriginalPrice originalPrice = new OriginalPrice();
                // 获取商品的原始价
                String fullPrice = sizesObj.getString("price");
                BigDecimal priceOld = new BigDecimal(fullPrice);
                BigDecimal div = new BigDecimal("100");
                BigDecimal priceNew = priceOld.divide(div, 2, BigDecimal.ROUND_DOWN);

                // TODO 转换汇率，目前商品单位是人民币
                fullPrice = SpiderUtil.exchangeRate(priceNew.toString());
                originalPrice.setSkuStr(skuStr);
                originalPrice.setPrice(fullPrice);
                originalPriceList.add(originalPrice);

                productResponse.setPrice(fullPrice);
                productResponse.setSalePrice(fullPrice + "-" + fullPrice);


                //////////////////////////////////// 获取原始价 END//////////////////////////////////
            }
            dynStock.setProductSkuStockList(productSkuStockList);
        }

        // 按照一下顺序进行 json 数据的填充
        productResponse.setPropFlag(true);
        productResponse.setProductPropSet(productPropSet);
        productResponse.setPlatform(PlatformEnum.PULLANDBEAR.getValue());
        productResponse.setPromotionList(promotionList);
        productResponse.setOriginalPriceList(originalPriceList);
        productResponse.setItemInfo(itemInfo);
        productResponse.setDynStock(dynStock);
        return productResponse;
    }


}

