import React, { memo, RefObject, useEffect } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Select, InputNumber, Input, Switch, Radio } from 'antd';
import Upload from './FormComponents/Upload';
import DataList from './FormComponents/DataList';
import ImageSource from './FormComponents/ImageSource';
import ImageListJustOne from './FormComponents/ImageListJustOne';
import MutiText from './FormComponents/MutiText';
import Color from './FormComponents/Color';
import CardPicker from './FormComponents/CardPicker';
import Table from './FormComponents/Table';
import Pos from './FormComponents/Pos';
import { Store } from 'antd/lib/form/interface';
import RichText from './FormComponents/XEditor';
import FormItems from './FormComponents/FormItems';
import ImageList from './FormComponents/ImageList';
import ImageList1 from './FormComponents/ImageList1';
import ProductList from './FormComponents/ProductList';
import { useParams } from 'react-router';
import { getUrlParamByKey } from 'editorUtils';
import ChooseCoupon from './FormComponents/ChooseCoupon';
import CouponTemplate from 'editorComponents/BasicShop/BasicComponents/CouponTemplate';
import CouponTemplateType from './FormComponents/CouponTemplateType';
import ModuleList from './FormComponents/ModuleList';
const normFile = (e: any) => {
  // console.log('Upload event:', e);
  if (Array.isArray(e)) {
    //待修改
    return e;
  }
  return e && e.fileList;
};

const { Option } = Select;
const { TextArea } = Input;

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

interface FormEditorProps {
  uid: string;
  onSave: Function;
  onDel: Function;
  defaultValue: { [key: string]: any };
  config: Array<any>;
  rightPannelRef: RefObject<HTMLDivElement>;
  form: any;
}

export const ImgWithContext = React.createContext(0);

const FormEditor = (props: FormEditorProps) => {
  const { config, defaultValue, onSave, uid, rightPannelRef, form } = props;
  const mode = getUrlParamByKey('mode');

  const { getFieldDecorator, validateFieldsAndScroll, setFieldsValue, getFieldsValue } = form;

  useEffect(() => {
    return () => {
      form.resetFields();
    };
  }, [uid, form]);

  return (
    <Form form={form} name={`form_editor`} {...formItemLayout}>
      {config.map((item, i) => {
        return (
          <React.Fragment key={i}>
            {item.type === 'Number' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(
                  <InputNumber
                    formatter={(num) => Math.floor(num) + ''}
                    min={item?.range?.[0]}
                    max={item?.range?.[1]}
                  />,
                )}
              </Form.Item>
            )}
            {item.type === 'Text' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(<Input />)}
              </Form.Item>
            )}
            {item.type === 'TextArea' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(<TextArea rows={4} />)}
              </Form.Item>
            )}
            {item.type === 'MutiText' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(<MutiText />)}
              </Form.Item>
            )}
            {item.type === 'DataList' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(<DataList cropRate={item.cropRate} />)}
              </Form.Item>
            )}
            {item.type === 'ImageList' && mode === 'miniApp' && (
              <ImgWithContext.Provider value={item?.data?.imgWidth}>
                <Form.Item label={item.name}>
                  {getFieldDecorator(item.key, {
                    initialValue: defaultValue[item.key],
                  })(<ImageList1 cropRate={item.cropRate} />)}
                </Form.Item>
              </ImgWithContext.Provider>
            )}
            {item.type === 'ProductList' && mode === 'miniApp' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(<ProductList cropRate={item.cropRate} />)}
              </Form.Item>
            )}

            {item.type === 'ImageList' && mode !== 'miniApp' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(<ImageList cropRate={item.cropRate} />)}
              </Form.Item>
            )}

            {item.type === 'ImageListJustOne' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(<ImageListJustOne cropRate={item.cropRate} />)}
              </Form.Item>
            )}
            {item.type === 'ImageSource' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(<ImageSource cropRate={item.cropRate} />)}
              </Form.Item>
            )}
            {item.type === 'ModuleList' && (
              <Form.Item labelCol={{span: 24}} wrapperCol={{span:24}} label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(<ModuleList theme={defaultValue["theme"]}/>)}
              </Form.Item>
            )}
            {item.type === 'Color' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(<Color />)}
              </Form.Item>
            )}

            {item.type === 'Select' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(
                  <Select placeholder="请选择">
                    {item.range.map((v: any, i: number) => {
                      return (
                        <Option value={v.key} key={i}>
                          {v.text}
                        </Option>
                      );
                    })}
                  </Select>,
                )}
              </Form.Item>
            )}
            {item.type === 'Radio' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(
                  <Radio.Group>
                    {item.range.map((v: any, i: number) => {
                      return (
                        <Radio value={v.key} key={i}>
                          {v.text}
                        </Radio>
                      );
                    })}
                  </Radio.Group>,
                )}
              </Form.Item>
            )}
            {item.type === 'Switch' && (
              <Form.Item labelCol={{ span: 8 }} wrapperCol={{ span: 14 }} label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                  valuePropName: 'checked',
                })(<Switch />)}
              </Form.Item>
            )}
            {item.type === 'Upload' && (
              <Form.Item label={item.name} key={Math.random()}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                  valuePropName: 'fileList',
                  getValueFromEvent: normFile,
                })(<Upload cropRate={item.cropRate} isCrop={item.isCrop} />)}
              </Form.Item>
            )}
            {item.type === 'CardPicker' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                  valuePropName: 'type',
                })(<CardPicker icons={item.icons} type={defaultValue['type']} />)}
              </Form.Item>
            )}
            {item.type === 'Table' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                  valuePropName: 'data',
                })(<Table data={item.data} />)}
              </Form.Item>
            )}
            {item.type === 'Pos' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(<Pos />)}
              </Form.Item>
            )}
            {item.type === 'FormItems' && (
              <Form.Item>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                  valuePropName: 'formList',
                })(
                  <FormItems
                    canAddItem={item?.canAddItem}
                    data={item.data}
                    rightPannelRef={rightPannelRef}
                  />,
                )}
              </Form.Item>
            )}
            {item.type === 'RichText' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(<RichText />)}
              </Form.Item>
            )}
            {item.type === 'CouponTemplateType' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(
                  <CouponTemplateType
                    value={form.getFieldValue(item.key) || defaultValue[item.key]}
                  />,
                )}
              </Form.Item>
            )}
            {item.type === 'ChooseCoupon' && (
              <Form.Item label={item.name}>
                {getFieldDecorator(item.key, {
                  initialValue: defaultValue[item.key],
                })(<ChooseCoupon />)}
              </Form.Item>
            )}
          </React.Fragment>
        );
      })}
    </Form>
  );
};

export default memo(
  Form.create({
    onValuesChange: (props, changedValues, allValues) => {
      props?.onSave(allValues);
    },
  })(FormEditor),
);
