
var appKey = "154838659000009e";
var secretKey = "e35b157960dca3e56407f7d1acda7f17";
var userId = "iplayabc";
// var baseUrl = "https://gray.stkouyu.com:8442/";
// var openApi = "https://openapi.iteachabc.com";
var domain = "https://teach.cdn.ireadabc.com/";
var baseUrl = "http://gray.stkouyu.com:8090/";
var openApi = "https://staging-openapi.iteachabc.com";

export function callNetworkApiGet(uri, data, callBack) {
    let queryStr = '?';
    const params = [];
    for (const key in data) {
        if (Object.hasOwnProperty.call(data, key)) {
            params.push(`${key}=${data[key]}`);
        }
    }
    queryStr += params.join("&");
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
        if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
            callBack(xhr.responseText);
        }
    };
    const url = `${openApi}${uri}${queryStr}`;
    console.log(`网络请求：`, url);
    xhr.open('GET', url, true);
    xhr.send();
}

export async function asyncCallNetworkApiGet(apiName, data) {
  return new Promise((resolve, reject) => {
    callNetworkApiGet(apiName, data, (res => {
      resolve(res);
    }));
  });
}



function getConSig(){
	var timestamp = new Date().getTime().toString();
	var sig = new jsSHA(appKey + timestamp + secretKey, 'TEXT').getHash("SHA-1", "HEX");
	return {sig:sig, timestamp: timestamp};
}
function getStartSig(){
	var timestamp = new Date().getTime().toString();
	var sig = new jsSHA(appKey + timestamp + userId + secretKey, 'TEXT').getHash("SHA-1", "HEX");
	return {sig:sig, timestamp: timestamp, userId: userId};
}
var createUUID = (function (uuidRegEx, uuidReplacer) {
	return function () {
		return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
	};
})(/[xy]/g, function (c) {
	var r = Math.random() * 16 | 0,
			v = c == "x" ? r : (r & 3 | 8);
	return v.toString(16);
});


var pubskyparms = null;
function initSkKouYuParms(refText="", coreType="para.eval") {
    var audioType = "mp3"; //音频格式，支持wav,mp3,ogg,opus等多种格式
    var sampleRate = 16000; //音频采样率
    var conSig = getConSig();
    var startSig = getStartSig();
    pubskyparms = {
      connect:{
        cmd: "connect",
        param: {
          sdk: {
            version: 16777472,
            source: 9,
            protocol: 2
          },
          app: {
            applicationId: appKey,
            sig: conSig.sig,
            timestamp: conSig.timestamp
          }
        }
      },
      start: {
        cmd: "start",
        param: {
          app: {
            applicationId: appKey,
            sig: startSig.sig,
            userId: startSig.userId,
            timestamp: startSig.timestamp
          },
          audio: {
            audioType: audioType,
            sampleRate: sampleRate,
            channel: 1,
            sampleBytes: 2
          },
          request: {
            getParam: 1,
            attachAudioUrl: 1,
            coreType: coreType,
            refText: refText,
            tokenId: createUUID()
          }
        }
      }
    };
}

var priOss = null;
async function getOssInstanse() {
  if (priOss) {
    return priOss; 
  }
  const stmp = Date.now();
  const salt = 'iplayABC2019';
  const sign = hex_md5(stmp + salt);
  const res = await asyncCallNetworkApiGet(`/oss/sts`, {stmp, sign});
  const ossConfig = JSON.parse(res).data;
  priOss = new OSS({
    accessKeyId: ossConfig.AccessKeyId,
    accessKeySecret: ossConfig.AccessKeySecret,
    stsToken: ossConfig.SecurityToken,
    refreshSTSToken: ossConfig.SecurityToken,
    refreshSTRokeInterval: 3000000,
    bucket: ossConfig.bucket,
    region: ossConfig.region
  });
  return priOss; 
}

var priRecorder = null;

function getWebRecordInstanse() {
  return priRecorder;
}

export function getRoomId() {
  if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) {
    return 'test-room-0001';
  }
  return new Promise((resolve) => {
    tt.getRoomInfo({
      complete(res){
        if (res && res.roomInfo) {
          resolve(res.roomInfo.roomID);
          return;
        }
        resolve(null);
      }
    });
  });
}

export function drawOpenNickName(str) {
  if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) {
    return {};
  }
  return new Promise((resolve) => {
    tt.drawOpenNickName({
      src: str,
      fontSize: 40,
      color: '#000000',
      complete(nickObj) {
        resolve(nickObj);
      }
    });
  });
}

export function getLiveUserInfo() {
  if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) {
    return {
      role: 'audience',
      uid: 'example',
      nickName: '',
    }
  }
  return new Promise((resolve) => {
    tt.getLiveUserInfo({
      complete(res){
        if (res.errCode != 0) {
          resolve(null);
          return;
        }
        const userInfo = res.userInfo;
        resolve({
          role: userInfo.role,
          uid: userInfo.openUID,
          nickName: userInfo.secNickname,
        });
      }
    });
  });
}

export function initRecorder(callback) {
  // if (!priRecorder) {
  //   priRecorder = tt.getRecorderManager();
  // }
  callback && callback(true);
}

var isSpeechToText;
export function supportMethod (method, param, fun) {
  if(method == 'getEngineInfo'){
    fun&&fun({isDev: 1, uuid: 'debug-xxxxxx-xxxxxx'});
  } else if (method == 'startTest') {
    // 初始化参数
    // initSkKouYuParms(param, 'para.eval');
    // const rec = getWebRecordInstanse();
    // rec.start();
  } else if (method == 'stopTest') {
    fun&&fun({
      result: {
        overall: 85
      },
      audioUrl: ""
    });
  } else {
    console.error(`${method}方法还没有Mock数据，请联系技术支持人员添加`);
  }
}
