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 net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

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

/**
 * Gap数据爬虫
 *
 * @author G
 */
@Component("gapItemSpider")
public class GapItemSpider implements IItemSpider {
    private static Logger logger = LoggerFactory.getLogger(GapItemSpider.class);

    /**
     * GAP 商品详情页链接
     */
    private static final String gapUrl="https://apicn.gap.cn/gap/store/product/list/searchProductByCondition.do";

    /**
     * 爬虫数据返回
     * @param targetUrl 商品详情页路径
     * @return
     */
    @Override
    public JSONObject captureItem(String targetUrl) throws IOException, InterruptedException, ExecutionException, TimeoutException {
        JSONObject resultObj;
        //获取链接中的商品spuCode
        String itemId= getItemId(targetUrl);
        Map<String,Object> paramMap=new HashMap<>();
        JSONArray conditionList=new JSONArray();
        JSONObject valueObj =new JSONObject();
        JSONObject condition =new JSONObject();
        valueObj.put("key","style");
        valueObj.put("valueType","basic");
        valueObj.put("value",new String [] {itemId});
        conditionList.add(valueObj);
        condition.put("conditionList",conditionList);
        paramMap.put("data",condition);
        //获取请求结果
        String content = HttpClientUtil.sendPostWithBodyParameter(gapUrl,paramMap);
        resultObj=JSONObject.fromObject(content);

        if(resultObj.getBoolean("success")) {
            //格式化为封装数据
            ProductResponse productResponse = formatGapProductResponse(resultObj.getJSONObject("data"));
            resultObj=JSONObject.fromObject(productResponse);
            //翻译
            TranslateHelper.translateProductResponse(resultObj);
        }
        return resultObj;
    }

    /**
     * 获取商品链接的 id
     * @param targetUrl
     * @return
     */
    private String getItemId(String targetUrl) {
        String spuCode=targetUrl.substring(targetUrl.lastIndexOf("/")+1);
        int firstUnder=spuCode.indexOf("_");
        int lastUnder=spuCode.lastIndexOf("_");
        return spuCode.substring(firstUnder+1,lastUnder);
    }

    /**
     * 格式化 gap 返回数据
     *
     * @param dataMap
     * @return
     */
    private ProductResponse formatGapProductResponse(JSONObject dataMap) {
        ProductResponse productResponse = new ProductResponse();
        //原始价
        List<OriginalPrice> originalPriceList = new ArrayList<>();
        //促销价格
        List<ProductPromotion> promotionList = new ArrayList<>();
        Map<String, Set<ProductProp>> productPropSet = new HashMap<>();
        JSONArray productList = dataMap.getJSONArray("productList");
        //商品信息
        ItemInfo itemInfo = new ItemInfo();
        for (int index = 0; index < productList.size(); index++) {
            JSONObject propObj = productList.getJSONObject(index);
            //////////////////获取价格//////////////////
            JSONArray skuList = propObj.getJSONArray("skuList");
            for (int i = 0; i < skuList.size(); i++) {
                JSONObject skuValue = skuList.getJSONObject(i);
                JSONArray attrSaleList = skuValue.getJSONArray("attrSaleList");
                String skuStr = ";";
                for (int m = 0; m < attrSaleList.size(); m++) {
                    JSONObject attrSale = attrSaleList.getJSONObject(m);
                    JSONArray attributeValueList = attrSale.getJSONArray("attributeValueList");
                    skuStr = skuStr + attributeValueList.getJSONObject(0).getString("code") + ";";
                }
                //原始价格
                OriginalPrice originalPrice = new OriginalPrice();
                originalPrice.setSkuStr(skuStr);

                String listPrice = skuValue.getString("listPrice");
                //转换汇率
                listPrice = exchangeRate(listPrice);
                originalPrice.setPrice(listPrice);
                originalPriceList.add(originalPrice);
                //促销价格
                if (StringUtils.isNotBlank(skuValue.getString("salePrice"))) {
                    String salePrice = skuValue.getString("salePrice");
                    //转换汇率
                    salePrice = exchangeRate(salePrice);
                    productResponse.setPromotionFlag(true);
                    ProductPromotion productPromotion = new ProductPromotion();
                    productPromotion.setSkuStr(skuStr);
                    productPromotion.setPrice(salePrice);
                    promotionList.add(productPromotion);
                }
            }
            //////////////////获取价格 END//////////////////
            //////////////////获取商品属性//////////////////
            JSONArray attrSaleList = propObj.getJSONArray("attrSaleList");
            for (int i = 0; i < attrSaleList.size(); i++) {
                JSONArray attributeValueList = attrSaleList.getJSONObject(i).getJSONArray("attributeValueList");
                //商品属性
                Set<ProductProp> propSet = new HashSet<>();
                for (int j = 0; j < attributeValueList.size(); j++) {
                    ProductProp productProp = new ProductProp();
                    //获取图片，拿第一张
                    if (attributeValueList.getJSONObject(j).get("itemAttributeValueImageList") != null && !"null".equalsIgnoreCase(attributeValueList.getJSONObject(j).getString("itemAttributeValueImageList"))) {
                        JSONArray itemAttributeValueImageList = attributeValueList.getJSONObject(j).getJSONArray("itemAttributeValueImageList");
                        productProp.setImage(itemAttributeValueImageList.getJSONObject(0).getString("picUrl"));
                    }
                    productProp.setPropName(attributeValueList.getJSONObject(j).getString("attributeValueName"));
                    productProp.setPropId(attributeValueList.getJSONObject(j).getString("code"));
                    propSet.add(productProp);
                }
                String attributeFrontName = attrSaleList.getJSONObject(i).getString("attributeFrontName");
                if (productPropSet.get(attributeFrontName) == null) {
                    productPropSet.put(attributeFrontName, propSet);
                } else {
                    Set<ProductProp> oldPropSet = productPropSet.get(attributeFrontName);
                    propSet.addAll(oldPropSet);
                    productPropSet.put(attributeFrontName, propSet);
                }
            }

            //////////////////获取商品属性 END//////////////////
            itemInfo.setItemId(propObj.getString("style"));
            if (propObj.get("itemImageList") != null && !"null".equalsIgnoreCase(propObj.getString("itemImageList"))) {

                JSONArray itemImageList = propObj.getJSONArray("itemImageList");
                if (!itemImageList.isEmpty()) {
                    String pic = itemImageList.getJSONObject(0).getString("picUrl");
                    //取第一张当作主图
                    itemInfo.setPic(pic);
                }
            }
            itemInfo.setShopName(PlatformEnum.GAP.getLabel());
            itemInfo.setShopUrl("https://www.gap.cn/");
            itemInfo.setTitle(propObj.getString("title"));

        }

        String minPrice = dataMap.getString("minPrice");
        String maxPrice = dataMap.getString("maxPrice");
        //转换汇率
        minPrice = exchangeRate(minPrice);
        maxPrice = exchangeRate(maxPrice);

        //一口价
        productResponse.setPrice(minPrice + "-" + maxPrice);
        //一口价
        productResponse.setSalePrice(minPrice + "-" + maxPrice);
        //没有库存信息 需要另外获取
        productResponse.setStockFlag(false);
        //有商品属性
        productResponse.setPropFlag(true);
        productResponse.setOriginalPriceList(originalPriceList);
        productResponse.setPromotionList(promotionList);
        productResponse.setItemInfo(itemInfo);
        productResponse.setPlatform(PlatformEnum.GAP.getValue());
        productResponse.setProductPropSet(productPropSet);
        return productResponse;
    }
}
