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

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

/**
 * H&M 数据爬虫
 *
 * @author 爱酱油不爱醋
 */
@Component("hmSpider")
public class HmSpider implements IItemSpider {
    private static Logger logger = LoggerFactory.getLogger(UniqloSpider.class);

    /**
     * H&M 数据格式化
     * @param targetUrl
     * @return
     */
    @Override
    public JSONObject captureItem(String targetUrl) throws URISyntaxException, IOException, ExecutionException, InterruptedException, TimeoutException {
        String[] spilt = targetUrl.split("productpage.");
        targetUrl = "https://www2.hm.com/zh_cn/productpage." + spilt[1];
        String content = HttpClientUtil.getContentByUrl(targetUrl, PlatformEnum.HM.getValue());
        ProductResponse productResponse = formatProductResponse(content);
        JSONObject resultObj = JSONObject.fromObject(productResponse);
        TranslateHelper.translateProductResponse(resultObj);
        return resultObj;
    }

    /**
     * 正则匹配是否为商品详情页的链接
     * TODO 正则编写
     * @param targetUrl url路径
     * @return 匹配失败则返回错误信息
     */
    private boolean urlPattern(String targetUrl) {
        String regex = "";
        return Pattern.matches(regex, targetUrl);
    }

    /**
     * 格式化返回数据
     *
     * @param content 页面数据
     * @return 格式化后的数据
     */
    public static ProductResponse formatProductResponse(String content) {
        // 获取主要数据并将转换 Json 数据及 Document 对象
        String detailStr = JsoupUtil.getScriptContent(content, "productArticleDetails");
        int firstBrackets = detailStr.indexOf("{");
        int lastbrackets = detailStr.lastIndexOf("}");
        String resultStr = detailStr.substring(firstBrackets, lastbrackets + 1);
        resultStr = resultStr.replaceAll("\'", "\"")
                .replaceAll("\"image\": isDesktop [?] ", "")
                .replaceAll("\"fullscreen\": isDesktop [?] ", "")
                .replaceAll("\"zoom\": isDesktop [?] ", "");
        JSONObject dataMap = JSONObject.fromObject(resultStr);
        Document document = Jsoup.parse(content);

        // 声明封装类
        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();

        //////////////////////////////////// 获取商品基本信息 ////////////////////////////
        itemInfo.setShopName("H&M");
        itemInfo.setShopUrl("https://www2.hm.com/");
        itemInfo.setItemId(document.select("div[class=article-code]").select("li").text());
        itemInfo.setTitle(document.select("h1[class=primary product-item-headline]").text());
        //////////////////////////////////// 获取商品基本信息(图片下取)End /////////////////////////

        // 获取原始价
        String fullPrice = document.select("div[class=primary-row product-item-price]").text();
        fullPrice = SpiderUtil.retainNumber(fullPrice);
        // TODO 转换汇率，目前商品单位是人民币
        fullPrice = exchangeRate(fullPrice);
        BigDecimal priceOld = new BigDecimal(fullPrice);
        BigDecimal div = new BigDecimal("100");
        fullPrice = priceOld.divide(div, 2, BigDecimal.ROUND_DOWN).toString();

        //////////////////////////////////// 获取商品颜色属性 ////////////////////////////////////////////
        // 取页面的数据
        Elements colorEle = document.select("div[class=mini-slider]").select("ul[class=inputlist clearfix]").select("li");
        for (Element element : colorEle) {

            String colorNo = element.select("a").attr("data-articlecode");
            String color = element.select("a").attr("data-color");
            String imgUrl = "http:" + element.select("noscript").attr("data-src");

            itemInfo.setPic(imgUrl);

            ProductProp productPropColor = new ProductProp();
            productPropColor.setPropId(colorNo);
            productPropColor.setPropName(color);
            productPropColor.setImage(imgUrl);
            propSet.add(productPropColor);
            if (productPropSet.get("颜色") == null) {
                productPropSet.put("颜色", propSet);
            } else {
                Set<ProductProp> oldPropSet = productPropSet.get("颜色");
                propSet.addAll(oldPropSet);
                productPropSet.put("颜色", propSet);
            }
            //////////////////////////////////// 获取商品颜色属性 END ////////////////////////////////////////////

            ///////////////////////// 获取商品尺码属性 ///////////////////////////////////////////////////////////
            JSONArray sizeArr = dataMap.getJSONObject(colorNo).getJSONArray("sizes");
            for (int i = 0; i < sizeArr.size(); i++) {
                JSONObject sizeObj = sizeArr.getJSONObject(i);

                String sizeNo = sizeObj.getString("sizeCode");
                String size = sizeObj.getString("name");

                ProductProp productPropSize = new ProductProp();
                productPropSize.setPropId(sizeNo);
                productPropSize.setPropName(size);
                sizePropSet.add(productPropSize);
                if (productPropSet.get("尺码") == null) {
                    productPropSet.put("尺码", sizePropSet);
                } else {
                    Set<ProductProp> oldPropSet = productPropSet.get("尺码");
                    sizePropSet.addAll(oldPropSet);
                    productPropSet.put("尺码", sizePropSet);
                }
                ///////////////////////// 获取商品尺码属性END //////////////////////////////////////////////////////

                // 设置 skuStr
                String skuStr = ";" + colorNo + ";" + sizeNo + ";";

                //////////////////////////////////// 获取库存 ////////////////////////////////////////////
                if (productSkuStockList == null) {
                    productSkuStockList = new ArrayList<>();
                }
                ProductSkuStock productSkuStock = new ProductSkuStock();
                productSkuStock.setSkuStr(skuStr);
                productSkuStock.setSellableQuantity(999);
                productSkuStockList.add(productSkuStock);
                dynStock.setProductSkuStockList(productSkuStockList);
                //////////////////////////////////// 获取库存 END/////////////////////////////////////////

                //////////////////////////////////// 获取原始价 //////////////////////////////////
                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("H&M");
        productResponse.setPromotionList(promotionList);
        productResponse.setOriginalPriceList(originalPriceList);
        productResponse.setItemInfo(itemInfo);
        productResponse.setDynStock(dynStock);
        return productResponse;
    }

}
