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.SpiderUtil;
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;

/**
 * Oysho 数据爬虫
 * TODO 抓取不到商品详情页的链接
 * @author 爱酱油不爱醋
 */
@Component("oyshoSpider")
public class OyshoSpider implements IItemSpider {
    private static Logger logger = LoggerFactory.getLogger(EifiniSpider.class);

    /**
     * Oysho 数据爬虫
     * @param targetUrl 接收的商品详情路径
     * @return 格式化与翻译后的 Json 数据
     */
    @Override
    public JSONObject captureItem(String targetUrl) throws InterruptedException, IOException, ExecutionException, URISyntaxException, TimeoutException {
        String[] spilt = targetUrl.split("origenId=");
        String pId = spilt[1];
        targetUrl = "https://www.oysho.cn/itxrest/2/catalog/store/65009628/60361118/category/0/product/" + pId + "/detail";
        String content = HttpClientUtil.getContentByUrl(targetUrl, PlatformEnum.OYSHO.getValue());
        ProductResponse productResponse = formatProductResponse(content, pId);
        JSONObject resultObj = JSONObject.fromObject(productResponse);
        TranslateHelper.translateProductResponse(resultObj);
        return resultObj;
    }

    /**
     * 格式化返回数据
     *
     * @param content 主要的页面数据
     * @param pId     截取链接中的商品 id
     * @return 格式化后的数据
     */
    private ProductResponse formatProductResponse(String content, 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> propSet = new HashSet<>(16);
        Set<ProductProp> sizePropSet = new HashSet<>(16);
        productResponse.setStockFlag(true);
        // 商品的基本属性
        ItemInfo itemInfo = new ItemInfo();

        JSONObject dataMap = JSONObject.fromObject(content);

        //////////////////////////////////// 获取商品基本信息 ////////////////////////////
        itemInfo.setItemId(pId);
        itemInfo.setShopName("Oysho");
        itemInfo.setShopUrl("https://www.oysho.cn/");
        itemInfo.setTitle(dataMap.getString("name"));
        //////////////////////////////////// 获取商品基本信息End /////////////////////////

        // color 数组节点在接口传递的 json 中会存在不同的情况
        System.err.println(dataMap.getJSONArray("bundleProductSummaries").size());
        JSONArray colorArr;
        if (dataMap.getJSONArray("bundleProductSummaries").size() != 0) {
            colorArr = dataMap.getJSONArray("bundleProductSummaries").getJSONObject(0).getJSONObject("detail").getJSONArray("colors");
        } else {
            colorArr = dataMap.getJSONObject("detail").getJSONArray("colors");
        }

        //////////////////////////////////// 获取商品颜色属性 ////////////////////////////
        for (int i = 0; i < colorArr.size(); i++) {
            JSONObject colorObj = colorArr.getJSONObject(i);

            String colorNo = colorObj.getString("id");
            String color = colorObj.getString("name");

            // 处理图片路径
            JSONObject imageObj = colorObj.getJSONObject("image");
            String imgUrl = "https://static.oysho.cn/6/photos2"
                    + imageObj.getString("url") + ".jpg?t=" + imageObj.getString("timestamp");

            if (i == 0) {
                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 sizesArr = colorObj.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.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///////////////////////////////////////////////////

                //////////////////////////////////// 获取库存与原始价 ////////////////////////////////////////////

                String skuStr = ";" + colorNo + ";" + sizeNo + ";";

                String fullPrice = sizesObj.getString("price");
                BigDecimal priceOld = new BigDecimal(fullPrice);
                BigDecimal div = new BigDecimal("100");
                fullPrice = priceOld.divide(div, 2, BigDecimal.ROUND_DOWN).toString();
                String originalFullPrice = SpiderUtil.exchangeRate(fullPrice);

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

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

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

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

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

}
