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.master.thread.TaskLimitSemaphore;
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.ValidateUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
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.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

/**
 * 天猫数据爬虫
 */
@Component("tmItemSpider")
public class TmItemSpider implements IItemSpider {
    private static Logger logger = LoggerFactory.getLogger(TmItemSpider.class);

    //天猫链接
    private static final String tmallUrl="https://detail.m.tmall.com/item.htm?";

    @Override
    public JSONObject captureItem(String targetUrl) throws URISyntaxException, IOException, ExecutionException, InterruptedException, TimeoutException {
        //主要获取id参数，组成新链接
        //targetUrl=processUrl(targetUrl);
        List<Map<String, Object>> futureList= new ArrayList<>();
        //获取url中的网页内容
        String content = HttpClientUtil.getContentByUrl(targetUrl,PlatformEnum.TM.getValue());
        //获取商品详情 观察数据可发现商品数据在 _DATA_Detail 变量中
        JSONObject infoMap= JsoupUtil.getItemDetailByName(content,"_DATA_Detail");
        JSONObject skuBaseMap= (JSONObject) infoMap.get("skuBase");
        if(!(skuBaseMap.get("props") instanceof JSONNull)) {
            JSONArray propsArray= (JSONArray) skuBaseMap.get("props");
            for(int i=0;i<propsArray.size();i++) {
                JSONObject propMap=propsArray.getJSONObject(i);
                String propName= (String) propMap.get("name");
                JSONArray valueArray=propMap.getJSONArray("values");
                //翻译属性名
                if(ValidateUtils.isContainChinese(propName)) {
                    TranslateHelper.translateText(futureList,propMap,propName);
                }
                //翻译sku title
                if(valueArray!=null&&valueArray.size()>0) {
                    for(int j=0;j<valueArray.size();j++) {
                        JSONObject valueMap=valueArray.getJSONObject(j);
                        if(valueMap!=null&&valueMap.size()>0) {
                            String skuName= (String) valueMap.get("name");
                            //翻译属性名
                            if(ValidateUtils.isContainChinese(skuName)) {
                                TranslateHelper.translateText(futureList,valueMap,skuName);
                            }
                        }
                    }

                }
            }
        }

        //等待翻译结果
        TranslateHelper.waitForResult(futureList);
        //只取其中部分信息 TODO 后续可以继续封装
        JSONObject returnJson=new JSONObject();
        returnJson.put("seller",infoMap.get("seller"));
        returnJson.put("item",infoMap.get("item"));
        returnJson.put("mock",infoMap.get("mock"));
        returnJson.put("skuBase",infoMap.get("skuBase"));
        returnJson.put("platform", PlatformEnum.TM.getValue());
        return returnJson;
    }



    /**
     * 主要是提取相关参数，组成新的url
     * @param targetUrl
     * @return
     */
    /*@Deprecated
    private String processUrl(String targetUrl) throws URISyntaxException, MalformedURLException {
        String newUrl=tmallUrl;
        //if(targetUrl.contains("h5.m.taobao.com")) {
        //替换会影响参数的字符
        targetUrl= targetUrl.replaceAll("\\{","");
        targetUrl= targetUrl.replaceAll("\\}","");
        Map<String,String> paramMap=HttpClientUtil.getParamMap(targetUrl);
        //目前淘宝需要四个参数 spm id scm pvid
        //引起错误的 参数 ali_refid
        *//*for(Map.Entry<String,String> entry:paramMap.entrySet()) {
            if("id".equals(entry.getKey())) {
                newUrl=newUrl.replace("itemId",entry.getValue());
                break;
            }
        }*//*
        StringBuffer paramBuffer=new StringBuffer();
        for(Map.Entry<String,String> entry:paramMap.entrySet()) {
            if("ali_refid".equals(entry.getKey())||"track_params".equals(entry.getKey())||"utparam".equals(entry.getKey())
                    ||"rmdChannelCode".equals(entry.getKey())||"locate".equals(entry.getKey())) {

            } else {
                paramBuffer.append(entry.getKey()+"="+entry.getValue()+"&");
            }
        }

        return newUrl+paramBuffer.toString();

    }*/

}
