import React, { Fragment, useState } from 'react';
import { Form, Input, Select, Radio } from '@easyv/antd';
import UploadThumb from 'components/NewUploadThumb';
import { useMousetrapPause } from 'components/easyUse';
import { useEffect } from 'react';
import ConfirmModal from 'components/ConfirmModal';
import { objectValueTrim ,getAssetsUrl} from 'utils/utils';
import styles from '../SortModal.less';

export default function EditModal({
  children,
  data,
  categorys,
  onOk
}: {
  children: React.ReactNode;
  data?: any;
  categorys: any;
  onOk: (value: any) => any;
}) {
  const [visible, setVisible] = useState(false);
  // const [content, setContent] = useState();
  const [thumb, setThumb] = useState();
  const [form] = Form.useForm();
  const { validateFields } = form;
  const [uploading, setUploading] = useState(false);

  const handleSubmit = () => {
    validateFields().then(async (values) => {
      setUploading(true);
      const param: any = {
        ...values
      };
      // if (content) {
      //   param.content = content;
      // }
      if (thumb) {
        param.thumb = thumb;
      }
      if (data?.id) {
        param.id = data.id;
      }
      const result = await onOk(objectValueTrim(param));
      setUploading(false);
      if (result) {
        setVisible(false);
      }
    });
  };

  useEffect(() => {
    if (!visible && form && form.resetFields) {
      form.resetFields();
    }
  }, [visible]);

  useMousetrapPause(visible);

  const defaultData = data || {
    type: 1,
    platformCategoryId: categorys[0]?.children[0]?.id
  };

  return (
    <Fragment>
      <span onClick={() => setVisible(true)}>{children}</span>
      <ConfirmModal
        title="新建"
        visible={visible}
        onCancel={() => setVisible(false)}
        onOk={handleSubmit}
        confirmLoading={uploading}
        footer={true}
        theme="black"
        destroyOnClose={true}>
        <Form labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} initialValues={defaultData} form={form} autoComplete="off">
          <Form.Item
            label="资源名称"
            name="name"
            rules={[
              { required: true, message: '组件名称必填', whitespace: true },
              { min: 2, max: 16, message: '请输入2～16个字符' }
            ]}>
            <Input placeholder="请输入名称，2～16个字符" />
          </Form.Item>
          <Form.Item label="选择分组" name="platformCategoryId" rules={[{ required: true, message: '选择分组' }]}>
            <Select dropdownClassName={styles.selectDrop}>
              {categorys.map((d) => {
                return (
                  <Select.OptGroup key={d.id} label={d.name}>
                    {d.children?.map((v) => {
                      return (
                        <Select.Option key={v.id} value={v.id}>
                          {v.name}
                        </Select.Option>
                      );
                    })}
                  </Select.OptGroup>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item label="素材类型" name="type">
            <Radio.Group>
              <Radio value={1}>图片</Radio>
              <Radio value={2}>视频</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}>
            {({ getFieldValue }) => {
              const type = getFieldValue('type');
              return (
                <Form.Item label="素材上传" name="content">
                  <UploadThumb
                    type={type === 1 ? 'image' : 'video'}
                    url={data?.content ? getAssetsUrl(`${data.content}`) : null}
                    maxSize={type === 1 ? 2 * 1024 * 1024 : 200 * 1024 * 1024}
                    onChange={setThumb}
                  />
                </Form.Item>
              );
            }}
          </Form.Item>
          <Form.Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}>
            {({ getFieldValue }) => {
              const type = getFieldValue('type');
              if (type === 2) {
                return (
                  <Form.Item label="缩略图" name="thumb">
                    <UploadThumb
                      url={data?.thumb ? getAssetsUrl(`${data.thumb}`) : null}
                      maxSize={200 * 1024}
                      onChange={setThumb}
                    />
                  </Form.Item>
                );
              } else {
                return null;
              }
            }}
          </Form.Item>
        </Form>
      </ConfirmModal>
    </Fragment>
  );
}
