'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ExtendButton = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _desc, _value, _class, _class2, _temp; /* eslint-disable no-console */

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactRouterRedux = require('react-router-redux');

var _coreDecorators = require('core-decorators');

var _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

var _index = require('../index');

var _mxa = require('../mxa');

var _routes = require('../../framework/entrance/routes');

var _ModalWrapper = require('../../framework/pageContainer/ModalWrapper');

var _longRunOpt = require('../../framework/system/longRunOpt');

var _windowUtils = require('../../framework/utils/windowUtils');

var _config = require('../../config');

var _config2 = _interopRequireDefault(_config);

var _actionProcess = require('./actionProcess');

var _actionProcess2 = _interopRequireDefault(_actionProcess);

var _IconHelper = require('../../framework/utils/IconHelper');

var _fetch = require('../../framework/system/fetch');

var _StringUtils = require('../../framework/utils/StringUtils');

var _CacheService = require('../../framework/service/CacheService');

var _dictCodes = require('../../framework/constant/dictCodes');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

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

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

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

function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
  var desc = {};
  Object['ke' + 'ys'](descriptor).forEach(function (key) {
    desc[key] = descriptor[key];
  });
  desc.enumerable = !!desc.enumerable;
  desc.configurable = !!desc.configurable;

  if ('value' in desc || desc.initializer) {
    desc.writable = true;
  }

  desc = decorators.slice().reverse().reduce(function (desc, decorator) {
    return decorator(target, property, desc) || desc;
  }, desc);

  if (context && desc.initializer !== void 0) {
    desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
    desc.initializer = undefined;
  }

  if (desc.initializer === void 0) {
    Object['define' + 'Property'](target, property, desc);
    desc = null;
  }

  return desc;
}

