/*
 * @Author: wfl
 * @LastEditors: wfl
 * @description:
 * @updateInfo:
 * @Date: 2022-10-11 13:50:33
 * @LastEditTime: 2022-10-13 11:03:48
 */
import { Md5 } from 'ts-md5/dist/md5';

const info = {
  apiServer:
    window.location.protocol === 'http:'
      ? 'http://api.fanyi.baidu.com/api/trans/vip/translate'
      : 'https://fanyi-api.baidu.com/api/trans/vip/translate',
  from: 'zh',
  to: 'en',
  appid: '20220914001342384',
};

let result = '';
window.translateCallback = function (response) {
  if (response && response.trans_result && response.trans_result.length) {
    const res = response.trans_result[0].dst;
    if (res) {
      result = res;
    } else {
      result = '';
    }
  }
};
let jsonp: HTMLScriptElement | null = null;
const translateAjax = (url, reslove) => {
  console.log('url: ', url);
  // jsonp 请求 百度翻译接口
  if (jsonp) {
    document.getElementsByTagName('head')[0].removeChild(jsonp);
    jsonp = null;
  }
  jsonp = document.createElement('script');
  jsonp.type = 'text/javascript';
  jsonp.src = url + '&callback=translateCallback';
  document.getElementsByTagName('head')[0].appendChild(jsonp);
  jsonp.onload = () => {
    reslove(true);
  };
  // fetch(url).then((res) => {
  //   res.json().then((json) => {
  //     console.log('json: ', json);

  //   })
  // })
};

function translateStr(this: any, q: string) {
  const { from, to, appid, apiServer } = info;
  const salt = Date.parse(new Date().toString()) / 1000;
  const params = {
    q,
    from,
    to,
    appid,
    salt,
    sign: Md5.hashStr(appid + q + salt + 'hGQg6hpQKH9CGwfqnXnQ'),
  };
  const url =
    apiServer + `?q=${q}&from=${from}&to=${to}&appid=${appid}&salt=${salt}&sign=${params.sign}`;
  return new Promise((reslove) => {
    return translateAjax(url, reslove);
  }).then(() => {
    window.translateCallback;
    return result; // 返回翻译后的信息
  });
}

export default translateStr;
