"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _controller = require("../controller.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var _status = Symbol("status");
/**
 * 后台服务组件
 * @param {[type]} dataModel [description]
 */


var Service = /*#__PURE__*/function (_InvisibleComponent) {
  _inherits(Service, _InvisibleComponent);

  var _super = _createSuper(Service);

  function Service(__tfp, dataModel, parent) {
    var _this;

    _classCallCheck(this, Service);

    _this = _super.call(this, __tfp, "Service", dataModel, parent);
    _this[_status] = 0;
    _this.cbFuncs = []; //回调函数

    return _this;
  } //服务请求状态，0：未请求，1：正在请求，2：请求完毕


  _createClass(Service, [{
    key: "status",
    get: function get() {
      return this[_status];
    },
    set: function set(value) {} //服务路径

  }, {
    key: "path",
    get: function get() {
      return this.dataModel.path;
    },
    set: function set(value) {
      this.dataModel.path = value;
    } //请求参数

  }, {
    key: "args",
    get: function get() {
      return this.dataModel.args;
    },
    set: function set(value) {
      this.dataModel.args = value;
    } //请求参数设置

  }, {
    key: "argSettings",
    get: function get() {
      return this.dataModel.argSettings;
    },
    set: function set(value) {
      this.dataModel.argSettings = value;
    } //是否自动显示错误提示

  }, {
    key: "autoShowError",
    get: function get() {
      return this.dataModel.autoShowError ? true : false;
    },
    set: function set(value) {
      this.dataModel.autoShowError = value ? true : false;
    }
    /**
     * 设置请求参数设置
     * @param {[type]} name  [description]
     * @param {[type]} type  [description]
     * @param {[type]} value [description]
     */

  }, {
    key: "setArgSetting",
    value: function setArgSetting(name, type, value) {
      if (!name) {
        this._tfp.showMsg("请提供参数名称！");

        return;
      }

      if (!this.dataModel.argSettings) this.dataModel.argSettings = [];
      var arg = {
        name: name
      };
      if (type) arg.type = type;
      if (value) arg.value = value;
      var isExists = false;

      for (var i = 0; i < this.dataModel.argSettings.length; i++) {
        if (this.dataModel.argSettings[i].name == arg.name) {
          isExists = true;
          this.dataModel.argSettings[i].type = type;
          this.dataModel.argSettings[i].value = value;
          break;
        }
      }

      if (!isExists) this.dataModel.argSettings.push(arg);
    }
    /**
     * 删除请求参数设置
     * @param  {[type]} name [description]
     * @return {[type]}      [description]
     */

  }, {
    key: "removeArgSetting",
    value: function removeArgSetting(name) {
      if (!name || !this.dataModel.argSettings) return;

      for (var i = 0; i < this.dataModel.argSettings.length; i++) {
        if (this.dataModel.argSettings[i].name == arg.name) {
          this.dataModel.argSettings.splice(i, 1);
          return;
        }
      }
    }
    /**
     * 显示错误信息
     * @param  {[type]} msg [description]
     * @return {[type]}     [description]
     */

  }, {
    key: "showError",
    value: function showError(msg) {
      console.error(msg);

      if (this.dataModel.autoShowError && typeof window != "undefined") {
        this._tfp.showMsg(msg);
      }

      if (this.onError) {
        this.onError(msg);
      } else if (this.dataModel.onError) {
        eval(this.dataModel.onError);
      }
    }
    /**
     * 获取HTTP请求对象
     * @return {[type]}         [description]
     */

  }, {
    key: "getHttpRequest",
    value: function getHttpRequest() {
      var httpRequest;

      if (window.XMLHttpRequest) {
        httpRequest = new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");

        if (!httpRequest) {
          httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
      }

      if (!httpRequest) {
        this.showError("您的浏览器不支持Ajax，无法执行该操作！");
        return null;
      }

      return httpRequest;
    }
    /**
     * 请求服务
     * @param  {[type]}   args 请求参数
     * @param  {Function} cb   回调函数
     */

  }, {
    key: "request",
    value: function request(args, cb) {
      if (!this.path) {
        this.showError("请提供服务路径！");
        return;
      }

      if (cb) this.cbFuncs.push(cb); //如果当前服务对象正在发送请求，则不重复请求

      if (this[_status] == 1) return; //设置请求参数

      if (!args) args = {};
      args.service = this.path;

      if (this.dataModel.args) {
        for (var p in this.dataModel.args) {
          args[p] = this.dataModel.args[p];
        }
      }

      if (this.dataModel.argSettings) {
        for (var i = 0; i < this.dataModel.argSettings.length; i++) {
          var _arg = this.dataModel.argSettings[i];

          if (_arg.type == "QueryString") {
            if (_arg.value) {
              args[_arg.name] = this._tfp.getUrlArg(_arg.value);
            } else {
              args[_arg.name] = this._tfp.getUrlArg(_arg.name);
            }
          } else if (_arg.type == "ComponentVal") {
            var cpt = null;

            if (_arg.value) {
              cpt = this._tfp.get(_arg.value);
            } else {
              cpt = this._tfp.get(_arg.name);
            }

            if (cpt) args[_arg.name] = cpt.value;
          } else if (_arg.type == "ComponentAttr") {
            if (_arg.value && _arg.value.indexOf(".") > 0) {
              var cptInfo = _arg.value.split(".");

              var _cpt = this._tfp.get(cptInfo[0]);

              if (_cpt && cptInfo[1] != "") args[_arg.name] = _cpt[cptInfo[1]];
            }
          } else if (_arg.type == "DialogArg") {
            if (_arg.value) {
              var dialogArgs = null;

              try {
                dialogArgs = JSON.parse(this._tfp.getDialogArgs());
                args[_arg.name] = dialogArgs[_arg.value];
              } catch (e) {
                this._tfp.showMsg(e.message);
              }
            } else {
              args[_arg.name] = this._tfp.getDialogArgs();
            }
          } else if (_arg.type == "Expression") {//TODO
          } else {
            args[_arg.name] = _arg.value;
          }
        }
      } //是否终止请求，如果服务请求有关的事件处理函数返回true
      //则表示终止请求，不再执行后续代码


      var endRequest = false;
      this.exeEventHandler("onRequest"); //如果设置了请求前需要执行的事件处理函数，则执行该函数

      /*if(this.onRequest && typeof this.onRequest == "function") {
        endRequest = this.onRequest(args);
      } else if(this.dataModel.onRequest) {
        endRequest = eval(this.dataModel.onRequest);
        if(endRequest) return;
      }*/

      this[_status] = 1; //设置身份验证信息

      if (typeof top != "undefined" && top.taskMsgAuthObj) {
        var authObj = {
          args: {}
        };
        top.taskMsgAuthObj.setAuthData(authObj);

        for (var _arg2 in authObj.args) {
          args[_arg2] = authObj.args[_arg2];
        }
      } else if (typeof window.parent != "undefined" && window.parent.taskMsgAuthObj) {
        var _authObj = {
          args: {}
        };
        window.parent.taskMsgAuthObj.setAuthData(_authObj);

        for (var _arg3 in _authObj.args) {
          args[_arg3] = _authObj.args[_arg3];
        }
      } else if (typeof tmClient != "undefined" && (tmClient.clientOSType == "iOS" && typeof TMiOSClient != "undefined" || tmClient.clientOSType == "Android" && typeof TMAndroidClient != "undefined")) {
        var authData = JSON.parse(tmClient.getAuthData());
        args._auth_org = authData._auth_org;
        args._auth_ts = authData._auth_ts;
        args._auth_data = authData._auth_data;
      } else {
        if (this._tfp.getUrlArg("_auth_org")) args._auth_org = this._tfp.getUrlArg("_auth_org");
        if (this._tfp.getUrlArg("_auth_ts")) args._auth_ts = this._tfp.getUrlArg("_auth_ts");
        if (this._tfp.getUrlArg("_auth_data")) args._auth_data = this._tfp.getUrlArg("_auth_data");
      } //console.log(args);


      if ("undefined" != typeof top.taskBuilder) {
        var that = this;
        top.taskBuilder.requestByIPC(this.path, args, function (req, res) {
          that.onResponse(req, res);
        });
      } else {
        this.sendRequest(args);
      }
    }
  }, {
    key: "exeResponseFunc",
    value: function exeResponseFunc(req, res, responseFuncStr) {
      if (responseFuncStr.indexOf(".") < 0 && responseFuncStr.indexOf(" ") < 0 && responseFuncStr.indexOf("=") < 0 && responseFuncStr.indexOf("(") < 0 && responseFuncStr.indexOf(")") < 0) {
        eval(responseFuncStr + "(req, res)");
      } else {
        eval(responseFuncStr);
      }
    }
  }, {
    key: "onResponse",
    value: function onResponse(req, res) {
      if (res.code == 0) {
        if (this.srcElement) req.srcElement = this.srcElement;

        if (this.cbFuncs.length > 0) {
          for (var i = 0; i < this.cbFuncs.length; i++) {
            this.cbFuncs[i](req, res);
          }
        }

        if (this.dataModel.onResponse && typeof this.dataModel.onResponse == "string") {
          this.exeResponseFunc(req, res, this.dataModel.onResponse);
        }
      } else {
        //如果是身份验证失败
        if (res.code == 501) {
          top.location = "/";
          return;
        }

        this.showError(res.message);
      }
    }
  }, {
    key: "sendRequest",
    value: function sendRequest(args) {
      var that = this;
      var httpRequest = this.getHttpRequest();

      try {
        httpRequest.onreadystatechange = function () {
          if (httpRequest.readyState == 4) {
            that[_status] = 2;

            if (httpRequest.status == 200) {
              var response = JSON.parse(httpRequest.responseText);
              that.onResponse(args, response);
            } else if (httpRequest.status == 404) {
              that.showError("请求的服务不存在！");
            } else {
              if (httpRequest.status !== 0) that.showError("向服务器发送请求时发生意外错误！\r\n错误代码：" + httpRequest.status);
            }
          }
        };

        var serverPath = location.toString();
        serverPath = serverPath.substr(0, serverPath.indexOf("/", 8) + 1);
        httpRequest.open("POST", serverPath + "Service", true);
        httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        httpRequest.send(JSON.stringify(args));
      } catch (e) {
        this.showError("向服务器发送请求时发生意外错误！\r\n错误描述：" + e.message);
      }
    }
  }]);

  return Service;
}(_controller.InvisibleComponent);

exports["default"] = Service;