package com.diaoyun.zion.chinafrica.bis.impl;

import com.diaoyun.zion.chinafrica.bis.IItemSpider;
import com.diaoyun.zion.chinafrica.constant.KeyConstant;
import com.diaoyun.zion.chinafrica.enums.PlatformEnum;
import com.diaoyun.zion.chinafrica.vo.*;
import com.diaoyun.zion.master.util.HttpClientUtil;
import com.diaoyun.zion.master.util.JsoupUtil;
import com.diaoyun.zion.master.util.TranslateHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

import static com.diaoyun.zion.master.util.SpiderUtil.exchangeRate;

/**
 * nike数据爬虫
 *
 * @author G
 */
@Component("nikeItemSpider")
public class NikeItemSpider implements IItemSpider {
    private static Logger logger = LoggerFactory.getLogger(NikeItemSpider.class);

    @Override
    public JSONObject captureItem(String targetUrl) throws URISyntaxException, IOException, InterruptedException, ExecutionException, TimeoutException {
        JSONObject resultObj;
        //获取url中的网页内容 >
        String content = HttpClientUtil.getContentByUrl(targetUrl, PlatformEnum.NIKE.getValue());
        //获取商品相关信息，详情放在<script> 标签的 window.INITIAL_REDUX_STATE 变量中
        resultObj = JsoupUtil.getItemDetailByName(content, "window.INITIAL_REDUX_STATE");
        //格式化为封装数据
        ProductResponse productResponse = formatNikeProductResponse(resultObj);
        resultObj = JSONObject.fromObject(productResponse);
        //翻译
        TranslateHelper.translateProductResponse(resultObj);
        return resultObj;
    }

    /**
     * 格式化 nike 返回数据
     *
     * @param dataMap
     * @return
     */
    private 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;
    }
}
