/*
 * @Author: your name
 * @Date: 2020-12-07 15:45:49
 * @LastEditTime: 2020-12-07 16:24:54
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \rs-cloud-platform-ui\src\utils\translate.js
 */
import "utils/md5";

window.transResult = ""

// 初始化翻译
window.toTranslate = function(words,toLanguage) {
    if (words == "") {
        return;
    }
    //获取创建的script标签
    var s = document.getElementById('urlData');
    //如果script标签已经存在删除了重新创建
    if (s) {
        s.parentNode.removeChild(s);
        translate(words,toLanguage);
    } else {
        translate(words,toLanguage);
    }
}

// 初始翻译标签
window.translate = function(words,lang = "en") {
    // appId和appSecret需要更改
    let appId = "2015063000000001"
    let appSecret = "12345678"
    //获取接口
    let url = 'http://api.fanyi.baidu.com/api/trans/vip/translate?';
    // 当前时间戳
    let salt = (new Date).getTime()
    // 组合字段
    let str = appId + words + salt + appSecret; //秘钥
    //此处拼接接口数据,好转换成jsonp数据格式,实现跨域访问
    // var str = '20170605000052254' + words + salt + '63r1c42X7_buc4OrXm1g';
    //使用加密算法计算数据
    let md5 = window.MD5(str);
    //然后得到的数据
    let data = 'q=' + words + '&from=auto&to=' + lang + '&appid=' + appId + '&salt=' + salt + '&sign=' + md5 + "&callback=callbackName";
    //引入src路径
    let src = url + data;
    //调用创建script标签函数
    createScript(src);
}

// 创建翻译脚本
window.createScript = function(src) {
    //创建一个script标签
    var script = document.createElement('script');
    //添加src和id属性
    script.id = 'urlData';
    script.src = src;
    //将script标签添加到body页面中
    document.body.appendChild(script);
}

//回调函数定义
window.callbackName = function(str){
    window.transResult = str
    console.log("翻译结果=>",window.transResult)
}