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.nodes.Element;
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;

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

/**
 * Apple(苹果) 数据爬虫
 *
 * @author 爱酱油不爱醋
 */
@Component("appleSpider")
public class AppleSpider implements IItemSpider {
    private static Logger logger = LoggerFactory.getLogger(PullandbearSpider.class);

    /**
     * Apple(苹果) 数据爬虫
     * @param targetUrl 接收的商品详情路径
     * @return 格式化与翻译后的 Json 数据
     */
    @Override
    public JSONObject captureItem(String targetUrl) throws URISyntaxException, IOException, ExecutionException, InterruptedException, TimeoutException {
        String content = HttpClientUtil.getContentByUrl(targetUrl, PlatformEnum.APPLE.getValue());
        ProductResponse productResponse = formatProductResponse(content);
        JSONObject resultObj = JSONObject.fromObject(productResponse);
        TranslateHelper.translateProductResponse(resultObj);
        return resultObj;
    }

    /**
     * 格式化返回数据
     *
     * @param content 主要的页面数据
     * @return 格式化后的数据
     */
    private ProductResponse formatProductResponse(String content) throws IOException, URISyntaxException {
        // 声明封装类
        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> propSet = new HashSet<>(16);
        Set<ProductProp> sizePropSet = new HashSet<>(16);
        productResponse.setStockFlag(true);
        // 商品的基本属性
        ItemInfo itemInfo = new ItemInfo();

        // 解析为 Document 对象
        Document document = Jsoup.parse(content);

        String pTitle = document.select("meta[property=og:title]").attr("content");
        String imgUrl = document.select("meta[property=og:image]").attr("content");
        String shopUrl = "https://www.apple.com/";

        //////////////////////////////////// 获取商品基本信息 ////////////////////////////
        itemInfo.setShopName("Apple");
        itemInfo.setShopUrl(shopUrl);

        itemInfo.setTitle(pTitle);
        itemInfo.setPic(imgUrl);
        //////////////////////////////////// 获取商品基本信息End /////////////////////////

        // 获取该商品下的所有款式的链接
        Elements pUrlEle = document.select("div[class=selection-buttons]").select("div[class=item equalize-capacity-button-height ]");
        for (Element element : pUrlEle) {
            String targetUrl = element.select("a").attr("href");
            if (!targetUrl.contains("https://www.apple.com")) {
                targetUrl = shopUrl + targetUrl;
            }

            System.err.println(targetUrl);
            String[] spilt = targetUrl.split("/");
            String pId = spilt[spilt.length - 2] + "/" + spilt[spilt.length - 1];
            content = HttpClientUtil.getContentByUrl(targetUrl, PlatformEnum.APPLE.getValue());
            document = Jsoup.parse(content);

            String skuStr = ";" + pId + ";" + pId + ";";

            //////////////////////////////////// 获取款式 ////////////////////////////////////////////

            pTitle = document.select("meta[property=og:title]").attr("content");
            imgUrl = document.select("meta[property=og:image]").attr("content");

            ProductProp productPropModel = new ProductProp();
            productPropModel.setPropId(pId);
            productPropModel.setPropName(pTitle);
            productPropModel.setImage(imgUrl);
            propSet.add(productPropModel);
            if (productPropSet.get("款式") == null) {
                productPropSet.put("款式", propSet);
            } else {
                Set<ProductProp> oldPropSet = productPropSet.get("款式");
                propSet.addAll(oldPropSet);
                productPropSet.put("款式", propSet);
            }
            //////////////////////////////////// 获取款式 END ////////////////////////////////////////////

            //////////////////////////////////// 获取库存 ////////////////////////////////////////////
            // 设置：商品包含库存信息
            if (productSkuStockList == null) {
                productSkuStockList = new ArrayList<>();
            }

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

            //////////////////////////////////// 获取原始价 //////////////////////////////////
            // 获取商品的原始价
            String fullPrice = document.select("span[class=as-price-currentprice]").text();
            fullPrice = SpiderUtil.retainNumber(fullPrice);
            fullPrice = exchangeRate(fullPrice);

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

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

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

}
