import React, { Component } from 'react';
import { Select } from '@easyv/antd';
import classNames from 'classnames';
import ConfirmModal from '../../../../components/ConfirmModal';
import SortableConstantItem from './SortableConstantItem';
import styles from '../SortModal.less';

const categorys = ['常规组件', '交互组件'];
const { Option } = Select;

interface IProps {
  data: {
    type: string;
    category: string;
    moduleName: string;
  }[];
  onComplete: (orders: { name: string; list: any[] }[]) => Promise<{}>;
}

interface IState {
  loading: boolean;
  visible: boolean;
  category: string;
  orders: {
    [x: string]: any[];
  };
}

export default class extends Component<IProps, IState> {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      visible: false,
      category: '常规组件',
      orders: {}
    };
  }

  showModal = () => {
    this.setState({
      visible: true
    });
  };

  hideModal = () => {
    this.setState({
      loading: false,
      visible: false,
      category: '常规组件',
      orders: {}
    });
  };

  onCategoryChange = (value) => {
    this.setState({
      category: value
    });
  };

  moveCard = (dragIndex, hoverIndex) => {
    const { category, orders } = this.state;
    const { data } = this.props;
    const key = category;
    let prevOrders = orders[key];
    if (!prevOrders) {
      prevOrders = data.filter((d) => d.category == category);
    }
    this.setState(() => {
      let dragCard = prevOrders[dragIndex];
      let newConstantsOrder = prevOrders.concat();
      newConstantsOrder.splice(dragIndex, 1);
      newConstantsOrder.splice(hoverIndex, 0, dragCard);
      return {
        orders: {
          ...orders,
          [key]: newConstantsOrder
        }
      };
    });
  };

  onComplete = async () => {
    const { onComplete } = this.props;
    const { orders } = this.state;
    if (Object.keys(orders).length) {
      this.setState({
        loading: true
      });
      let completeOrders = Object.entries(orders).map((d) => ({ name: `mobileConstants_${d[0]}`, list: d[1].map((d) => d.uniqueTag) }));

      const result = await onComplete(completeOrders);

      this.setState({
        loading: false
      });
      if (result) {
        this.hideModal();
      }
    } else {
      this.hideModal();
    }
  };

  render() {
    const { data } = this.props;
    const { visible, category, orders, loading } = this.state;
    const key = category;
    let currentConstants: {
      type: string;
      category: string;
      moduleName: string;
    }[] = [];
    if (orders[key]) {
      currentConstants = orders[key];
    } else {
      currentConstants = data.filter((d) => d.category == category);
    }

    return (
      <span>
        <span onClick={this.showModal}>{this.props.children}</span>
        <ConfirmModal
          title="组件排序"
          visible={visible}
          footer={true}
          okText="保存"
          theme="black"
          width={700}
          onCancel={this.hideModal}
          onOk={this.onComplete}
          confirmLoading={loading}>
          <div className={styles.formItem}>
            <label className={styles.label}>
              <b className={styles.requiredIcon}>*</b>组件类别：
            </label>
            <div className={styles.field}>
              <Select value={category} onChange={this.onCategoryChange} dropdownClassName={styles.selectDrop}>
                {categorys.map((d) => (
                  <Option key={d} value={d}>
                    {d}
                  </Option>
                ))}
              </Select>
            </div>
          </div>
          <div className={styles.formItem}>
            <label className={styles.label}>
              <b className={styles.requiredIcon}>*</b>拖拽排序：
            </label>
            <div className={classNames(styles.field, styles.sort)}>
              <p className={styles.tip}>拖拽下列组件进行排序</p>
              <ul className={styles.sortContainer}>
                {currentConstants.length ? (
                  currentConstants.map((d, i) => (
                    <SortableConstantItem
                      className={styles.item}
                      key={d.moduleName}
                      index={i}
                      id={d.moduleName}
                      data={d}
                      moveCard={this.moveCard}
                    />
                  ))
                ) : (
                  <div style={{ textAlign: 'center', flex: 1, lineHeight: '100px' }}>该分类下暂无组件</div>
                )}
              </ul>
            </div>
          </div>
        </ConfirmModal>
      </span>
    );
  }
}
