import React from 'react';
import { Renderer, RendererProps } from '../../../../factory';
import { filter } from '../../../../utils/tpl';
import cx from 'classnames';
import { anyChanged, functionInOneFrame, getPropValue } from '../../../../utils/helper';
import { escapeHtml } from '../../../../utils/tpl-builtin';
import { BaseSchema, SchemaTpl } from '../../../../Schema';
import styled from 'styled-components';
import offset from '../../../../utils/offset';


const Wrapper = styled.div`
  .testTpl{
    box-sizing: border-box;
    border:0;
    margin-top:5px;
    color: #333;
    -webkit-font-smoothing: antialiased;
    .testTpl-item{
      display: flex;
      align-items: center;
      justify-content: flex-end;
      padding: 0 20px;
      font-weight: 700;
      span{
        margin-left: 20px;
        margin-right: 0px;
      }
    }
  }

`

/**
 * tpl 渲染器
 */
export interface LionTplSchema extends BaseSchema {
  /**
   * 指定为模板渲染器。
   *
   * 文档：https://baidu.gitee.io/amis/docs/concepts/template
   */
  type: 'lion-tpl' | 'lion-html';

  tpl?: SchemaTpl;
  html?: SchemaTpl;
  text?: SchemaTpl;
  raw?: string;

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

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

export interface TplProps extends RendererProps, LionTplSchema {
  className?: string;
  value?: string;
  wrapperComponent?: any;
  inline?: boolean;
  updateAutoFillHeight?: () => void
}

export class LionTpl extends React.Component<TplProps, object> {
  static defaultProps: Partial<TplProps> = {
    inline: true,
    placeholder: ''
  };

  dom: any;

  constructor(props: TplProps) {
    super(props);
    this.htmlRef = this.htmlRef.bind(this);
  }

  componentDidUpdate(prevProps: TplProps) {
    if (
      anyChanged(
        ['data', 'tpl', 'html', 'text', 'raw', 'value'],
        this.props,
        prevProps
      )
    ) {
      functionInOneFrame(() => {
        this._render();
      })
    }
  }

  componentWillUnmount(): void {
    this.dom = null
  }

  htmlRef(dom: any) {
    this.dom = dom;
    // if (offset(dom?.parentElement)) {
    //   this.props?.updateAutoFillHeight?.()
    // }
    this._render();
  }

  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);
    }
  }

  _render() {
    if (!this.dom) {
      return;
    }

    let _html: string = '';
    this.getContent().split(',').map(item => {
      _html += `<span>${item}</span>`
    })


    this.dom.firstChild.innerHTML = this.props.collect ? _html : this.getContent();
  }

  render() {
    const {
      className,
      wrapperComponent,
      inline,
      classnames: cx,
      style,
      collect
    } = this.props;
    const Component = collect ? (wrapperComponent || 'div') : wrapperComponent || (inline ? 'span' : 'div')

    return (
      <Wrapper>
        <Component
          ref={this.htmlRef}
          className={cx('TplField', collect ? 'testTpl' : '', className)}
          style={style}
        >{
            collect ? <div className='testTpl-item'>
              {
                this.getContent().split(',').map(item => {
                  return <span>{item}</span>
                })
              }
            </div> : <span>{this.getContent()}</span>
          }
        </Component>
      </Wrapper>
    )
  }
}

@Renderer({
  test: /(^|\/)(?:lion-tpl|lion-html)$/,
  name: 'lion-tpl'
})
export class LionTplRenderer extends LionTpl { }
