import React, { useEffect, useMemo, useState } from 'react';
import ProForm, {
  ProFormText,
  ProFormSelect,
  ProFormTextArea,
  ProFormSwitch,
  ProFormDigit,
  ProFormRadio,
} from '@ant-design/pro-form';
import UploadImage from '@/components/UploadImage';
import UploadVideo from '@/components/UploadVideo';
import WangEditor from '@/components/WangEditor';
import request from '@/utils/request';
import { notification, Form } from 'antd';

export default (props) => {
  const [form] = Form.useForm();
  const [isVideo, setIsVideo] = useState(false);

  const typeDict = useMemo(() => {
    return (props.typeList || []).reduce((acc, item) => {
      return {
        ...acc,
        [item.typeId]: item.name,
      };
    }, {});
  }, [props.typeList]);

  const handleSubmit = (values) => {
    const data = {
      ...props.post || {},
      ...values,
    }

    if (!data.postId) {
      // 新增
      return request('/post', { method: 'post', data })
        .then((res) => {
          props.onChange(res);
          notification.success({ message: '操作成功' });
        })
        .catch((e) => {
          notification.error({ message: e.message });
          return Promise.reject(e.message);
        });
    }

    // 编辑
    return request(`/post/${data.postId}`, { method: 'put', data })
    .then((res) => {
      props.onChange(res);
      notification.success({ message: '操作成功' });
    })
    .catch((e) => {
      notification.error({ message: e.message });
      return Promise.reject(e.message);
    });
  };

  const handleValueChange = (changed) => {
    const key = Object.keys(changed)[0];

    if (key === 'isVideo') {
      setIsVideo(changed[key]);
    }
  };

  useEffect(() => {
    if (props.post && props.post.postId) {
      form.setFieldsValue(props.post);
      setIsVideo(props.post.isVideo);
    }
  }, [props.post, form]);

  return (
    <ProForm form={form} onFinish={handleSubmit} onValuesChange={handleValueChange}>
      <ProFormText
        label="标题"
        placeholder="请输入标题"
        name="name"
        rules={[{ required: true, message: '请填写标题' }]}
      />

      <ProFormText
        label="作者"
        placeholder="请输入作者"
        name="author"
        rules={[{ required: true, message: '请填写作者' }]}
      />

      <ProFormSelect
        label="类型"
        placeholder="请选择类型"
        name="typeId"
        valueEnum={typeDict}
        rules={[{ required: true, message: '请选择类型' }]}
      />

      <Form.Item name="poster" label="封面" placeholder="请设置封面">
        <UploadImage />
      </Form.Item>

      <ProFormTextArea label="简介" placeholder="请输入简介" name="summary" />

      <ProFormSwitch label="视频" name="isVideo" checkedChildren="视频" unCheckedChildren="图文" />

      {isVideo ? (
        <>
          <Form.Item name="videoPoster" label="视频封面" placeholder="请设置封面">
            <UploadImage />
          </Form.Item>
          <Form.Item name="videoUrl" label="视频地址" placeholder="请上传视频">
            <UploadVideo />
          </Form.Item>
        </>
      ) : (
        <Form.Item name="content" label="图文内容" placeholder="请填写图文内容">
          <WangEditor />
        </Form.Item>
      )}

      <ProFormDigit
        label="答题数"
        name="answerNum"
        help="0 代表不会要求答题, 数字 N 代表至少要求答 N 道题目"
        fieldProps={{
          min: 0,
          max: 20,
        }}
        precision={0}
      />

      <ProFormDigit
        label="积分"
        placeholder="请设置获取积分"
        name="points"
        help="答题成功, 赢取积分数"
        fieldProps={{
          min: 0,
        }}
        precision={0}
      />

      <ProFormSwitch label="热门" name="isTopic" checkedChildren="是" unCheckedChildren="否" />

      <ProFormRadio.Group
        label="状态"
        name="status"
        options={[
          {
            label: '未发布',
            value: 0,
          },
          {
            label: '已发布',
            value: 1,
          },
        ]}
      />

      <ProFormText label="创建日期" name="createDate" readonly />
    </ProForm>
  );
};
