// 更新模板计算数值到数据域
import React from 'react';
import { Renderer, RendererProps } from '../../../../factory';
import { filter } from '../../../../utils/tpl';
import { anyChanged, getPropValue } from '../../../../utils/helper';
import { escapeHtml } from '../../../../utils/tpl-builtin';
import { BaseSchema, SchemaTpl } from '../../../../Schema';
import { BadgeSchema, withBadge } from '../../../../components/Badge';

export interface LionCalcTplSchema extends BaseSchema {
  type: 'lion-calc-tpl';
  tpl?: SchemaTpl;
  html?: SchemaTpl;
  text?: SchemaTpl;
  raw?: string;

  /**
   * 是否内联显示？
   */
  inline?: boolean;

  /**
   * 自定义样式
   */
  style?: {
    [propName: string]: any;
  };

  /**
   * 角标
   */
  badge?: BadgeSchema;
}
export interface LionCalcTplProps
  extends RendererProps,
  Omit<LionCalcTplSchema, 'type' | 'className'> {
  wrapperComponent?: any;
}

export interface LionCalcTplState {
  content: any
}

export class LionCalcTpl extends React.Component<LionCalcTplProps, LionCalcTplState> {
  static defaultProps: Partial<LionCalcTplProps> = {
    wrapperComponent: '',
    inline: true,
    placeholder: '-'
  };

  constructor(props: LionCalcTplProps) {
    super(props)
    this.state = {
      content: ""
    }
  }


  getContent() {
    const { tpl, html, text, raw, data, placeholder } = this.props;
    const value = getPropValue(this.props);

    if (raw) {
      return raw;
    } else if (html) {
      return filter(html, data);
    } else if (tpl) {
      return filter(tpl, data);
    } else if (text) {
      return escapeHtml(filter(text, data));
    } else {
      return value == null || value === ''
        ? `<span class="text-muted">${placeholder}</span>`
        : typeof value === 'string'
          ? value
          : JSON.stringify(value);
    }
  }

  componentWillMount() {
    this.updateValue()
  }

  componentDidUpdate() {
    this.updateValue()
  }

  updateValue() {
    const { name, onQuickChange } = this.props;
    const value = this.getContent()
    if (value !== this.state.content) {
      this.setState({ content: value }, () => {
        // 发送计算好的数值到上层，isUpdate 是否经过更新
        onQuickChange && onQuickChange({ [name]: value })
      })
    }
  }

  render() {
    const {
      className,
      wrapperComponent,
      inline,
      classnames: cx,
      style
    } = this.props;

    const Component = wrapperComponent || (inline ? 'span' : 'div');

    return (
      <Component className={cx('LionCalcTplField', className)} style={style}>
        {this.state.content}
      </Component>
    );
  }
}


@Renderer({
  test: /(^|\/)(?:lion-calc-tpl|lion-calc-html)$/,
  name: 'lion-calc-tpl'
})
// @ts-ignore 类型没搞定
@withBadge
export class LionCalcTplRenderer extends LionCalcTpl { }
