package com.diaoyun.zion.master.util;

import com.diaoyun.zion.master.bo.TencentTranslateParam;
import com.diaoyun.zion.master.thread.TaskLimitSemaphore;
import com.diaoyun.zion.master.thread.TranslateCallable;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 腾讯翻译
 */
public class TranslateHelper {
    private static Logger logger = LoggerFactory.getLogger(TranslateHelper.class);

    //默认20条线程跑翻译
    private static final TaskLimitSemaphore taskLimitSemaphore=new TaskLimitSemaphore(20);
    /**
     * 翻译文本
     * @param futureList
     * @param valeMap
     * @param text
     */
    public static void translateText(List<Map<String, Object>> futureList, Map<String,Object> valeMap, String text){
        TencentTranslateParam tencentTranslateParam =new TencentTranslateParam(text);
        Future<Map<String,Object>> future = null;
        try {
            future = taskLimitSemaphore.submit(new TranslateCallable(tencentTranslateParam));
            Map<String,Object> map=new HashMap<>();
            map.put("future",future);
            map.put("value",valeMap);
            futureList.add(map);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 等待翻译结果
     * @param futureList
     */
    public static void waitForResult(List<Map<String, Object>> futureList) throws ExecutionException, InterruptedException, TimeoutException {
        for(Map<String,Object> futureMap:futureList) {
            Future<Map<String,Object>> future= (Future<Map<String, Object>>) futureMap.get("future");
            Map<String,Object> valeMap = (Map<String,Object> ) futureMap.get("value");
            while(!future.isDone());//Future返回如果没有完成，则一直循环等待，直到Future返回完成
            Map<String,Object> resultMap=future.get(10000, TimeUnit.MILLISECONDS);
            String targetText="unknow";
            if(resultMap!=null&&(int)resultMap.get("ret")==0) {
                Map<String,Object> dataMap=(Map<String,Object>)resultMap.get("data");
                targetText= (String) dataMap.get("target_text");
            } else {
                logger.error("翻译出错");
            }
            valeMap.put("translate",targetText);
        }
    }


    /**
     *  翻译规格属性 productPropSetMap 为 ProductResponse 的productPropSetMap 属性
     * @param futureList 线程回调
     * @param productPropSetMap 属性集合Map 为 ProductResponse 的productPropSetMap 属性
     */
    public static void translateProp(List<Map<String, Object>> futureList, Map<String,JSONArray> productPropSetMap) {
        JSONArray translateArray=new JSONArray();
        /*腾讯翻译*/
        for(Map.Entry<String, JSONArray>entry : productPropSetMap.entrySet()) {
            String key=entry.getKey();
            Map <String,Object> keyTranslateMap=new HashMap<>();
            keyTranslateMap.put(key,key);
            JSONArray productPropSet = entry.getValue();
            for(int i=0;i<productPropSet.size();i++) {
                JSONObject productPropMap=productPropSet.getJSONObject(i);
                //翻译属性值
                if(ValidateUtils.isContainChinese((String) productPropMap.get("propName"))) {
                    TranslateHelper.translateText(futureList,productPropMap, (String) productPropMap.get("propName"));
                } else {
                    productPropMap.put("translate",(String) productPropMap.get("propName"));
                }

            }
            translateArray.add(keyTranslateMap);

        }
        // TODO productPropSetMap.put("translateArray",translateArray);
    }

    /**
     * 翻译爬取回来的数据
     * @param resultObj ProductResponse格式的JSONObject
     * @throws InterruptedException
     * @throws ExecutionException
     * @throws TimeoutException
     */
    public static void translateProductResponse(JSONObject resultObj) throws InterruptedException, ExecutionException, TimeoutException {
        //////////////////////翻译//////////////////////
        List<Map<String, Object>> futureList= new ArrayList<>();
        Map<String, JSONArray> productPropSet = resultObj.getJSONObject("productPropSet");
        if(!productPropSet.isEmpty()) {
            //调用腾讯ai，翻译属性值
            TranslateHelper.translateProp(futureList,productPropSet);
            //翻译属性名
            //翻译属性名 // TODO 返回格式有待和前端确认
            /*JSONArray translateArray =productPropSet.get("translateArray");
            for(int i=0;i<translateArray.size();i++) {
                Map <String,Object> keyTranslateMap=translateArray.getJSONObject(i);
                boolean tranlateFlag=false;
                String key="";
                for(Map.Entry<String,Object> entry:keyTranslateMap.entrySet()) {
                    key=entry.getKey();
                    //翻译属性名
                    if(ValidateUtils.isContainChinese(key)) {
                        tranlateFlag=true;
                        TranslateHelper.translateText(futureList,keyTranslateMap,key);
                    }
                }
                if(!tranlateFlag) {
                    keyTranslateMap.put("translate",key);
                }
            }*/
        }
        //等待翻译结果
        TranslateHelper.waitForResult(futureList);
        resultObj.put("productPropSet",productPropSet);
        //////////////////////翻译 END//////////////////////
    }
}
