import React, { useContext, useState, useRef, useEffect, useMemo } from 'react';
import styles from '../index.less';
import dataStyle from './data.less';
import { Drawer, Collapse, Input } from '@easyv/react-gui';
import classnames from 'classnames';
import ComponentDataSource from './ComponentDataSource';
import { DataContext } from './Context/index';
import { ComponentItem } from 'models/component.types';
import { getContainerWithUsedComponents } from 'utils/containers';
import { connect } from 'react-redux';
import message from 'components/message';
import { Tooltip } from '@easyv/antd';
// import CustomEvent from 'containers/screen-edit/components/ScreenConfig/CustomEvent';
import { updateDataContainer, dataUpdateEvents } from 'models/data-container';
import { selectComponentWithId } from 'models/create-app';
import { useHistory } from 'react-router-dom';
import { Course } from 'models/course.types';

const title = (
  <div className={dataStyle.title}>
    <span>数据容器</span>
  </div>
);

function Data({
  visible,
  zIndex = 1000,
  mask = false,
  course,
  updateDataContainer,
  dataUpdateEvents,
  componentsById,
  isFilterOpen = true,
  selectComponentWithId
}: {
  visible: boolean;
  zIndex?: number;
  course: {
    [id: string]: any;
  };
  componentsById: ComponentItem;
  mask?: boolean;
  isFilterOpen?: boolean;
  updateDataContainer: (x: number, y: any) => any;
  dataUpdateEvents: (x: any) => void;
  selectComponentWithId: (id, history) => void;
}) {
  const { onOpenFilter, onSetEdit, editItem } = useContext(DataContext);
  const [inputVal, setInput] = useState('');
  const [isEditName, setEditName] = useState(false);
  const inputRef: any = useRef(null);
  const history = useHistory();
  const isOpen = editItem && editItem?.type !== 'close';


  // useEffect(()=>{
  //   onOpenFilter({
  //     type: 'close',
  //   });
  // },[visible])


  useEffect(() => {
    if (editItem?.type === 'create') {
      onDoubleClick();
    }
    const { name } = editItem?.data || {};
    name && setInput(name);
  }, [editItem]);

  const onDoubleClick = () => {
    setEditName(true);
    setTimeout(() => {
      inputRef.current?.focus();
    }, 0);
  };

  const onBlur = async () => {
    if (!inputVal) {
      message.warning('请输入有效名');
    } else {
      const { name, id } = editItem?.data || {};
      if (id && inputVal !== name) {
        const hide = message.loading('更新中...', 0);
        const result = await updateDataContainer(id, {
          name: inputVal
        });
        if (result) {
          setInput('');
        }
        hide();
      }
    }
    setEditName(false);
  };

  // const { dataConfigs, events, triggers } = getEvent;
  const _getContainerWithUsedComponents = useMemo(() => {
    if (!editItem?.data) {
      return [];
    }
    return getContainerWithUsedComponents({
      id: editItem.data.id,
      componentsById
    });
  }, [editItem, componentsById]);

  const tooltipTitle = useMemo(() => {
    return (
      <>
        <div className={dataStyle.tooltipTitle}>
          {_getContainerWithUsedComponents.map((d) => (
            <span
              key={d.id}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                selectComponentWithId(d.id, history);
              }}>{`${d.name}_${d.id}`}</span>
          ))}
        </div>
      </>
    );
  }, [_getContainerWithUsedComponents]);

  // 教程
  const _course = course[Course.DATA_CONTAINERS];

  return (
    <Drawer
      className={`${styles.drawer} ${dataStyle.filter}`}
      title={title}
      placement="right"
      visible={visible}
      zIndex={zIndex}
      mask={mask}
      width={334}
      closable={false}>
      {visible && (
        <div>
          <div className={dataStyle.list} id="data-container-config" style={{ maxHeight: 'calc(100vh - 100px)' }}>
            <div className={dataStyle.header}>
              <div className={dataStyle.row}>
                <i
                  className="icon iconfont icon-btn_arrowsleft"
                  onClick={() => {
                    onSetEdit();
                  }}></i>
                {isEditName ? (
                  <span style={{ display: 'inline-block' }}>
                    <Input
                      ref={inputRef}
                      onBlur={onBlur}
                      onPressEnter={onBlur}
                      maxLength={20}
                      onChange={(e) => {
                        const val = e.target.value.trim();
                        setInput(val);
                      }}
                      value={inputVal}
                    />
                  </span>
                ) : (
                  <Tooltip title={editItem?.data.name}>
                    <span className={dataStyle.name} onDoubleClick={onDoubleClick}>
                      {editItem?.data.name}
                    </span>
                  </Tooltip>
                )}
                {_course && (
                  <span className={dataStyle.link}>
                    <a target="_blank" style={{ color: '#fff' }} href={_course.courseUrl}>
                      查看教程
                    </a>
                  </span>
                )}
              </div>
              {_getContainerWithUsedComponents.length ? (
                <div className={classnames(dataStyle.tip)}>
                  <Tooltip title={tooltipTitle}>
                    <span>{_getContainerWithUsedComponents.length}个组件正在使用</span>
                  </Tooltip>
                </div>
              ) : null}
            </div>
            <Collapse activeKey={[1]} header={'数据源'}>
              {isOpen ? <ComponentDataSource  /> : null}
            </Collapse>
            {/* {dataConfigs && events && triggers && (
            <CustomEvent dataUpdateEvents={dataUpdateEvents} events={events} triggers={triggers} staticConfig={dataConfigs.static} />
          )} */}
          </div>
        </div>
      )}
    </Drawer>
  );
}

const mapStateToProps = ({ componentsById, course }) => {
  return {
    componentsById,
    course
  };
};

export default connect(mapStateToProps, {
  updateDataContainer,
  dataUpdateEvents,
  selectComponentWithId
})(Data);
