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.ProductResponse;
import com.diaoyun.zion.master.util.HttpClientUtil;
import com.diaoyun.zion.master.util.TranslateHelper;
import com.diaoyun.zion.master.util.spider.UniqloSpiderParse;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

/**
 * 优衣库数据爬虫
 *
 * @author 爱酱油不爱醋
 */
@Component("uniqloSpider")
public class UniqloSpider implements IItemSpider {
    private static Logger logger = LoggerFactory.getLogger(UniqloSpider.class);

    /**
     * Uniqlo 商品详情链接
     */
    private static final String UNIQLO_URL = "https://www.uniqlo.cn/data/products/spu/";

    /**
     * Uniqlo 数据爬虫
     * @see UniqloSpiderParse#formatProductResponse 格式化数据方法
     * @param targetUrl 接收的商品详情路径
     * @return 格式化与翻译后的 Json 数据
     */
    @Override
    public JSONObject captureItem(String targetUrl) throws URISyntaxException, IOException, ExecutionException, InterruptedException, TimeoutException {
        // 截取链接中的商品 id
        String[] split = targetUrl.split("pid=");
        String pId = split[1];
        targetUrl = UNIQLO_URL + "zh_CN/" + pId + ".json";
        String content = HttpClientUtil.getContentByUrl(targetUrl, PlatformEnum.UNIQLO.getValue());
        // 获取折扣价格的接口
        String priceUrl = "https://d.uniqlo.cn/p/product/i/product/spu/pc/query/" + pId + "/zh_CN";
        String priceContent = HttpClientUtil.getContentByUrl(priceUrl, PlatformEnum.UNIQLO.getValue());
        JSONObject resultJson = JSONObject.fromObject(content);
        JSONObject priceJson = JSONObject.fromObject(priceContent);
        ProductResponse productResponse = UniqloSpiderParse.formatProductResponse(resultJson, priceJson, pId);
        resultJson = JSONObject.fromObject(productResponse);
        // 翻译
        TranslateHelper.translateProductResponse(resultJson);
        return resultJson;
    }

}
