import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BarGroup, IconButton, briskWarningTip } from 'amos-designer';
import { Icon } from 'amos-framework';
import { api } from '@gm/graphmod-utils';
import { connectGlobalPage } from '@gm/graphmod-common';
import ExecuteProgress from './ExecuteProgress';

const { templateDownload } = api;

/**
 * 导出sql脚本模块
 * @class DownloadView
 * @extends {Component}
 */
@connectGlobalPage({
  testDataConfig: {
    // resourceCode: 'StudioApplication', // 标识
    // dimension: 'appSeq', // 字段
    // appSeq: '1620614032232841218',
    // mqttUrl: 'ws://172.16.3.18:8088/mqtt'
  }
})
class DownloadView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      downloadVisible: false,
      logsVisible: false,
      selectId: ''
    };
  }

  handleClose = (key) => {
    this.setState({
      [key]: false
    });
  };

  handleOpen = (key) => {
    this.setState({
      [key]: true
    });
  };

  handleItemClick = () => {
    const { selectedRowKeys = [], dataConfig, record } = this.props;
    if (selectedRowKeys.length > 0 || record) {
      this.setState({ selectId: selectedRowKeys.length === 0 ? record.id ?? record.sequenceNbr  : selectedRowKeys[0], logsVisible: true }, () => {
        if (dataConfig.dimension && (selectedRowKeys.length > 0 || record)) {
          dataConfig[dataConfig.dimension] = (record ? record.id ?? record.sequenceNbr : null) || selectedRowKeys.join(',');
          templateDownload({ resourceCode: dataConfig.resourceCode, dimension: dataConfig.dimension, [dataConfig.dimension]: dataConfig[dataConfig.dimension] });
        }
      });
    } else {
      briskWarningTip('至少选择一行数据');
    }
  };

  render() {
    const { dataConfig = {} } = this.props;
    const { logsVisible, selectId } = this.state;
    return (
      <div>
        {dataConfig.position === 'header' ?
          <div className="ig-stage-toolbar-right">
            <BarGroup label="导出脚本" mode="none" position="right">
              <IconButton colorful icon="export" title="导出SQL脚本" style={{ borderRadius: 4 }} onClick={() => this.handleItemClick()} />
            </BarGroup>
          </div>
          :
          <p onClick={this.handleItemClick}><Icon icon="download" />下载</p>
        }
        {/* <DownloadModel
          visible={downloadVisible}
          onClose={() => this.handleClose('downloadVisible')}
          handleOpen={() => this.handleOpen()}
          dataConfig={dataConfig}
        /> */}
        <ExecuteProgress visible={logsVisible} mqttUrl={dataConfig.mqttUrl} exeId={selectId} onClose={() => this.handleClose('logsVisible')} />
      </div>
    );
  }
}

DownloadView.propTypes = {
  selectedRowKeys: PropTypes.array,
  dataConfig: PropTypes.object,
  record: PropTypes.object
};

export default DownloadView;
