import React, { useEffect } from 'react';
import ModuleForm from './ModuleForm';
import {
  getModuleList,
  TMarketingMixConfig,
} from 'editorComponents/BasicShop/BasicComponents/MarketingMix/schema';
import styled from 'styled-components';
import Button from 'antd/es/button';
import { ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';
import _ from 'lodash';

export interface IModuleListProps {
  onChange?: (v: any) => void;
  value?: TMarketingMixConfig['moduleList'];
  theme?: TMarketingMixConfig['theme'];
}

const ModuleList: React.FC<IModuleListProps> = (props) => {
  const num = props.theme === 'fourInARow' ? 4 : 2;

  const onChange = (idx: number, value: any) => {
    const data = props?.value?.map((item, i) => {
      if (i === idx) {
        return value;
      }
      return item;
    });
    props?.onChange?.(data);
  };

  /**
   * 向下移动
   * @param idx
   * @returns
   */
  const onDown = (idx: number) => {
    if (props?.value === undefined) {
      return;
    }

    // 当前最后一个
    if (idx === num-1 && props.theme === 'fourInARow') {
      swap(0, num-1);
      return;
    }
    // 当前最后一个且只有两个模块，交换即可
    if (idx === 1 && props.theme === 'twoInARow') {
      swap(0, 1);
      return;
    }

    swap(idx, idx + 1);
  };

  /**
   * 向上移动
   * @param idx
   * @returns
   */
  const onUp = (idx: number) => {
    if (props?.value === undefined) {
      return;
    }

    // 当前是第一个
    if (idx === 0 && props.theme === 'fourInARow') {
      swap(0, num-1);
      return;
    }

    // 当前第一个且只有两个模块，交换即可
    if (idx === 0 && props.theme === 'twoInARow') {
      swap(0, 1);
      return;
    }

    swap(idx, idx - 1);
  };

  function swap(current: number, next: number) {
    if (props?.value === undefined) {
      return;
    }
    const newData = _.clone(props.value);
    const temp = newData[current];
    newData[current] = newData[next];
    newData[next] = temp;
    props?.onChange?.(newData);
  }

  return (
    <div>
      {props?.value?.slice(0, num).map((item, idx) => {
        return (
          <>
            <Title>
              <h3>{`模块${idx + 1}`}</h3>
              <div>
                <Button size="small" onClick={() => onUp(idx)}>
                  <ArrowUpOutlined />
                </Button>{' '}
                <Button size="small" onClick={() => onDown(idx)}>
                  <ArrowDownOutlined />
                </Button>
              </div>
            </Title>
            <ModuleForm
              key={idx}
              theme={props.theme}
              data={item}
              onChange={(value) => {
                onChange(idx, { ...item, ...value });
              }}
            />
          </>
        );
      })}
    </div>
  );
};

const Title = styled.div`
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 20px;
`;

export default ModuleList;
