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.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

/**
 * afri-eshop 数据爬虫
 *
 * @author G
 */
@Component("africaShopItemSpider")
public class AfricaShopItemSpider implements IItemSpider {
    private static Logger logger = LoggerFactory.getLogger(AfricaShopItemSpider.class);

    @Override
    public JSONObject captureItem(String targetUrl) throws URISyntaxException, IOException, InterruptedException, ExecutionException, TimeoutException {
        JSONObject resultObj;
        //获取url中的网页内容 >
        String content = HttpClientUtil.getContentByUrl(targetUrl, PlatformEnum.AfriEshop.getValue());
        //获取商品相关信息，详情放在<script> 标签里  <script type="application/json" id="ProductJson-product-template">
        resultObj = JsoupUtil.getScriptContentById(content, "ProductJson-product-template");
        //格式化为封装数据
        ProductResponse productResponse = formatProductResponse(resultObj);
        resultObj = JSONObject.fromObject(productResponse);
        //翻译
        TranslateHelper.translateProductResponse(resultObj);
        return resultObj;
    }

    /**
     * 格式化 afric-eshop 返回数据
     *
     * @param resultObj
     * @return
     */
    private ProductResponse formatProductResponse(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");

            String skuStr = ";";
            for (int m = 0; m < itemOptionsArray.size(); m++) {
                skuStr = skuStr + KeyConstant.CUSTOMIZE_ID + itemOptionsArray.getString(m) + ";";
            }
            //没有属性的时候，会返回 Default Title
            if ("Default Title".equalsIgnoreCase(itemOptionsArray.getString(0))) {

            }
            ///////////////////原始价////////////////////////////////////
            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;
    }

}
