const axios = require('axios');
const uuid = require('uuid');
const crypto = require('crypto');
const dayjs = require('dayjs');
let config = {};
let sipLocalNumber = '';
function sendLog(log) {
  try {
    const logData = {
      level: 'info',
      traceId: uuid.v4(),
      content: `${dayjs().format('YYYY-MM-DD HH:mm:ss')} [${sipLocalNumber}]${log}`,
      way:"jssip"
    };
    let headers = getHeaders();
      axios
      .post('https://ktapps.keytop.cn/report/report/trace', logData, {
        headers,
      })
      .then((res) => {
        if (res.status === 200) {
          if (res.data.resultCode == 200) {
            ktlogFun(1, 'sip 日志上报成功');
          } else {
            ktlogFun(2, `sip 日志上报失败：${JSON.stringify(res.data)}`);
          }
        } else {
          ktlogFun(2, `sip 日志上报失败：${res.status},`);
        }
      })
      .catch((error) => {
        ktlogFun(2, `sip 日志上报错误：${error.message}`);
      });
  } catch (error) {
    ktlogFun(2, `sip 日志上报错误：${error.message}`);
  }
}
function ktlogFun(type = 1, msg) {
  if (type == 1) {
    if (ktLog && ktLog.i) {
      ktLog.i(msg);
    } else {
      console.log(msg);
    }
  } else if (type == 2) {
    if (ktLog && ktLog.e) {
      ktLog.e(msg);
    } else {
      console.error(msg);
    }
  }
}
function getHeaders() {
  let timestamp = Date.now()/1000;
  let md5 = crypto.createHash('md5');
  let appId = 1000;
  let appSecret = "770e4ae3765a4d9";
  let lotcode = config.lotcode ? config.lotcode : global.localConfig.lotCode;
  if (!appId || !appSecret || !lotcode) {
    throw new Error('appId or appSecret or lotcode is empty');
  }
  let sign = md5.update(appId + '_' + appSecret + '_' + timestamp).digest('hex');
  return {
    'Content-Type': 'application/json;charset=UTF-8',
    timestamp,
    sign,
    lotcode,
    appId,
  };
}
function setSipLogConfig(configParam) {
  config = configParam;
}
function setLocalNumber(number) {
  sipLocalNumber = number;
}
module.exports = {
  sendLog,
  setSipLogConfig,
  setLocalNumber,
};
