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.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
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;

/**
 * UnderArmour 数据爬虫
 *
 * @author 爱酱油不爱醋
 */
@Component("underarmourSpider")
public class UnderArmourSpider implements IItemSpider {
    private static Logger logger = LoggerFactory.getLogger(ZaraSpider.class);

    /**
     * 爬虫数据返回
     * @param targetUrl 接收的商品详情路径
     * @return 格式化与翻译后的 Json 数据
     * @see
     */
    @Override
    public JSONObject captureItem(String targetUrl) throws URISyntaxException, IOException, ExecutionException, InterruptedException, TimeoutException {
        String content = HttpClientUtil.getContentByUrl(targetUrl, PlatformEnum.UNDERARMOUR.getValue());
        ProductResponse productResponse = formatProductResponse(content);
        if (productResponse.getItemInfo() == null) {
            JSONObject notFundData = new JSONObject();
            notFundData.put("message", "找不到此类网址的数据爬虫！");
            return notFundData;
        }
        JSONObject resultObj = JSONObject.fromObject(productResponse);
        TranslateHelper.translateProductResponse(resultObj);
        return resultObj;
    }

    /**
     * 格式化返回数据
     * @param content 主要的页面数据
     * @return 格式化后的数据
     */
    private ProductResponse formatProductResponse(String content) {
        // 声明封装类
        ProductResponse productResponse = new ProductResponse();
        // 解析成 Document 对象
        Document document = Jsoup.parse(content);
        // 如果未获取到该网站的商品id信息，说明还未在商品详情页则返回未找到爬虫信息
        String pId = document.select("div[id=SKU]").text();
        if ("".equals(pId) || pId == null) {
            return 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> propSet = new HashSet<>(16);
        Set<ProductProp> sizePropSet = new HashSet<>(16);
        productResponse.setStockFlag(true);
        // 商品的基本属性
        ItemInfo itemInfo = new ItemInfo();

        //////////////////////////////////// 获取商品基本信息 ////////////////////////////
        itemInfo.setItemId(pId);
        itemInfo.setShopName("UNDERARMOUR");
        itemInfo.setShopUrl("https://www.underarmour.cn");
        String pTitle = document.select("h3[class=commo-name]").text();
        itemInfo.setTitle(pTitle);
        String pPic = document.select("span[class=e-color-show]").text();
        itemInfo.setPic("https://underarmour.scene7.com/is/image/Underarmour/V5-" + pPic + "_FC_Main");
        //////////////////////////////////// 获取商品基本信息End /////////////////////////

        //////////////////////////////////// 获取商品颜色属性 ////////////////////////////
        Elements colorEle = document.select("ul[class=color-choice float-clearfix e-color-choice]").select("li");
        List<String> pColorList = colorEle.eachText();
        List<String> pColorNoList = colorEle.eachAttr("itemcode");
        for (int i = 0; i < pColorList.size(); i++) {
            ProductProp productPropColor = new ProductProp();

            productPropColor.setPropName(pColorList.get(i));
            productPropColor.setPropId(pColorNoList.get(i));
            productPropColor.setImage("https://underarmour.scene7.com/is/image/Underarmour/V5-" + pColorNoList.get(i) + "_FC_Main");
            propSet.add(productPropColor);
            if (productPropSet.get("颜色") == null) {
                productPropSet.put("颜色", propSet);
            } else {
                Set<ProductProp> oldPropSet = productPropSet.get("颜色");
                propSet.addAll(oldPropSet);
                productPropSet.put("颜色", propSet);
            }
        }
        //////////////////////////////////// 获取商品颜色属性 END ////////////////////////////////////////

        ///////////////////////// 获取商品尺码属性 ///////////////////////////////////////////////////////
        Elements sizeEle = document.select("ul[class=size-choice float-clearfix  e-size-choice]").select("li");
        List<String> pSizeList = sizeEle.eachText();
        List<String> pSizeNoList = sizeEle.eachAttr("skuid");
        for (int i = 0; i < pSizeList.size(); i++) {
            ProductProp productPropSize = new ProductProp();
            productPropSize.setPropId(pSizeNoList.get(i));
            productPropSize.setPropName(pSizeList.get(i));
            sizePropSet.add(productPropSize);
            if (productPropSet.get("尺码") == null) {
                productPropSet.put("尺码", sizePropSet);
            } else {
                Set<ProductProp> oldPropSet = productPropSet.get("尺码");
                sizePropSet.addAll(oldPropSet);
                productPropSet.put("尺码", sizePropSet);
            }
        }
        ///////////////////////// 获取商品尺码属性 END///////////////////////////////////////////////////

        //////////////////////////////////// 获取库存与原始价 ////////////////////////////////////////////
        String fullPrice = document.select("p[class=commo-price]").text().replaceAll("￥", "");
        // TODO 转换汇率，目前商品单位是人民币
        String originalFullPrice = SpiderUtil.exchangeRate(fullPrice);
        for (String pColorNo : pColorNoList) {
            for (String pSizeNo : pSizeNoList) {
                // 设置库存id
                String skuStr = ";" + pColorNo + ";" + pSizeNo + ";";

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

                ProductSkuStock productSkuStock = new ProductSkuStock();
                productSkuStock.setSellableQuantity(999);
                productSkuStock.setSkuStr(skuStr);
                productSkuStockList.add(productSkuStock);
                dynStock.setProductSkuStockList(productSkuStockList);

                OriginalPrice originalPrice = new OriginalPrice();
                originalPrice.setPrice(originalFullPrice);
                originalPrice.setSkuStr(skuStr);
                originalPriceList.add(originalPrice);

                productResponse.setPrice(originalFullPrice);
                productResponse.setSalePrice(originalFullPrice + "-" + originalFullPrice);
            }
        }
        //////////////////////////////////// 获取库存与原始价 END///////////////////////////////

        productResponse.setProductPropSet(productPropSet);
        productResponse.setPlatform(PlatformEnum.UNDERARMOUR.getValue());
        productResponse.setPromotionList(promotionList);
        productResponse.setOriginalPriceList(originalPriceList);
        productResponse.setItemInfo(itemInfo);
        productResponse.setDynStock(dynStock);
        return productResponse;
    }

}