import React from 'react';
import { Dialog, Loading, Placeholder, Icon } from '@txdfe/at';
import Item from '../extension-item';
import './index.scss';

class ExtensionPanel extends React.Component {

  handleOpenAppStore = () => {
    window.open(`${this.props.appstoreUrl || window.UILessConfig.appstoreUrl}?organizationId=${window.UILessConfig.orgId}`)
  }

  render() {
    const { loading, visible, onClose } = this.props;

    return (
      <Dialog
        visible={visible}
        title="应用中心"
        closeable="esc,close,mask"
        minMargin={48}
        className="uiless-extension-panel"
        footer={false}
        onClose={onClose}
        cache
      >
        <Loading className="uiless-extension-container" visible={loading}>
          {this.renderApps()}
          {this.renderMoreApps()}
        </Loading>
      </Dialog>
    )
  }

  renderApps() {
    const { extendData, isAdmin, objectType, objectId, onChange } = this.props
    if (!extendData.length) {
      return (
        <div className="uiless-extension-container-empty">
          <Placeholder
            image="https://img.alicdn.com/tfs/TB1Awk8lqL7gK0jSZFBXXXZZpXa-124-124.png"
            description="暂无应用"
          />
        </div>
      )
    }

    const rowData = [];
    let rowIndex = -1;
    extendData.forEach((item, index) => {
      if (index % 3 === 0) {
        rowIndex = rowIndex + 1;
      }
      if (!rowData[rowIndex]) {
        rowData[rowIndex] = [];
      }
      rowData[rowIndex].push(item);
    });

    const genEmptyItem = () => ({
      isEmpty: true,
      key: Math.random(),
    });
    if (extendData.length % 3 === 1) {
      rowData[rowData.length - 1].push(genEmptyItem());
      rowData[rowData.length - 1].push(genEmptyItem());
    } else if (extendData.length % 3 === 2) {
      rowData[rowData.length - 1].push(genEmptyItem());
    }

    return (
      <>
        {
          rowData.map((row, rowI) => {
            return (
              <div key={rowI} className="uiless-extension-container-row">
                {
                  row.map((item, index) => {
                    return (
                      <Item
                        onChange={onChange}
                        objectId={objectId}
                        objectType={objectType}
                        key={item.key}
                        item={item}
                        isAdmin={isAdmin}
                      />
                    );
                  })
                }
              </div>
            )
          })
        }
      </>
    )
  }

  renderMoreApps() {
    const { needAppstore = true, appstoreUrl, loading } = this.props;
    if (!needAppstore || !(appstoreUrl || window.UILessConfig.appstoreUrl) || loading) {
      return null
    }

    return (
      <div className="uiless-extension-container-fix-button" onClick={this.handleOpenAppStore}>
        更多应用
        <Icon type="arrow-right-o" />
      </div>
    )
  }
}

export default ExtensionPanel;
