/* eslint-disable no-param-reassign */
import React, { useState, useEffect } from 'react';
import { omit } from 'lodash';
import {
  Form,
  InputNumber,
  Slider,
  Collapse,
  Row,
  Col,
  Modal,
  Tag,
  message,
} from 'antd';
import produce from 'immer';
import {
  PlusOutlined,
  RightSquareFilled,
  LeftSquareFilled,
  ExclamationCircleOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons';
import { findValuesByNamePath, guid } from '../../../utils';

import './index.less';

const { confirm } = Modal;
const { Panel } = Collapse;
export default ({ propKey, config, node = {}, onChange }) => {
  const monitor = node[propKey];
  const [state, setState] = useState({});
  const [stateChildren, setStateChildren] = useState([]);
  const { name, label } = config;
  const { rowCells = 1, gutter = [0, 0] } = findValuesByNamePath(name, state);
  const normalSpan = 24 / rowCells;
  const span = normalSpan < 6 ? 6 : normalSpan;
  const colCounts = {};
  const colCountsArry = [1, 2, 3, 4, 6, 8, 12];
  colCountsArry.forEach((value, i) => {
    colCounts[i] = value;
  });
  const colCountsIndex = colCountsArry.findIndex(p => p === rowCells);

  const updateNodeChildren = nodeChildren => {
    setStateChildren(nodeChildren);
    const storeChildren = nodeChildren.map(item => {
      return omit(item, ['sortName']);
    });
    onChange('children', storeChildren, true);
  };

  const handleGutterChange = (e, index) => {
    const result = [...gutter];
    result[index] = e;
    const nextState = produce(state, draft => {
      draft[name.gutter] = result;
    });
    setState(nextState);
    onChange(name.gutter, result);
  };

  const handleColCountChange = colCountKey => {
    const nextState = produce(state, draft => {
      draft[name.rowCells] = colCounts[colCountKey];
    });
    setState(nextState);
    onChange(name.rowCells, colCounts[colCountKey]);
  };

  const handleDelCell = index => {
    confirm({
      title: '系统提示',
      icon: <ExclamationCircleOutlined />,
      content: '确认删除该项?',
      onOk() {
        const nextChildren = produce(stateChildren, draft => {
          draft.splice(index, 1);
        });
        updateNodeChildren(nextChildren);
      },
    });
  };

  const getMaxSortIndex = () => {
    if (!stateChildren.length) {
      return 0;
    }
    const sortNameList = stateChildren.map(item => {
      return item.sortName;
    });
    sortNameList.sort((a, b) => {
      return b - a;
    });
    return sortNameList[0];
  };

  const handleAddCell = () => {
    const sortName = getMaxSortIndex() + 1;
    const newChild = {
      type: 'VerLayout',
      id: guid(),
      style: {
        width: '100%',
      },
      props: {},
      pid: node.id,
      children: [],
      sortName,
    };
    const nextChildren = produce(stateChildren, draft => {
      draft.push(newChild);
    });
    updateNodeChildren(nextChildren);
  };

  const handleChangeCellIndex = (index, direction) => {
    if (direction === -1) {
      if (index < 1) {
        message.warning('已经是最前面');
        return;
      }
    }
    if (direction === 1) {
      if (index >= stateChildren.length - 1) {
        message.warning('已经是最后面');
        return;
      }
    }
    const nextChildren = produce(stateChildren, draft => {
      [draft[index], draft[index + direction]] = [
        draft[index + direction],
        draft[index],
      ];
    });
    updateNodeChildren(nextChildren);
    message.success('操作成功');
  };

  useEffect(() => {
    setState(monitor || {});
    const children = node.children.map((item, index) => {
      return {
        ...item,
        sortName: index + 1,
      };
    });
    setStateChildren(children);
  }, [monitor]);

  return (
    <Collapse style={{ width: '100%' }} defaultActiveKey={['1']}>
      <Panel header={`设置${label}`} key="1">
        <Form.Item>
          <Row gutter={[5, 5]}>
            {stateChildren.map((child, index) => {
              return (
                <Col span={span} key={index.toString()}>
                  <div className="drawer-grid-item">
                    {`块${child.sortName}`}
                    <div
                      className="drawer-grid-item__close"
                      onClick={() => handleDelCell(index)}
                    >
                      <CloseCircleOutlined />
                    </div>
                    {index > 0 && (
                      <div
                        className="drawer-grid-item__left"
                        onClick={() => handleChangeCellIndex(index, -1)}
                      >
                        <LeftSquareFilled />
                      </div>
                    )}
                    {index < stateChildren.length - 1 && (
                      <div
                        className="drawer-grid-item__right"
                        onClick={() => handleChangeCellIndex(index, 1)}
                      >
                        <RightSquareFilled />
                      </div>
                    )}
                  </div>
                </Col>
              );
            })}
          </Row>
          <Tag onClick={handleAddCell}>
            <PlusOutlined /> 新增
          </Tag>
          <div className="cell-row pudge-grid-row-cells">
            <div className="cell-row__lable">每行格数</div>
            <Slider
              style={{ width: 200 }}
              min={0}
              max={Object.keys(colCounts).length - 1}
              value={colCountsIndex}
              onChange={handleColCountChange}
              marks={colCounts}
              step={null}
              tipFormatter={value => colCounts[value]}
            />
          </div>
          <div className="cell-row">
            <div className="cell-row__lable">左右间距</div>
            <InputNumber
              defaultValue={gutter[0]}
              value={gutter[0]}
              onChange={e => handleGutterChange(e, 0)}
            />
          </div>
          <div className="cell-row">
            <div className="cell-row__lable">上下间距</div>
            <InputNumber
              defaultValue={gutter[1]}
              value={gutter[1]}
              onChange={e => handleGutterChange(e, 1)}
            />
          </div>
        </Form.Item>
      </Panel>
    </Collapse>
  );
};
