import React, { useEffect, useState } from 'react';

import { Form, Modal, Button, InputNumber } from 'antd';
import { SketchPicker } from 'react-color';
import styles from './ColorLinear.less';
const ColorLinear = props => {
  const { onSubumit, handleCancel, visible, color } = props;
  const [colorList, setColorList] = useState(['#F5222D', '#FA541C']);
  const [angle, setAngle] = useState(0);
  const [colorValue, setColorValue] = useState();

  const [form] = Form.useForm();
  useEffect(() => {
    if (visible) {
      let list = [...colorList];
      if (color.indexOf('linear-gradient') != -1) {
        // 渐变
        let str = color;
        let re = /\([^\)]+\)/g;
        str = str.match(re)[0];
        str = str.substring(1, str.length - 1);
        list = str.split(',');
        const a = list.shift();
        setAngle(parseInt(a));
      } else {
        list.push(color);
      }
      setColorList(list);
    } else {
      setColorList([]);
    }
  }, [visible]);
  useEffect(() => {
    if (colorList.length > 1) {
      setColorValue(`linear-gradient(${angle}deg,${colorList.join(',')})`);
    } else {
      setColorValue(colorList[0]);
    }
  }, [colorList, angle]);

  // 渐变角度切换
  const onChange = e => {
    console.log(e, 'eeeee');
    setAngle(e);
  };
  const addColor = () => {
    let list = [...colorList];
    list.push(list[list.length - 1]);
    setColorList(list);
  };
  const delColor = () => {
    let list = [...colorList];
    list.pop();
    setColorList(list);
  };
  // 颜色选择
  const colorChange = (value, index) => {
    let list = [...colorList];
    list[index] = value.hex;
    setColorList(list);
  };
  // 提交表单
  const onFinish = () => {
    onSubumit(colorValue);
    handleCancel();
  };
  console.log(angle, 'angle');
  return (
    <Modal
      title="顶部颜色配置"
      visible={visible}
      onOk={onFinish}
      width="900px"
      onCancel={handleCancel}
      maskClosable={false}
      destroyOnClose
      centered
    >
      <div className={styles.content}>
        <div className={styles.headerBox} style={{ background: colorValue }}>
          <Button onClick={addColor}>添加颜色</Button>
          <Button onClick={delColor} style={{ margin: '0 10px' }}>
            移除颜色
          </Button>
          <InputNumber min={0} max={360} value={angle} onChange={onChange} />
        </div>
        <div className={styles.colorBorderContent}>
          <div className={styles.colorContent}>
            <div className={styles.colorHeader}>
              <div className={styles.color} />
            </div>
            <div className={styles.colorBox}>
              {colorList.map((item, index) => (
                <div key={index} style={{ marginBottom: '15px' }}>
                  <SketchPicker width="230px" color={item} onChange={e => colorChange(e, index)} />
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
};
export default ColorLinear;
