import React from 'react';
import { Renderer, RendererProps } from '../factory';
import { filter } from '../utils/tpl';
import { anyChanged, getPropValue, isMobile } from '../utils/helper';
import { escapeHtml } from '../utils/tpl-builtin';
import { BaseSchema, SchemaTpl } from '../Schema';
import { BadgeSchema, withBadge } from '../components/Badge';
import { Icon } from '../components/icons';
import Popover from 'antd/lib/popover';
import { Button } from 'antd';
import { Drawer } from '../components/antdCompoentsProxy';
import { ModleHandleClick } from '../utils/utils';
import { isNil } from 'lodash';

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

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

  /**
   * 是否内联显示？
   */
  inline?: boolean;
  /**
   * 自定义样式
   */
  style?: {
    [propName: string]: any;
  };

  /**
   * 角标
   */
  badge?: BadgeSchema;


  defaultOpen?: boolean;
  linkId?: string
  /**
   * 请求的路径
   */
  linkUrl?: string;
  /**
   * 弹窗大小
   */
  linkSize?: string;
  /**
   * 弹窗类型 0 弹窗 1 saas tab分页调用env.onPageLink 3暂时没有
   */
  linkType?: 0 | 1 | 2;
  /**
   *  弹窗标题
   */
  linkTitle?: string
}

export interface TplProps extends RendererProps, TplSchema {
  className?: string;
  value?: string;
  wrapperComponent?: any;
  inline?: boolean;

}
interface TplState {
  contents?: any
  visible: boolean
  openHtml: boolean
}
export class Tpl extends React.Component<TplProps, object, TplState> {
  static defaultProps: Partial<TplProps> = {
    inline: true,
    placeholder: ''
  };

  dom: any;
  pop: any;
  state: TplState = {
    contents: '',
    visible: false,
    openHtml: false
  }
  constructor(props: TplProps) {
    super(props);
    this.htmlRef = this.htmlRef.bind(this);
    this.htmlPopovers = this.htmlPopovers.bind(this);
  }

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

  htmlRef(dom: any) {
    this.dom = dom;
    this._render();
  }
  htmlPopovers(pop: any) {
    this.pop = pop
    this._poprender();
  }
  getContent() {
    const { tpl, html, text, raw, data, placeholder, biGroupIndex, name } = this.props;
    const value = getPropValue(this.props);
    if (raw) {
      return raw;
    } else if (html) {
      return filter(html, data);
    } else if (tpl) {
      if (biGroupIndex) {
        return String(value)
      }
      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 }
    const { defaultOpen, formItem, type, detailsTitle, isTableContent } = this.props
    const Html = formItem?.type == 'static-html' || type == 'html'
    const prpovertit = Html || detailsTitle
    const value = this.props.env.filterHtml(this.getContent());
    this.dom.firstChild.innerHTML = (defaultOpen || prpovertit) ? !isTableContent ? this.getContent() : this.removeHtmlTags(value) : value
  }
  _poprender() {
    if (!this.pop) { return; }
    this.pop.innerHTML = this.props.env.filterHtml(this.getContent());
  }
  tplPopover() {
    const { classnames: cx, formItem, type, name } = this.props;
    const Html = isMobile() && (formItem?.type == 'static-html' || type == 'html')
    let style = {}

    if (!isMobile() && formItem?.type == 'static-html' || type == 'html' && localStorage.getItem('textControlHtml') && typeof localStorage.getItem('textControlHtml') == 'string') {
      const textControlHtml = JSON.parse(localStorage.getItem('textControlHtml')!)
      if (textControlHtml && Array.isArray(textControlHtml) && textControlHtml.some((item: any) => item.name == name)) {
        style = textControlHtml.find((item: any) => item.name == name).style
      }
    }
    return (
      <>
        <span onClick={(e) => e.stopPropagation()} ref={this.htmlPopovers} className={cx('TplPopover', Html && 'TplStaticHtml')} style={style}>
        </span >
        {!Html &&
          <div className={cx('Footer-tplPop')} onClick={(e) => e.stopPropagation()}>
            <Button size='small' style={{ borderRadius: 5 }} onClick={() => this.setState({ visible: false, })}>
              {this.props.translate('Dialog.close')}
            </Button>
          </div>}
      </>
    )
  }
  removeHtmlTags = (html: any) => {
    if (!html) return ""
    var tempDiv = document.createElement("div");
    tempDiv.innerHTML = html;
    return tempDiv.textContent || tempDiv.innerText || "";
  }
  tplrender() {
    const {
      className,
      wrapperComponent,
      inline,
      classnames: cx,
      style,
      defaultOpen,
      detailsTitle,
      formItem,
      type,
      linkUrl,
      linkId,
      linkTitle,
      linkType,
      env,
      data
    } = this.props;
    const Component = wrapperComponent || (inline ? 'span' : 'div');
    const value = this.getContent();
    const Html = formItem?.type == 'static-html' || type == 'html'
    const prpovertit = Html || detailsTitle
    const open = isMobile() && Html
    const privateStyle = { ...style }
    privateStyle.width = ''
    const title = (!prpovertit && !defaultOpen) ? (value.includes('</font>') ? value.split('</font>')?.[1] : (value.includes('</') ? this.props.value : value)) : "";
    return <Component
      ref={this.htmlRef}
      className={cx('TplField', defaultOpen && 'TplOpen', className, open && 'OpenExpandBtn', prpovertit && 'Static-Html-TplOpen')}
      style={{ ...privateStyle }}
      onClick={() => {
        open && this.setState({ openHtml: true })
        if (linkUrl && linkId && linkTitle) {
          const handleJump = this.props.handleJump
          ModleHandleClick({
            classnames: cx,
            env, linkUrl,
            linkType: linkType ?? (handleJump ? undefined : 1),
            linkTitle,
            linkId,
            data,
            value: true,
            handleJump
          })
        }
      }}
    >
      <span title={title} >
        {prpovertit ? this.removeHtmlTags(value) : value}
      </span>
    </Component >
  }

