import {
  ReactVisualEditorBlock,
  ReactVisualEditorConfig,
  ReactVisualEditorValue,
} from './ReactVisualEditor.utils';
import React, { useEffect, useState } from 'react';
import deepcopy from 'deepcopy';
import styles from './ReactVisualEditor.less';
import { Button, Form, Input, InputNumber, Select } from 'antd';
import {
  ReactVisualEditorProps,
  ReactVisualEditorPropsType,
  createColorProp,
} from './ReactVisualEditor.props';
import { SketchPicker } from 'react-color';
import { TablePropEditor } from './TablePropEditor/TablePropEditor';
import { getHookState } from './../hook/getHookState';
const { TextArea } = Input;
export const ReactVisualOperator: React.FC<{
  selectBlock?: ReactVisualEditorBlock;
  value: ReactVisualEditorValue;
  config: ReactVisualEditorConfig;
  updateValue: (val: ReactVisualEditorValue) => void;
  updateBlock: (newBlock: ReactVisualEditorBlock, oldBlock: ReactVisualEditorBlock) => void;
}> = (props) => {
  const [editData, setEditData] = useState({} as any);

  const [form] = Form.useForm();

  useEffect(() => methods.reset(), [props.selectBlock]);

  const methods = {
    apply: async () => {
      const editData: any = await getHookState(setEditData);
      if (!props.selectBlock) {
        /*更新value*/
        props.updateValue({
          ...props.value,
          container: { ...editData, themeColor: editData.props?.containerThemeColor?.hex
          },
        });
      } else {
        /*更新block*/
        props.updateBlock(deepcopy(editData), props.selectBlock);
      }
    },
    reset: () => {
      let data: any;
      if (!props.selectBlock) {
        data = deepcopy(props.value.container);
      } else {
        data = deepcopy(props.selectBlock);
      }
      setEditData(data);
      form.resetFields();
      form.setFieldsValue(data);
    },
    onFormValuesChange: (changeValues: any, values: any) => {
      setEditData({
        ...editData,
        ...values,
      });
    },
  };

  let render: JSX.Element[] = [];
  if (!props.selectBlock) {
    /*编辑容器属性*/
    // render.push(
    //   <Form.Item label="宽度" name="width" key="container-width">
    //     <InputNumber step={100} min={0} precision={0} />
    //   </Form.Item>,
    // );
    // render.push(
    //   <Form.Item label="高度" name="height" key="container-height">
    //     <InputNumber step={100} min={0} precision={0} />
    //   </Form.Item>,
    // );
    // /**主题色 */
    // render.push(renderEditor('containerThemeColor', createColorProp('主题色'), methods.apply));
    render.push(
      <Form.Item label={ <span style={{color:'#fff'}}> 主题背景图</span>} name="backgroundImage" key="container-themeImage">
        <Input />
      </Form.Item>,
    );
  } else {
    /*编辑block属性*/
    const component = props.config.componentMap[props.selectBlock.componentKey];
    if (component) {
      // render.push(
      //   <Form.Item label="组件标识" name="slotName" key="slotName">
      //     <Input />
      //   </Form.Item>,
      // );
      render.push(
        ...Object.entries(component.props || {}).map(([propName, propConfig]) =>
          renderEditor(propName, propConfig, methods.apply),
        ),
      );
      render.push(
        ...Object.entries(component.model || {}).map(([modelProp, modelName]) => (
          <Form.Item label={modelName} name={['model', modelProp]} key={`model_${modelProp}`}>
            <Input />
          </Form.Item>
        )),
      );
    }
  }

  return (
    <div className={styles.reactVisualEditorOperator}>
      <div className={styles.reactVisualEditorOperatorTitle} style={{color:'#fff', fontSize:'25px',marginBottom:'20px'}}>
        {!!props.selectBlock ? '编辑元素' : '编辑容器'}
      </div>
      <Form layout="vertical" form={form} onValuesChange={methods.onFormValuesChange}>
        {render}
        <Form.Item key="operator">
          <Button type="primary" onClick={methods.apply} style={{ marginRight: '8px' }}>
            应用
          </Button>
          <Button onClick={methods.reset}>重置</Button>
        </Form.Item>
      </Form>
    </div>
  );
};

function renderEditor(propsName: string, propsConfig: ReactVisualEditorProps, apply: () => void) {
  switch (propsConfig.type) {
    case ReactVisualEditorPropsType.text:
      return (
        <Form.Item label={ <span style={{color:'#fff'}}> {propsConfig.name}</span>}  name={['props', propsName]} key={`props_${propsName}`}>
          <Input  style={{background:'#aaa',color:'#fff'}}/>
        </Form.Item>
      );
    case ReactVisualEditorPropsType.textarea:
      return (
        <Form.Item  label={ <span style={{color:'#fff'}}> {propsConfig.name}</span>} name={['props', propsName]} key={`props_${propsName}`}>
          <TextArea />
        </Form.Item>
      );
    case ReactVisualEditorPropsType.select:
      return (
        <Form.Item  label={ <span style={{color:'#fff'}}> {propsConfig.name}</span>} name={['props', propsName]} key={`props_${propsName}`}>
          <Select>
            {propsConfig.options.map((opt, index) => (
              <Select.Option value={opt.value} key={index}>
                {opt.label}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
      );
    case ReactVisualEditorPropsType.color:
      return (
        <Form.Item label={propsConfig.name} name={['props', propsName]} key={`props_${propsName}`}>
          <SketchPicker />
        </Form.Item>
      );
    case ReactVisualEditorPropsType.table:
      return (
        <Form.Item  label={ <span style={{color:'#fff'}}> {propsConfig.name}</span>} name={['props', propsName]} key={`props_${propsName}`}>
          <TablePropEditor config={propsConfig} onChange={() => setTimeout(apply)} />
        </Form.Item>
      );
  }
}
