// (function (path){ 
//     var a=document.createElement("script");
//     a.type = "text/javascript"; 
//     a.src=path; 
//     var head=document.getElementsByTagName("head")[0];
//     head.appendChild(a);
//   })('fcfg.js');


(function (global) {

  // 工具组件
  var utils = {};

  /**
   * 将 url 的附带参数转化成 JSON 对象
   * @param  {String} str 类似于`"name=abc&age=12"`
   * @return {JSON}     JSON键值对
   */
  utils.queryToJson = function (str) {
    return str.split('&').reduce(function (prev, curr) {
      curr = curr.split('=');
      curr[1] = curr[1].replace('(~)', "=").replace('(^)', "&");
      prev[curr[0]] = curr[1];
      return prev;
    }, {});
  };

  /**
   * 将 JSON 对象转换成 url 查询字符串
   * @param  {JSON} obj JSON键值对
   * @return {String}     查询串
   */
  utils.jsonToQuery = function (obj) {
    var ret = [];
    var key;
    for (key in obj) {
      if (obj.hasOwnProperty(key)) {
        ret.push(key + '=' + obj[key]);
      }
    }
    return ret.join('&');
  };


  function FyCmdex(options) {
    options.path = options.path || '/FYCMDEX';
    if (typeof jQuery == 'undefined') {
      axios({
        method: 'get',
        url: options.path + '?' + options.data,
        scriptCharset: 'utf-8',
      })
        .then(function (res) {
          options.callback(null, res.data);
        })
        .catch(function (err) {
          options.callback(err, null);
        });
    } else {
      $.ajax({
        url: options.path + '?' + options.data,
        type: 'Get',
        scriptCharset: 'utf-8',
        success: function (res) {
          options.callback(null, res);
        },
        error: function (xhr, state, err) {
          options.callback(err, null);
        }
      });
    }
  }

  function FyInnerCmdex(options) {
    options.path = options.path || '/FYCMDEX';
    var promise = $.ajax({
      url: options.path + '?' + options.data,
      type: 'Get',
      scriptCharset: 'utf-8',
      success: function (res) {
        options.callback(null, res);
      },
      error: function (xhr, state, err) {
        options.callback(err, null);
      }
    });
    return promise;
  }
  global.CallFYEX = FyCmdex;
  global.FYServer = FConfig._FYURL + ':' + FConfig._FYPORT;
  var rapidCalls = {};

  rapidCalls.PC = function (entry, stream, callback) {
    function once(fn) {
      var called = false;
      return function () {
        if (called) {
          console.warn('重复的回调: ', fn.name);
          return;
        }
        called = true;
        return fn.apply(this, arguments);
      };
    }
    var request = {
      Method: 'CallFQL',
      FuncName: entry,
      Param: stream
    };
    callback = once(callback);
    window.CallFYEX({
      request: JSON.stringify(request),
      onSuccess: function (response) {
        callback(null, response);
      },
      onFailure: function (errCode, errInfo) {
        callback(errInfo || '底层错误(FYQuery)', errCode);
      }
    });
  };

  global.FYClientLite = function (type) {
    switch (String(type).toLowerCase()) {
      case 'fyex':
        return (function () {
          return function (entry, data, callback) {
            tqlex({
              entry: entry,
              data: data,
              callback: callback
            });
          };
        }());
      default:
        return (function () {
          return rapidCalls.PC;
        }());
    }
  };
}(window));