  render() {
    const {
      classnames: cx,
      defaultOpen,
      domicile,
      formItem,
      type,
      env
    } = this.props;
    const { visible, openHtml } = this.state
    const placement = !isMobile() ? 'rightTop' : 'bottomRight';
    const primaryField = (this.props.store as any)?.primaryField
    const primaryVlaue = domicile ? domicile?.data?.[primaryField] ?? '' : ''
    const primarylable = domicile ? domicile.label : ''
    const open = isMobile() && defaultOpen && formItem?.type == 'static-html' || type == 'html'
    return (<>
      {
        defaultOpen ?
          <div className={cx('Tpltab')}>
            {
              this.tplrender()
            }
            {!isMobile() &&
              <Popover
                content={this.tplPopover()}
                trigger={'click'}
                visible={visible}
                overlayClassName={cx('TplPop')}
                getPopupContainer={env.getModalContainer}
                autoAdjustOverflow
                destroyTooltipOnHide
                placement={placement}

                onVisibleChange={(visible) => { this.setState({ visible }) }}
                title={
                  <div className={cx('Title-tplPop')} onClick={(e) => e.stopPropagation()}>
                    <div>{primarylable + ": " + (isNil(primaryVlaue) ? '' : primaryVlaue)}</div>
                    <div> <Icon icon="close" className="icon" style={{ cursor: 'pointer' }} onClick={() => this.setState({ visible: false })} /></div>
                  </div>
                }
              >
                <Icon onClick={(e: Event) => e.stopPropagation()} icon="provincial" className={[cx('TplSaving'), 'icon']} />
              </Popover>
            }
          </div>
          :
          this.tplrender()
      }
      {open &&
        < Drawer
          visible={openHtml}
          width="100%"
          className="textarea-drawer"
          closeIcon={<Icon icon='title-left' className="icon" style={{ width: '16px', height: '16px' }} />}
          onClose={() => this.setState({ openHtml: false })}
          destroyOnClose
          mask={false}
          getContainer={this.props.env.getModalContainer}
          zIndex={1011}
          title={domicile?.label ?? formItem?.labelName ?? ''}
          extra={<></>}
          footer={
            <div className='textarea-drawer-footer'>
              <Button type="primary" onClick={() => this.setState({ openHtml: false })}>
                {this.props.translate('Dialog.close')}
              </Button>
            </div>
          }
        >
          {this.tplPopover()}
        </Drawer>}
    </>

    );
  }
}

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