/* eslint-disable no-console */

import React, { PropTypes } from 'react';
import { push } from 'react-router-redux';
import { autobind } from 'core-decorators';
import Qs from 'qs';
import { Button, Tooltip } from '../index';
import { Upload, Modal } from '../mxa';
import { CONTAINER_PRE } from '../../framework/entrance/routes';
import { showModal } from '../../framework/pageContainer/ModalWrapper';
import { longRunExec } from '../../framework/system/longRunOpt';
import { jumpToNewTab } from '../../framework/utils/windowUtils';
import actionProcess from './actionProcess';
import { iconWrapper } from '../../framework/utils/IconHelper';
import { FFetch, GFetch } from '../../framework/system/fetch';
import { trimStart } from '../../framework/utils/StringUtils';
import { getSecurityToken, updateSecurityToken } from '../../framework/service/CacheService';

import {
  LIST_SELECTTYPE,
  BUTTON_INTERACTIVETYPE,
  BUTTON_MESSAGEPROMPTTYPE,
  BUTTON_RELATEDDATA,
  BUTTON_BINDPARAMETERTYPE,
  BUTTON_ACTIONTYPE
} from '../../framework/constant/dictCodes';

export class ExtendButton extends React.Component {
  static propTypes = {
    disabled: PropTypes.bool,
    prefixCls: PropTypes.string,
    noneIcon: PropTypes.bool,
  };

  static defaultProps = {
    selectedType: LIST_SELECTTYPE.INLINE,
    inline: true,
    relatedData: BUTTON_RELATEDDATA.NONE,
    noneIcon: false
  };

  constructor(props) {
    super(props);
    this.state = {
      loading: false
    };
  }

  _getIcon = 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));
  };

  @autobind
  switchLoading(flag) {
    this.setState({ loading: flag });
  }

  @autobind
  downloadFile(records, flag) {
    if (records && records.length > 0 && records.filter(record => record.documentPath !== null).length > 0) {
      const stsToken = getSecurityToken();
      const that = this;
      let client;
      if (stsToken && Object.keys(stsToken).length > 0) {
        client = this.createClient(stsToken);
        records.forEach(record => {
          this.executeDownloadFile(client, record, flag);
        });
      } else {
        updateSecurityToken().then(response => {
          if (Object.keys(response).length > 0) {
            client = this.createClient(response);
            records.forEach(record => {
              this.executeDownloadFile(client, record, flag);
            });
          } else {
            that.showDownloadFileErrorModal('获取token失败');
          }
        }).catch(err => {
          that.showDownloadFileErrorModal(err.code);
        });
      }
    } else {
      this.showDownloadFileErrorModal(' 无可下载文件');
    }
  }

  @autobind
  showDownloadFileErrorModal(err, record) {
    Modal.error({
      title: '下载失败',
      content: (record ? (record.name || '') : '') + err,
    });
  }

  @autobind
  createClient(stsToken) {
    /* eslint-disable */
    return new OSS.Wrapper({
      region: 'oss-cn-hangzhou',
      accessKeyId: stsToken.accessKeyId,
      accessKeySecret: stsToken.accessKeySecret,
      stsToken: stsToken.securityToken,
      bucket: 'demo-loc'
    });
  }

  @autobind
  executeDownloadFile(client, record, flag) {
    const documentPath = record.documentPath;
    const that = this;
    if (documentPath) {
      const iframe = document.createElement('iframe');
      document.body.appendChild(iframe);
      const 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 + '"'
        }
      });
    }
  }

  @autobind
  excelTemplateDownload() {
    const { actionLink, bindParameters } = this.props;
    // 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);
    longRunExec(() => {
      return GFetch(trimStart(actionLink, '/'), this._getBindParams(bindParameters)).then(response => {
        console.log('asdasdasdsdas');
      });
    });
  }

  // 第一阶段  收集数据
  @autobind
  _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 && actionProcess(this.props, this.switchLoading);
    }
  }

  @autobind
  _renderButton(isUpload) {
    return (
      <div onClick={!isUpload && this._triggerAction} className={'common-btn ' + (this.props.disabled ? 'disable' : '')} >
        {!this.props.noneIcon && iconWrapper(this._getIcon(this.props), undefined, undefined, undefined)}
        <a
          prefixCls={this.props.prefixCls}
          className={this.props.className}
          disabled={this.props.disabled}
        >{this.props.buttonDescriptionSupper || this.props.buttonDescription}</a>
      </div>
    );
  }

  @autobind
  genParams(parameters) {
    let str = '?';
    parameters.forEach(item => {
      str = str + item.name + '=' + item.value;
    });
    return str;
  }

  @autobind
  _getBindParams(parameters) {
    const params = {};
    parameters.forEach(item => {
      params[item.name] = item.value;
    })
    return params;
  }

  @autobind
  _getUploadProps() {
    const { bindParameters } = this.props;
    const params = this._getBindParams(bindParameters);
    return {
      data: this._getBindParams(bindParameters),
      showUploadList: false,
      multiple: false,
      withCredentials: false,
      // accept: 'application/*'
      customRequest: info => {
        if (info.file) {
          const {onSuccess, onError, ...rest} = info;
          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);
          };
          longRunExec(() => {
            return FFetch(rest).then(response => {

            });
          });
        }
      }
    };
  }


  componentDidMount() {
    const uploadBtns = document.querySelectorAll('.mx-upload-select-text');
    if (uploadBtns.length > 0) {
      const uploadBtnsLength = uploadBtns.length;
      let i = 0;
      for(; i < uploadBtnsLength; i++) {
        uploadBtns[i].style.width = '100%';
      }
    }
  }

  render() {
    if (this.props.buttonName === 'IMPORTEXCEL') {
      const uploadProps = this._getUploadProps();
      return (
        <Upload {...uploadProps} action={this.props.actionLink}>
          {this._renderButton(true)}
        </Upload>
      );
    }
    return this._renderButton();
  }
}

export default ExtendButton;