var ExtendButton = exports.ExtendButton = (_class = (_temp = _class2 = function (_React$Component) {
  _inherits(ExtendButton, _React$Component);

  function ExtendButton(props) {
    _classCallCheck(this, ExtendButton);

    var _this = _possibleConstructorReturn(this, (ExtendButton.__proto__ || Object.getPrototypeOf(ExtendButton)).call(this, props));

    _this._getIcon = function (item) {
      if (item && !item.buttonIcon && !item.menuIcon) {
        if (item.name === 'PROCESS_APPLY_TRANSACTION' || item.name === 'PROCESS_REVIEW_TRANSACTION') {
          return 'icon-xiangmuguanli_yewuchuli';
        } else if (item.name === 'PROCESS_APPLY_QUERY' || item.name === 'PROCESS_REVIEW_QUERY') {
          return 'icon-jinduchaxun';
        } else if (item.name === 'PROCESS_APPLY_DETAIL' || item.name === 'PROCESS_REVIEW_DETAIL') {
          return 'icon-chakanxiangqing';
        } else if (item.name === 'PROCESS_APPLY_CANCEL') {
          return 'icon-quxiaoshenqing';
        }
      }
      return item && (item.buttonIcon || item.menuIcon);
    };

    _this.state = {
      loading: false
    };
    return _this;
  }

  _createClass(ExtendButton, [{
    key: 'switchLoading',
    value: function switchLoading(flag) {
      this.setState({ loading: flag });
    }
  }, {
    key: 'downloadFile',
    value: function downloadFile(records, flag) {
      var _this2 = this;

      if (records && records.length > 0 && records.filter(function (record) {
        return record.documentPath !== null;
      }).length > 0) {
        (function () {
          var stsToken = (0, _CacheService.getSecurityToken)();
          var that = _this2;
          var client = void 0;
          if (stsToken && Object.keys(stsToken).length > 0) {
            client = _this2.createClient(stsToken);
            records.forEach(function (record) {
              _this2.executeDownloadFile(client, record, flag);
            });
          } else {
            (0, _CacheService.updateSecurityToken)().then(function (response) {
              if (Object.keys(response).length > 0) {
                client = _this2.createClient(response);
                records.forEach(function (record) {
                  _this2.executeDownloadFile(client, record, flag);
                });
              } else {
                that.showDownloadFileErrorModal('获取token失败');
              }
            }).catch(function (err) {
              that.showDownloadFileErrorModal(err.code);
            });
          }
        })();
      } else {
        this.showDownloadFileErrorModal(' 无可下载文件');
      }
    }
  }, {
    key: 'showDownloadFileErrorModal',
    value: function showDownloadFileErrorModal(err, record) {
      _mxa.Modal.error({
        title: '下载失败',
        content: (record ? record.name || '' : '') + err
      });
    }
  }, {
    key: 'createClient',
    value: function createClient(stsToken) {
      /* eslint-disable */
      return new OSS.Wrapper({
        region: 'oss-cn-hangzhou',
        accessKeyId: stsToken.accessKeyId,
        accessKeySecret: stsToken.accessKeySecret,
        stsToken: stsToken.securityToken,
        bucket: 'demo-loc'
      });
    }
  }, {
    key: 'executeDownloadFile',
    value: function executeDownloadFile(client, record, flag) {
      var documentPath = record.documentPath;
      var that = this;
      if (documentPath) {
        var iframe = document.createElement('iframe');
        document.body.appendChild(iframe);
        var localFileName = record.name || documentPath.split('$')[1];
        iframe.onload = function (e) {
          if (!flag) {
            that.downloadFile([record], true);
          } else {
            that.showDownloadFileErrorModal("token 已经失效", record);
          }
        };
        iframe.src = client.signatureUrl(documentPath, {
          expires: 3600,
          response: {
            'content-disposition': 'attachment; filename="' + localFileName + '"'
          }
        });
      }
    }
  }, {
    key: 'excelTemplateDownload',
    value: function excelTemplateDownload() {
      var _this3 = this;

      var _props = this.props,
          actionLink = _props.actionLink,
          bindParameters = _props.bindParameters;
      // console.log('asdasdasdsa');
      // const iframe = document.createElement('iframe');
      // iframe.src = 'http://192.168.64.108:9081/core/' + trimStart(actionLink, '/') + this.genParams(bindParameters);
      // document.body.appendChild(iframe);

      (0, _longRunOpt.longRunExec)(function () {
        return (0, _fetch.GFetch)((0, _StringUtils.trimStart)(actionLink, '/'), _this3._getBindParams(bindParameters)).then(function (response) {
          console.log('asdasdasdsdas');
        });
      });
    }

    // 第一阶段  收集数据

  }, {
    key: '_triggerAction',
    value: function _triggerAction() {
      if (this.props.buttonName === 'DOWNLOAD') {
        this.downloadFile(this.props.record);
      } else if (this.props.buttonName === 'DOWNLOADEXCELTEMPLATE') {
        this.excelTemplateDownload();
      } else {
        !this.props.disabled && !this.state.loading && (0, _actionProcess2.default)(this.props, this.switchLoading);
      }
    }
  }, {
    key: '_renderButton',
    value: function _renderButton(isUpload) {
      return _react2.default.createElement(
        'div',
        { onClick: !isUpload && this._triggerAction, className: 'common-btn ' + (this.props.disabled ? 'disable' : '') },
        !this.props.noneIcon && (0, _IconHelper.iconWrapper)(this._getIcon(this.props), undefined, undefined, undefined),
        _react2.default.createElement(
          'a',
          {
            prefixCls: this.props.prefixCls,
            className: this.props.className,
            disabled: this.props.disabled
          },
          this.props.buttonDescriptionSupper || this.props.buttonDescription
        )
      );
    }
  }, {
    key: 'genParams',
    value: function genParams(parameters) {
      var str = '?';
      parameters.forEach(function (item) {
        str = str + item.name + '=' + item.value;
      });
      return str;
    }
  }, {
    key: '_getBindParams',
    value: function _getBindParams(parameters) {
      var params = {};
      parameters.forEach(function (item) {
        params[item.name] = item.value;
      });
      return params;
    }
  }, {
    key: '_getUploadProps',
    value: function _getUploadProps() {
      var bindParameters = this.props.bindParameters;

      var params = this._getBindParams(bindParameters);
      return {
        data: this._getBindParams(bindParameters),
        showUploadList: false,
        multiple: false,
        withCredentials: false,
        // accept: 'application/*'
        customRequest: function customRequest(info) {
          if (info.file) {
            (function () {
              var onSuccess = info.onSuccess,
                  onError = info.onError,
                  rest = _objectWithoutProperties(info, ['onSuccess', 'onError']);

              rest.onSuccess = function (ret) {
                onSuccess && onSuccess(ret);
                console.log('success', ret);
                if (ret === '') {
                  location.reload();
                }
              };
              rest.onError = function (err, ret) {
                onError && onError(err, ret);
                console.log('error', err);
              };
              (0, _longRunOpt.longRunExec)(function () {
                return (0, _fetch.FFetch)(rest).then(function (response) {});
              });
            })();
          }
        }
      };
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      var uploadBtns = document.querySelectorAll('.mx-upload-select-text');
      if (uploadBtns.length > 0) {
        var uploadBtnsLength = uploadBtns.length;
        var i = 0;
        for (; i < uploadBtnsLength; i++) {
          uploadBtns[i].style.width = '100%';
        }
      }
    }
  }, {
    key: 'render',
    value: function render() {
      if (this.props.buttonName === 'IMPORTEXCEL') {
        var uploadProps = this._getUploadProps();
        return _react2.default.createElement(
          _mxa.Upload,
          _extends({}, uploadProps, { action: this.props.actionLink }),
          this._renderButton(true)
        );
      }
      return this._renderButton();
    }
  }]);

  return ExtendButton;
}(_react2.default.Component), _class2.propTypes = {
  disabled: _react.PropTypes.bool,
  prefixCls: _react.PropTypes.string,
  noneIcon: _react.PropTypes.bool
}, _class2.defaultProps = {
  selectedType: _dictCodes.LIST_SELECTTYPE.INLINE,
  inline: true,
  relatedData: _dictCodes.BUTTON_RELATEDDATA.NONE,
  noneIcon: false
}, _temp), (_applyDecoratedDescriptor(_class.prototype, 'switchLoading', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'switchLoading'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'downloadFile', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'downloadFile'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'showDownloadFileErrorModal', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'showDownloadFileErrorModal'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'createClient', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'createClient'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'executeDownloadFile', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'executeDownloadFile'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'excelTemplateDownload', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'excelTemplateDownload'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, '_triggerAction', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, '_triggerAction'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, '_renderButton', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, '_renderButton'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'genParams', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'genParams'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, '_getBindParams', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, '_getBindParams'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, '_getUploadProps', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, '_getUploadProps'), _class.prototype)), _class);
exports.default = ExtendButton;