package com.diaoyun.zion.chinafrica.bis.impl;

import com.diaoyun.zion.chinafrica.bis.IItemSpider;
import com.diaoyun.zion.chinafrica.vo.ProductResponse;
import com.diaoyun.zion.master.util.*;
import com.diaoyun.zion.master.util.spider.SpiderUtil;
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.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

/**
 * Gap数据爬虫
 *
 * TOTO 不可用
 */
@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";

    @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 = SpiderUtil.formatGapProductResponse(resultObj.getJSONObject("data"));
            resultObj=JSONObject.fromObject(productResponse);
            //翻译
            TranslateHelper.translateProductResponse(resultObj);
        }

        return resultObj;
    }




    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);
    }



}
