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.*;

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();
    }

    /**
     * 格式化 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;
    }

    /**
     * 格式化 H&M 返回数据
     * @see com.diaoyun.zion.chinafrica.bis.impl.HmSpider
     * @param dataMap 主要的 json 数据
     * @return 格式化后的数据
     */
    public static ProductResponse formatHMProductResponse(JSONObject dataMap) {
        // 声明封装类
        ProductResponse productResponse = new ProductResponse();
        // 属性：Zara 的商品属性有颜色、尺码
        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();

        // 按照一下顺序进行 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;
    }
}

