import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import './DetailsList.scss';
/**
 * 对象详情列表展示组件
 *
 * @class DetailsList
 * @extends {Component}
 */
class DetailsList extends Component {

  static propTypes = {
    className: PropTypes.string, // css class
    prefixCls: PropTypes.string, // css class 前缀
    onClick: PropTypes.func, // 点击值函数
    // 对象展示配置信息
    configs: PropTypes.arrayOf(PropTypes.shape({
      key: PropTypes.string.isRequired, // 对象属性名
      label: PropTypes.string.isRequired, // 对象属性显示名称
      render: PropTypes.func // 对象值渲染函数
    })),
    data: PropTypes.object // 数据对象
  };

  static defaultProps = {
    configs: {},
    data: {},
    prefixCls: 'mods-com'
  };

  constructor(props) {
    super(props);
    this.state = {

    };
  }

  render() {
    const { configs, data, prefixCls, className, onClick } = this.props;
    const list = (configs || []).filter(e => !e.hide);
    if (list.length === 0) {
      return null;
    }
    const maxLabel = list.reduce((a,b) => a.label.length > b.label.length ? a : b) || '';
    return (
      <div className={classnames(`${prefixCls}-details-list`, className)}>
        {
          (configs || []).filter(e => !e.hide).map((e, index) => (
            <div key={e.key} className={`${prefixCls}-details-item`}>
              {e.label && <div className={`${prefixCls}-details-label`} style={{ width: `${maxLabel.length + 1}rem` }}>
                <label>{e.label}：</label>
              </div>}
              {e.unSetStyle ? <div
                className={classnames(`${prefixCls}-details-value`,e.className)}
              >
                {
                  !e.render ?
                    <label title={data[e.key]} onClick={(event)=>onClick(data[e.key], event)}>
                      {data[e.key]}
                    </label> :
                    e.render(data[e.key], data, index)
                }
              </div> :
                <div
                  className={`${prefixCls}-details-value`}
                  style={{ width: `calc(100% - ${e.label ? maxLabel.length + 1 : 0}rem)`, paddingLeft: e.label ? '1rem' : 0 }}
                >
                  {
                    !e.render ?
                      <label title={data[e.key]} onClick={(event)=>onClick(data[e.key], event)}>
                        {data[e.key]}
                      </label> :
                      e.render(data[e.key], data, index)
                  }
                </div>
              }
            </div>
          ))
        }
      </div>
    );
  }
}

export default DetailsList;
