import React, { useState, useEffect } from 'react';
import { Button, Form, Input, DatePicker, notification } from 'antd';
import AuthButton from '@/components/AuthButton'
import request from '@/utils/request';
import apis from '@/services/apis';
import moment from 'moment';
import ModalForm from '../components/ModalForm';

const fullWidth = { width: '100%' };

const AMForm = props => {
  const { visibleData, onCancel, form, panoramaList, onSuccess } = props;
  const { visible, data } = visibleData;
  const { getFieldDecorator, setFieldsValue, resetFields, validateFields } = form;

  useEffect(() => {
    if (data) {
      data.trendTime=moment(data.trendTime)
      setFieldsValue(data);
    }
  }, [data]);

  function submitData(e) {
    e.preventDefault();
    validateFields((err, values) => {
      if (err) {
        console.error(err);
        return;
      }

      values.buildingId = props.buildingId;
      // 网路请求
      if (data?.trendId) {
        request({ ...apis.building.putTrend, urlData: {id:data?.trendId}, data: { ...values } })
          .then(() => {
            notification.success({ message: '操作成功' });
            onSuccess();
          })
          .catch(err => {
            notification.error({ message: 'err' });
            props.onCancel();
          });
      } else {
        request({ ...apis.building.addTrend, data: { ...values } })
          .then(() => {
            notification.success({ message: '操作成功' });
            onSuccess();
          })
          .catch(err => {
            notification.error({ message: 'err' });
            props.onCancel();
          });
      }
    });
  }

  return (
    <ModalForm
      title="项目动态设置"
      visible={visible}
      onCancel={onCancel}
      modalProps={{ destroyOnClose: true }}
      onSubmit={submitData}
    >
      <Form.Item label="时间">
        {getFieldDecorator('trendTime', {
          rules: [{ required: true, message: '请选择时间' }],
        })(<DatePicker style={fullWidth} />)}
      </Form.Item>
      <Form.Item label="标题">
        {getFieldDecorator('trendTitle', {
          rules: [
            { required: true, message: '请填写标题' },
            { max: 30, message: '标题不超过30个字符' },
          ],
        })(<Input placeholder="标题不超过30个字符" />)}
      </Form.Item>
      <Form.Item label="内容">
        {getFieldDecorator('trendContent', {
          rules: [{ required: true, message: '请填写内容' }],
        })(<Input.TextArea row={4} />)}
      </Form.Item>
      <Form.Item label=" " colon={false} style={{ marginTop: '2em' }}>
        <AuthButton name="building.dynamic.edit">
          <Button style={{ marginLeft: '4em' }} type="primary" htmlType="submit">
            保存
          </Button>
        </AuthButton>
        <Button style={{ marginLeft: '2em' }} onClick={props.onCancel}>
          取消
        </Button>
      </Form.Item>
    </ModalForm>
  );
};

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