import React, { useState, useEffect } from 'react';
import { Form, Input, Button, DatePicker, message } from 'antd';
import router from 'umi/router';
import apis from '@/services/apis';
import moment from 'moment';
import BuildSelect from '@/components/SelectButton/BuildSelect2';
import Wangedit from '@/components/Wangedit/Wangedit';
import request from '@/utils/request';
import ImageUploader from '@/components/XForm/ImageUpload';
import AuthButton from '@/components/AuthButton';

const { RangePicker } = DatePicker;

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 },
};

const cancelPage = () => {
  router.go('-1');
};

const BasicForm = props => {
  const [isEnlist, setIsEnlist] = useState(1);
  const [activityStatus, setActivityStatus] = useState(1);
  const [disable, setDisable] = useState(false);
  const [data, setData] = useState(1);
  const [showSignupTime, setShowSignupTime] = useState([]);

  const { dynamicId, type } = props;

  // 查询详情
  const getDynamicData = dynamicId => {
    request({ ...apis.activity.details, params: { dynamicId } }).then(data => {
      data.activityTime = [moment(data.startDate), moment(data.endDate)];
      data.signupTime = [moment(data.enlistStart), moment(data.enlistEnd)];
      // setSignupTime([moment(data.enlistStart), moment(data.enlistEnd)])
      setData(data);
      setIsEnlist(data.isEnlist);
      setActivityStatus(data.activityStatus);
      setDisable(data.activityStatus === 0);
      props.form.setFieldsValue(data);
    });
  };

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    props.form.setFieldsValue({ isEnlist });
    if (dynamicId) {
      getDynamicData(dynamicId);
    }
  }, []);
  const checkTime = () => {
    function compareDate(dateTime1, dateTime2) {
      return new Date(dateTime1) > new Date(dateTime2);
    }
    // 1）修改后的开始时间不得大于当前时间（会存在已经成功报名的用户）

    // （2）修改后开始时间<当前时间<修改后结束时间：活动进行中

    // （3）修改后结束时间<当前时间：活动已结束
    if (showSignupTime[0]) {
      // const date = data.signupTime
      const nowDate = new Date();
      // console.log(compareDate(nowDate, showSignupTime[0]))
      if (compareDate(nowDate, showSignupTime[0])) {
        return true;
      } else {
        return '修改后的开始时间不得大于当前时间（会存在已经成功报名的用户）';
      }
    }
    return true;
  };

  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        const { activityTime, signupTime } = values;
        const [startDate, endDate] = activityTime;
        values.startDate = moment(startDate).format('YYYY-MM-DD HH:mm');
        values.endDate = moment(endDate).format('YYYY-MM-DD HH:mm');
        if (signupTime) {
          const [enlistStart, enlistEnd] = signupTime;
          values.enlistStart = moment(enlistStart).format('YYYY-MM-DD HH:mm');
          values.enlistEnd = moment(enlistEnd).format('YYYY-MM-DD HH:mm');
        }

        values.type = type;
        if (dynamicId) {
          const checks = checkTime();
          if (checks != true) {
            message.info(checks);
            return;
          }
          console.log(data.enlistNum, values.personNum, '143');

          if (data.enlistNum > values.personNum) {
            message.info('活动人数必须大于已报名人数');
            return;
          }

          values.dynamicId = dynamicId;
          request({ ...apis.activity.update, data: values })
            .then(data => {
              message.info('保存成功');
              // router.go(-1)
            })
            .catch(err => {
              message.info(err.msg || err.message);
            });
        } else {
          request({ ...apis.activity.add, data: { ...values } })
            .then(data => {
              message.info('保存成功');
              router.go(-1);
            })
            .catch(err => {
              message.info(err.msg || err.message);
            });
        }
      }
    });
  };
  const changeTime = (value, date) => {
    setShowSignupTime(date);
  };

  const { getFieldDecorator } = props.form;
  return (
    <>
      <Form {...formItemLayout} onSubmit={handleSubmit} style={{ maxWidth: '1000px' }}>
        <Form.Item label="所属项目">
          {getFieldDecorator('buildingId', {
            rules: [
              {
                required: true,
                message: '请选择所属项目',
              },
            ],
          })(<BuildSelect disabled={disable} />)}
        </Form.Item>
        <Form.Item label="活动封面图" help="建议图片尺寸：690px*388px，比例16:9,格式：jpg，用于：活动列表页">
          {getFieldDecorator('listImgUrl', {
            rules: [
              {
                required: true,
                message: '请选择活动封面图1',
              },
            ],
          })(<ImageUploader />)}
        </Form.Item>
        <Form.Item
          label="活动封面图2"
          help="建议图片尺寸：750*250，比例3:1，格式：jpg，用于：项目详情页"
        >
          {getFieldDecorator('bannerListImg', {
            rules: [
              {
                required: true,
                message: '请选择活动封面图2',
              },
            ],
          })(<ImageUploader />)}
        </Form.Item>
        <Form.Item
          label="活动详情主图"
          help="建议图片尺寸：750*415px，比例16:9,格式：jpg，用于：活动详情"
        >
          {getFieldDecorator('imgUrl', {
            rules: [
              {
                required: true,
                message: '请选择活动详情主图',
              },
            ],
          })(<ImageUploader />)}
        </Form.Item>
        <Form.Item label="活动标题">
          {getFieldDecorator('title', {
            rules: [
              {
                required: true,
                message: '请输入活动标题',
              },
            ],
          })(<Input />)}
        </Form.Item>
        <Form.Item label="活动副标题">
          {getFieldDecorator('halfTitle', {
            rules: [
              {
                required: true,
                message: '请输入活动副标题',
              },
            ],
          })(<Input />)}
        </Form.Item>
        <Form.Item label="活动时间">
          {getFieldDecorator('activityTime', {
            rules: [
              {
                required: true,
                message: '请选择活动时间',
              },
            ],
          })(<RangePicker format="YYYY-MM-DD HH:mm" />)}
        </Form.Item>
        <Form.Item label="活动地点">
          {getFieldDecorator('address', {
            rules: [
              {
                required: true,
                message: '请输入活动地点',
              },
            ],
          })(<Input />)}
        </Form.Item>
        {/* disabled={activityStatus === 0 ? true : false} */}
        <Form.Item label="活动人数" help="当前活动最多可报名人数">
          {getFieldDecorator('personNum', {
            rules: [
              {
                required: true,
                message: '请输入活动人数',
              },
              // {
              //   min: data.personNum,min={data.personNum || 0}
              //   message: '活动人数必须大于已报名人数',
              // },
            ],
          })(<Input type="number" />)}
        </Form.Item>
        {/* <Form.Item label="用户携带人数" help="每个用户最多可携带参与活动的人数">
          {getFieldDecorator('maxEnlistByPerson', {
            rules: [
              {
                required: true,
                message: '请输入用户携带人数',
              },
            ],
          })(<Input type="number" min={1} />)}
        </Form.Item> */}
        <Form.Item label="活动详情">{getFieldDecorator('desc')(<Wangedit />)}</Form.Item>
        <Form.Item label="报名时间">
          {getFieldDecorator('signupTime', {
            rules: [
              {
                required: true,
                message: '请选择报名时间',
              },
            ],
          })(<RangePicker format="YYYY-MM-DD HH:mm" onChange={changeTime} />)}
        </Form.Item>
        <Form.Item label="权重">
          {getFieldDecorator('heavy', {
            rules: [
              {
                required: true,
                message: '请输入权重',
              },
            ],
          })(<Input type="number" style={{ width: 80 }} />)}
          <span style={{ marginLeft: 30, color: 'grey' }}>数字越大越靠前</span>
        </Form.Item>
        <Form.Item wrapperCol={{ span: 12, offset: 8 }}>
          <AuthButton name="activity.enroll.submit" noRight={null}>
            <Button type="primary" htmlType="submit">
              确认
            </Button>
          </AuthButton>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button onClick={() => cancelPage()}>取消</Button>
        </Form.Item>
      </Form>
    </>
  );
};

export default Form.create({ name: 'BasicForm' })(BasicForm);
