import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { getPropsValue } from 'amos-designer';
import { utils } from 'amos-tool';
/**
 * LabelValueFrame
 *
 * @class LabelValueFrame
 * @extends {Component}
 */
class LabelValueFrame extends Component {

  static propTypes = {
    data: PropTypes.object,
    columns: PropTypes.array
  };

  static defaultProps = {

  };

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

    };
  }
  /**
  * 获取去字符串中的变量名称
  * 如 变量${props} 返回 [props]
  * @param {*} str
  */
  getExecStrs = (str) => {
    if (str && utils.isString(str)) {
      const reg = /\{(.+?)\}/g;
      const list = [];
      let result = null;
      do {
        result = reg.exec(str);
        result && list.push(result[1]);
      } while (result);
      return list;
    } else {
      return [];
    }
  }

  getValue = (data, value, defaultValue) => {
    if (utils.isString(value)) {
      if (value.includes('{')) {
        let variables = this.getExecStrs(value);
        let resValue = value;
        variables.forEach(key => {
          let _value = getPropsValue(data, key, defaultValue);
          resValue = resValue.replace(`{${key}}`, _value);
        });
        return resValue;
      } else {
        return getPropsValue(data, value, defaultValue);
      }
    } else if (utils.isFunction(value)) {
      return value(data);
    } else {
      return value;
    }
  }

  render() {
    const { columns, data } = this.props;
    return (
      <div className="ccs-comlv-frame">
        {
          columns.map(e => (
            <div key={e.label} className="ccs-comlv-item" style={{ width: e.width }}>
              <div className="ccs-comlv-label" style={{ width: e.labelWidth }}>{e.label}</div>
              <div className="ccs-comlv-valye">
                {
                  this.getValue(data, e.value, e.defaultValue)
                }
              </div>
            </div>
          ))
        }
      </div>
    );
  }
}

export default LabelValueFrame;
