import React from 'react';
import { Renderer, RendererProps } from '../factory';
import { BaseSchema, SchemaTpl } from '../Schema';
import { autobind, createObject, getPropValue } from '../utils/helper';
import { filter } from '../utils/tpl';
import { BadgeSchema, withBadge } from '../components/Badge';
import Link from '../components/Link';
import styled from 'styled-components';

const WrapperHref = styled(Link)`
// 宽度超出200显示省略号
  max-width:calc(200px - 1.25rem);
  display:inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
`

/**
 * Link 链接展示控件。
 * 文档：https://baidu.gitee.io/amis/docs/components/link
 */
export interface LinkSchema extends BaseSchema {
  /**
   * 指定为 link 链接展示控件
   */
  type: 'link';

  /**
   * 是否新窗口打开。
   */
  blank?: boolean;

  /**
   * 链接内容，如果不配置将显示链接地址。
   */
  body?: SchemaTpl;

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

  /**
   * a标签原生target属性
   */
  htmlTarget?: string;

  /**
   * 图标
   */
  icon?: string;

  /**
   * 右侧图标
   */
  rightIcon?: string;
}

export interface LinkProps
  extends RendererProps,
  Omit<LinkSchema, 'type' | 'className'> { }

export class LinkCmpt extends React.Component<LinkProps, object> {
  static defaultProps = {
    blank: true,
    disabled: false,
    htmlTarget: ''
  };

  async handleClick(href: string) {
    const { env, blank, body, dispatchEvent, data } = this.props;
    env?.tracker(
      {
        eventType: 'url',
        // 需要和 action 里命名一致方便后续分析
        eventData: { url: href, blank, label: body }
      },
      this.props
    );
    // 触发渲染器事件
    const rendererEvent = await dispatchEvent(
      'click',
      createObject(data, {
        // 注意：每个组件都必须把数据链带上
        url: href,
        blank,
        label: body
      })
    );

    // 阻止原有动作执行
    if (rendererEvent?.prevented) {
      return;
    }
  }

  getHref() { }

  render() {
    const {
      className,
      body,
      href,
      classnames: cx,
      blank,
      disabled,
      htmlTarget,
      data,
      render,
      translate: __,
      title,
      icon,
      rightIcon
    } = this.props;

    let value =
      (typeof href === 'string' && href
        ? filter(href, data, '| raw')
        : undefined) || getPropValue(this.props);

    return (
      <WrapperHref
        className={className}
        href={value}
        disabled={disabled}
        title={title}
        htmlTarget={htmlTarget || (blank ? '_blank' : '_self')}
        icon={icon}
        rightIcon={rightIcon}
      >
        {body ? render('body', body) : value || __('link')}
      </WrapperHref>
    );
  }
}

@Renderer({
  type: 'link'
})
// @ts-ignore 类型没搞定
@withBadge
export class LinkFieldRenderer extends LinkCmpt { }
