import React, { useEffect, useState, useCallback } from 'react';
import { Button, Form, Select, Input, InputNumber, Radio, message, Card } from 'antd';
import ImageUpload from '@/components/XForm/ImageUpload';
import FileUpload from '@/components/XForm/FileUpload';
import Wangedit from '@/components/Wangedit/Wangedit';
import router from 'umi/router';
import { fetch, apis } from '@/utils/request';
import AuthButton from '@/components/AuthButton';

const FormItem = Form.Item;
const Option = Select.Option;
const getCurriculumData = fetch(apis.course.searchCourse);
const saveCurriculumData = fetch(apis.course.addCourse);
const updateCurriculumData = fetch(apis.course.alterCourse);
const goBack = () => router.goBack(-1);

const CurriculumForm = React.forwardRef((props, ref) => {
  const [loading, setLoading] = useState(false); //防止多次点击 定义loadind
  // const [formData, setFormData] = useState({});//提交表单的数据
  const [contentType, setContentType] = useState(0); //单选。初始默认显示0 富文本框。点击视频， 渲染1
  const { form, history } = props;
  const { getFieldDecorator, setFieldsValue, validateFields, getFieldValue } = form;
  const { curriculumId } = history.location.query || {};

  const formItemLayout = {
    //布局
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };

  const fileUploadBeforeUpload = (file, fileList) => {
    return new Promise((resolve, reject) => {
      if (file.type === 'video/mp4' || file.type === '.mp4') {
        // setVideoImage(true)
        resolve(file);
      } else {
        notification.error({ message: '项目视频，仅支持MP4格式' });
        reject();
      }
    });
  };

  const handleSubmit = e => {
    e.preventDefault();
    validateFields((err, values) => {
      if (err) {
        return;
        //字符验证未填写---返回
      }

      setLoading(true); //loading开始
      if (values.curriculumUrl) {
        values.curriculumUrl = values.curriculumUrl[0];
      }
      if (curriculumId) {
        //如果有这个id拿。没有就，拿返回的curriculumId
        updateCurriculumData({
          data: {
            ...values,
            curriculumId,
          },
          urlData: { id: curriculumId },
        })
          .then(() => {
            setLoading(false);
            message.success('数据更新成功');
            goBack();
          })
          .catch(err => {
            setLoading(false); //loading消失
            message.error(err.message || err);
          });
      } else {
        saveCurriculumData({ data: values })
          .then(() => {
            setLoading(false);
            message.success('数据保存成功');
            goBack();
          })
          .catch(err => {
            setLoading(false); //loading消失
            message.error(err.message || err);
          });
      }
    });
  };

  const getCourseData = useCallback(({ curriculumId }) => {
    //函数结果存 初始化运行一次，等待调用。
    getCurriculumData({ urlData: { id: curriculumId } }).then(res => {
      if (res.curriculumUrl) {
        res.curriculumUrl = [res.curriculumUrl];
      }
      setFieldsValue(res);
      // setFormData(res)
      // setContentType(res.type)
    });
  }, []);

  useEffect(() => {
    if (curriculumId) {
      getCourseData({ curriculumId }); //第一次渲染前//获取id
    }
  }, [curriculumId]); //第二次id一样不执行

  // useEffect(() => {
  //   if (formData) {//1.form表单数据{2} 执行。无变更不执行
  //     setFieldsValue(formData)
  //   }
  // }, [formData])//2.有变更跟的话

  return (
    <Card>
      <Form {...formItemLayout} onSubmit={handleSubmit}>
        {/* 布局提交表单 */}
        <FormItem label="参与对象">
          {getFieldDecorator('roleId', {
            rules: [{ required: true, message: '请选择参与对象' }],
          })(
            <Select style={{ width: '500px' }}>
              <Option value="1">经纪人</Option>
              <Option value="2">置业顾问</Option>
              <Option value="3">{`置业顾问&经纪人`}</Option>
            </Select>,
          )}
        </FormItem>
        <FormItem label="主图" help="建议尺寸：750px*600px，比例5:4，格式：jpg，用于：列表和详情">
          {getFieldDecorator('curriculumImg', {
            rules: [{ required: true, message: '请上传主图' }],
          })(<ImageUpload />)}
        </FormItem>
        <FormItem label="课程标题">
          {getFieldDecorator('name', {
            rules: [{ required: true, message: '请输入课程标题' }],
          })(<Input style={{ width: '500px' }} />)}
        </FormItem>
        <FormItem label="简介">
          {getFieldDecorator('remark', {
            rules: [{ required: true, message: '请填写简介' }],
          })(<Input.TextArea rows="5" style={{ width: '500px' }} />)}
        </FormItem>

        <FormItem label="详情">
          {getFieldDecorator('type', {
            initialValue: 0,
            rules: [{ required: true, message: '请选择详情类型' }],
          })(
            <Radio.Group style={{ width: '500px' }}>
              <Radio value={0}>图文</Radio>
              <Radio value={1}>视频</Radio>
            </Radio.Group>,
          )}
        </FormItem>
        {/*       
      <FormItem label="详情">
        {
        getFieldDecorator('type'),{
          rules:[
            {required:true,message:'请选择详情类型'}
          ]

        },
        <Radio.Group value={contentType} onChange={e => setContentType(e.target.value)}>
        <Radio value={1} type='0'>图文</Radio>
        <Radio value={2}type='1'>视频</Radio>
      </Radio.Group>
        }

      </FormItem> */}
        <FormItem label="图文" style={{ display: getFieldValue('type') == 0 ? 'block' : 'none' }}>
          {getFieldDecorator('content', {
            rules: [{ required: getFieldValue('type') == 0, message: '请输入详情内容' }],
          })(<Wangedit style={{ width: '500px' }} />)}
        </FormItem>
        <FormItem label="视频" style={{ display: getFieldValue('type') == 1 ? 'block' : 'none' }}>
          {getFieldDecorator('curriculumUrl', {
            rules: [{ required: getFieldValue('type') == 1, message: '请上传视频文件' }],
          })(<FileUpload accept=".mp4" label="上传视频" size={1} />)}
        </FormItem>

        <FormItem label="权重">{getFieldDecorator('weight')(<InputNumber min="0" />)}</FormItem>

        <FormItem wrapperCol={{ span: 12, offset: 6 }}>
          <AuthButton name="course.submit" noRight={null}>
            <Button loading={loading} type="primary" htmlType="submit">
              保存
            </Button>
          </AuthButton>
          <Button style={{ marginLeft: '2em' }} onClick={goBack}>
            取消
          </Button>
        </FormItem>
      </Form>
    </Card>
  );
});

export default Form.create({})(CurriculumForm);
