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

import com.diaoyun.zion.chinafrica.bis.IItemSpider;
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.TranslateHelper;
import com.diaoyun.zion.master.util.SpiderUtil;
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;
import java.util.regex.Pattern;

/**
 * 西班牙年轻时尚品牌-PullAndBear 数据爬虫
 *
 * @author 爱酱油不爱醋
 */
@Component("pullandbearSpider")
public class PullandbearSpider implements IItemSpider {
    private static Logger logger = LoggerFactory.getLogger(PullandbearSpider.class);

    /**
     * PullAndBear 数据爬虫
     * @param targetUrl 接收的商品详情路径
     * @return 格式化与翻译后的 Json 数据
     */
    @Override
    public JSONObject captureItem(String targetUrl) throws URISyntaxException, IOException, ExecutionException, InterruptedException, TimeoutException {
        JSONObject resultJson = new JSONObject();
        if (!urlPattern(targetUrl)) {
            resultJson.put("message", "不是商品的详情页路径");
            return resultJson;
        }
        String pId = targetUrl.substring(targetUrl.lastIndexOf("p")+1, targetUrl.lastIndexOf(".html"));
        targetUrl = "https://www.pullandbear.cn/itxrest/2/catalog/store/24009528/20309423/category/0/product/" + pId + "/detail?languageId=-7&appId=1";
        String content = HttpClientUtil.getContentByUrl(targetUrl, PlatformEnum.PULLANDBEAR.getValue());
        resultJson = JSONObject.fromObject(content);
        ProductResponse productResponse = formatProductResponse(resultJson, pId);
        resultJson = JSONObject.fromObject(productResponse);
        TranslateHelper.translateProductResponse(resultJson);
        return resultJson;
    }

    /**
     * 正则匹配是否为商品详情页的链接
     * @param targetUrl url路径
     * @return 匹配失败则返回错误信息
     */
    private boolean urlPattern(String targetUrl) {
        String regex = "^.*pullandbear\\.cn/.*-c\\d{5,10}p\\d{9,10}.html\\?cS=\\d*";
        return Pattern.matches(regex, targetUrl);
    }

    /**
     * 格式化 PullAndBear 返回数据
     * @see com.diaoyun.zion.chinafrica.bis.impl.PullandbearSpider
     * @param dataMap 主要的 json 数据
     * @param pId     商品链接的 id
     * @return 格式化后的数据
     */
    private ProductResponse formatProductResponse(JSONObject dataMap, String pId) {
        // 声明封装类
        ProductResponse productResponse = new ProductResponse();
        // 含有商品的属性，设置为true
        productResponse.setPropFlag(true);
        // 库存信息，如果没有可使用的库存信息则默认为999
        DynStock dynStock = new DynStock();
        dynStock.setSellableQuantity(9999);
        List<ProductSkuStock> productSkuStockList = dynStock.getProductSkuStockList();
        // 产品的原始价与优惠价
        List<OriginalPrice> originalPriceList = new ArrayList<>();
        List<ProductPromotion> promotionList = new ArrayList<>();
        // 商品的属性，常用的商品属性为颜色与尺码
        Map<String, Set<ProductProp>> productPropSet = new HashMap<>(16);
        Set<ProductProp> propSetColor = new HashSet<>(16);
        Set<ProductProp> sizePropSetSize = new HashSet<>(16);
        productResponse.setStockFlag(true);
        // 商品的基本属性
        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");
        productResponse.setStockFlag(true);
        for (int i = 0; i < colorsArr.size(); i++) {
            JSONObject colorsObj = colorsArr.getJSONObject(i);

            //////////////////////////////////// 获取商品颜色与图片属性 ////////////////////////////////////////////
            JSONObject imageObj = colorsObj.getJSONObject("image");
            String colorNo = colorsObj.getString("id");
            String color = colorsObj.getString("name");
            String imageUrl = "https://static.pullandbear.cn/2/photos/"
                    + imageObj.getString("url")
                    + "_2_1_8.jpg?t="
                    + imageObj.getString("timestamp");

            if (i == 0) {
                itemInfo.setPic(imageUrl);
            }

            ProductProp productPropColor = new ProductProp();
            productPropColor.setPropId(colorNo);
            productPropColor.setPropName(color);
            productPropColor.setImage(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);

                ///////////////////////// 获取商品尺码属性 ////////////////////
                String sizeNo = sizesObj.getString("sku");
                String size = sizesObj.getString("name");

                ProductProp productPropSize = new ProductProp();
                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 + ";";

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

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

                ProductSkuStock productSkuStock = new ProductSkuStock();
                productSkuStock.setSkuStr(skuStr);
                productSkuStock.setSellableQuantity(999);
                productSkuStockList.add(productSkuStock);
                //////////////////////////////////// 获取库存 END/////////////////////////////////////////

                //////////////////////////////////// 获取原始价 //////////////////////////////////
                // 获取商品的原始价
                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 originalPrice = new OriginalPrice();
                originalPrice.setSkuStr(skuStr);
                originalPrice.setPrice(fullPrice);
                originalPriceList.add(originalPrice);
                dynStock.setProductSkuStockList(productSkuStockList);

                productResponse.setPrice(fullPrice);
                productResponse.setSalePrice(fullPrice + "-" + fullPrice);
                //////////////////////////////////// 获取原始价 END//////////////////////////////////
            }
        }

        productResponse.setPropFlag(true);
        productResponse.setProductPropSet(productPropSet);
        productResponse.setPlatform("PullAndBear");
        productResponse.setPromotionList(promotionList);
        productResponse.setOriginalPriceList(originalPriceList);
        productResponse.setItemInfo(itemInfo);
        productResponse.setDynStock(dynStock);
        return productResponse;
    }

}


