import React from 'react';
import { FormItem, FormControlProps, FormBaseControl } from './Item';
import { TableCell } from '../Table';
import PopOver, { SchemaPopOver } from '../PopOver';
import QuickEdit, { SchemaQuickEdit } from '../QuickEdit';
import { Renderer } from '../../factory';
import Copyable, { SchemaCopyable } from '../Copyable';
import { extendObject, isMobile, ucFirst } from '../../utils/helper';
import omit = require('lodash/omit');
import { SchemaObject, SchemaTpl, SchemaType } from '../../Schema';

/**
 * Static
 * 文档：https://baidu.gitee.io/amis/docs/components/form/static
 */
export interface StaticExactControlSchema extends FormBaseControl {
  type: 'static';

  /**
   * 内容模板， 支持 HTML
   */
  tpl?: SchemaTpl;

  /**
   * 内容模板，不支持 HTML
   */
  text?: SchemaTpl;

  /**
   * 配置查看详情功能
   */
  popOver?: SchemaPopOver;

  /**
   * 配置快速编辑功能
   */
  quickEdit?: SchemaQuickEdit;

  /**
   * 配置点击复制功能
   */
  copyable?: SchemaCopyable;

  /**
   * 边框模式，默认是无边框的
   */
  borderMode?: 'full' | 'half' | 'none';
  /**
   * 字段名称
   */
  labelName?: string;
}

export interface StaticProps extends FormControlProps {
  placeholder?: string;
  tpl?: string;
  text?: string;
}

export default class StaticControl extends React.Component<StaticProps, any> {
  static defaultProps = {
    placeholder: '-'
  };

  constructor(props: StaticProps) {
    super(props);

    this.handleQuickChange = this.handleQuickChange.bind(this);
    // this.mouseOverAll = this.mouseOverAll.bind(this)
    // this.mouseOutAll = this.mouseOutAll.bind(this)
    // this.state = {
    //   hemlset: null,
    // }
  }

  async handleQuickChange(values: any, saveImmediately: boolean | any) {
    const { onBulkChange, onAction, data } = this.props;

    if (saveImmediately && saveImmediately.api) {
      await onAction(
        null,
        {
          actionType: 'ajax',
          api: saveImmediately.api
        },
        extendObject(data, values),
        true
      );
    }

    onBulkChange && onBulkChange(values, saveImmediately === true);
  }

  // mouseOverAll(e: any) {
  //   const { type, value } = this.props
  //   const curr = e.currentTarget;
  //   const currChildren = curr.childNodes[0];
  //   const currChildrenHtml = type == 'static-html' || type == 'html'

  //   const style = {
  //     top: e.pageY,
  //     left: e.pageX
  //   }

  //   // 判断当前的宽度和实际的宽度对比判断是否有省略号
  //   if (currChildren.scrollWidth > currChildren.clientWidth) {
  //     let htmlset = null
  //     htmlset = (
  //       <div className={this.props.classnames(`Form-static-pop`)} style={style}>
  //         {!!currChildrenHtml ? <div dangerouslySetInnerHTML={{
  //           __html: value
  //         }} /> : value}
  //       </div>
  //     )
  //     this.setState({
  //       hemlset: htmlset,
  //     });
  //   }
  // }
  // mouseOutAll(e: any) {
  //   this.setState({
  //     hemlset: null
  //   });
  // }
  render() {
    const {
      className,
      value,
      label,
      type,
      render,
      children,
      data,
      classnames: cx,
      name,
      disabled,
      $schema,
      defaultValue,
      borderMode,
      ...rest
    } = this.props;

    const subType = /^static/.test(type)
      ? type.substring(7) || (rest.tpl ? 'tpl' : 'plain')
      : type;

    const field = {
      label,
      name,
      ...$schema,
      type: subType
    };

    return (
      <div
        className={cx('Form-static', {
          [`Form-static--border${ucFirst(borderMode)}`]: borderMode
        })}
      >
        <StaticFieldRenderer
          {...{
            ...(rest as any),
            name,
            render,
            field,
            value: value,
            className,
            onQuickChange: this.handleQuickChange,
            data,
            disabled,
            classnames: cx,
            // mouseOverAll: this.mouseOverAll,
            // mouseOutAll: this.mouseOutAll,
            // hemlset: this.state.hemlset
          }}

        />
      </div>
    );
  }
}

@FormItem({
  test: /(^|\/)static(\-[^\/]+)?$/,
  weight: -90,
  strictMode: false,
  sizeMutable: false,
  name: 'static'
})
export class StaticControlRenderer extends StaticControl { }

@QuickEdit()
@PopOver({
  position: 'right'
})
@Copyable()

export class StaticFieldRenderer extends TableCell {

  static defaultProps = {
    ...TableCell.defaultProps,
    wrapperComponent: 'div',
  };

  render() {
    let {
      type,
      className,
      render,
      style,
      wrapperComponent: Component,
      labelClassName,
      value,
      data,
      children,
      body: nBody,
      width,
      inputClassName,
      label,
      tabIndex,
      onKeyUp,
      field,
      // mouseOverAll,
      // mouseOutAll,
      // hemlset,
      ...rest
    } = this.props;


    const schema = {
      ...field,
      className: inputClassName,
      type: (field && field.type) || 'plain'
    };

    let body = nBody
      ? render('field', nBody)
      : render('field', schema, {
        ...omit(rest, Object.keys(schema)),
        value,
        data
      });

    if (width) {
      style = style || {};
      style.width = style.width || width;
    }

    if (!Component) {
      return body as JSX.Element;
    }

    return (
      <Component
        style={style}
        className={className}
        tabIndex={tabIndex}
        onKeyUp={onKeyUp}
        // onMouseEnter={(e: any) => { !isMobile() && mouseOverAll(e) }}
        // onMouseLeave={(e: any) => { !isMobile() && mouseOutAll(e) }}
        title={value}
      >
        {body}
        {/* {hemlset} */}
      </Component>
    );
  }
}
