import React, { useState, useContext, useMemo, useEffect } from 'react';
import { Select } from '@easyv/react-gui';
import styles from './DataBox.less';
import AceEditorBox from './AceEditorBox';
import message from 'components/message';
import { Tag } from '@easyv/antd';
import { connect } from 'react-redux';
import { bindContainer } from 'models/component';
import Tooltip from 'components/EasyvTooltip';
import { DataContext } from '../RightZoneBar/DataBox/Context/index';
import { getScreenId } from 'utils/screen';
import { addDataContainer } from 'models/data-container';
import difference from 'lodash/difference';
import { getTopScreenId } from 'utils/screen';
import { QuestionCircleOutlined } from '@easyv/react-icons';
import EasyvEmpty from 'components/EasyvEmpty';

const { Option } = Select;
// 容器最多只能选择10个 / 组件
const MAX_SELECT_NUM = 10;

function DataBox({
  dataList,
  bindContainer,
  filterResult,
  dataContainers = [],
  addDataContainer
}: {
  dataList: any[];
  filterResult: {
    [x: string]: any;
  };
  dataContainers: any[];
  bindContainer: (body) => any;
  addDataContainer: () => any;
}) {
  const { onSetEdit } = useContext(DataContext);
  const [activeTab, setActiveTab] = useState('');
  const [lock, setLock] = useState(false);
  const [vessels, setVessel] = useState<string[]>([]);

  useEffect(() => {
    setVessel(dataContainers.map((d) => d.id + ''));
    dataContainers?.length && setActiveTab(dataContainers[0].id);
  }, [dataContainers]);

  const children = useMemo(() => {
    return dataList.map((d) => (
      <Option key={d.id} title={d.name} className={styles.option}>
        {d.name}
      </Option>
    ));
  }, [dataList]);

  const tagRender = (props) => {
    const { label, value } = props;
    const onPreventMouseDown = (event) => {
      if (['svg', 'path'].includes(event.target.tagName)) {
        event.preventDefault();
        event.stopPropagation();
      }
    };
    return (
      <Tooltip title={label} placement="top">
        <Tag
          closable
          onMouseDown={onPreventMouseDown}
          onClose={() => {
            const _vessels = vessels.filter((d) => d != value);
            setBindContainer(value);
            setVessel(_vessels);
            _vessels.length ? setActiveTab(_vessels[_vessels.length - 1]) : setActiveTab('');
          }}>
          <span>{label}</span>
        </Tag>
      </Tooltip>
    );
  };

  const setBindContainer = (containerId, binding = false) => {
    const screenId = getScreenId();
    return bindContainer({
      screenId: screenId,
      containerId: +containerId,
      binding
    });
  };

  const onEditChange = () => {
    onSetEdit({
      type: 'edit',
      data: dataList.find((d) => d.id === +activeTab)
    });
  };

  const handleChange = async (value) => {
    if (value.length > MAX_SELECT_NUM) {
      message.warning('数据容器选择超出最大限制');
      return;
    }
    let result = null;
    const containerId = value[value.length - 1];
    if (value.length < vessels.length) {
      // 取消了
      const [diffValue] = difference(vessels, value);
      result = await setBindContainer(diffValue, false);
    } else {
      result = await setBindContainer(containerId, true);
    }
    if (result) {
      setActiveTab(containerId); // json 面板选中
      setVessel(value);
    }
  };

  const onAdd = async () => {
    // onAdd
    if (lock) {
      // +🔒
      return;
    }
    const hide = message.loading('创建中...', 0);
    const result = await addDataContainer();
    hide();
    result &&
      onSetEdit({
        type: 'create',
        data: result
      });
    setLock(false);
  };
  // 当前组件/控件 过滤器
  const resultData = filterResult?.[activeTab] || {};
  const aceEditorProps = {
    readOnly: true,
    height: '210px',
    value: JSON.stringify(resultData, null, '\t')
  };

  if (activeTab) {
    aceEditorProps['onEditChange'] = onEditChange;
  }

  return (
    <div className={styles.dataBox}>
      <div className={styles.dataBoxHeader}>
        <span>
          数据容器
          <Tooltip placement="top" title="当绑定多个数据容器时，默认以数组格式返回数据">
            <QuestionCircleOutlined className={styles.tooltip} />
          </Tooltip>
        </span>
        {/* 最多选择10个 */}
        <Select
          mode="tags"
          notFoundContent={
            <div style={{ margin: '40px 0' }}>
              <EasyvEmpty />
            </div>
          }
          tagRender={tagRender}
          value={vessels}
          placeholder="请选择数据容器"
          onChange={handleChange}>
          {children}
        </Select>
        <div className={styles.addIcon} onClick={onAdd}>
          <i className="icon iconfont icon-icon_add"></i>
        </div>
      </div>
      {vessels.length ? (
        <ul className={styles.tabs}>
          {vessels.map((d) => {
            const current = dataList.find((v) => v.id == d);
            if (!current) {
              return null;
            }
            return (
              <Tooltip key={d} title={current.name} placement="top">
                <li
                  onClick={() => {
                    setActiveTab(d);
                  }}
                  className={activeTab == d ? styles.active : ''}>
                  {current.name}
                </li>
              </Tooltip>
            );
          })}
        </ul>
      ) : null}
      <AceEditorBox {...aceEditorProps} />
    </div>
  );
}

function mapStateToProps({ dataContainers }) {
  const { filterResult, list } = dataContainers;
  const screenId = getTopScreenId();

  return {
    dataList: list.filter((d) => d.screenId === screenId),
    filterResult
  };
}

export default connect(mapStateToProps, {
  bindContainer,
  addDataContainer
})(DataBox);
