import React, { useState, useEffect, useRef } from 'react';
import { Input, Tabs, message, Form, Button, DatePicker, Spin } from 'antd';
const { TabPane } = Tabs;

import { connect, history } from 'umi';

import { RA, SA } from '@/utils/method';
import TitleBack from '@/components/TitleBack/TitleBack';
// import FileUpload from '@/components/FileUpload/FileUpload';
import { validateMessages } from '@/utils/params';
import PictureOptionsRow from '@/components/PictureOptions/PictureOptionsRow';
import TextArea from 'antd/lib/input/TextArea';
import SelectCommunity from '@/components/SelectCommunity';
// import Line from '@/components/Line/Line';
// import TimeComfirm from '@/components/TimeComfirm/TimeComfirm';
import imgs from '@/assets/logo_icon_bg.png';
import './ann.less';
import { Notice } from '@/utils/tip';
import { getCookie } from '@/utils/method';
import moment from 'moment';

const module = 'CommunityAnnouncement';

const Add = (props: any) => {
  const { dispatch, Result, loading, DataSave, ImgSrc } = props;
  const formRef = useRef(null);
  const [form] = Form.useForm();

  // 图片地址
  const [ImageSrc, setImageSrc] = useState([] as any);

  // 监听传递过来的值
  useEffect(() => {
    if (DataSave != null) {
      let day = moment(DataSave.noticStartTime.time);
      let day2 = DataSave.noticEndTime ? moment(DataSave.noticEndTime.time) : null;

      // 赋值
      form.setFieldsValue({
        noticTitle: DataSave.noticTitlel,
        noticText: DataSave.noticText,
        noticStartTime: day,
        noticEndTime: day2,
      });
      // 发起请求图片
      let msg = {
        type: 'tosCommunityNoticePreview',
        fileName: DataSave.noticImageName,
      };
      RA(47, msg, module, dispatch);
    }
  }, [DataSave]);

  // 监听图片状态  ImgSrc
  useEffect(() => {
    if (ImgSrc != null) {
      let imgUrl = [
        {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: ImgSrc,
        },
      ];
      setImageSrc(imgUrl);
    }
  }, [ImgSrc]);

  // 监听是不是提交成功
  useEffect(() => {
    if (Result != null) {
      // 移除传递来的信息
      dispatch({
        type: `${module}/ResultRemove`,
      });
      // 重新刷新页面
      let page = {
        noticTitlel: '',
        creator: '',
        pageNum: 1,
      };
      // 把内容存进去
      SA(DetailPage(page), module, dispatch);
      message.success('Released Successfully');
      history.push('/CommunityManagement/CommunityAnnouncement');
    }
  }, [Result]);

  // 分业数据
  const DetailPage = (page: any) => {
    let data = {
      Method: 'returnDataSaveDetail',
      DefaultName: 'DataSaveDetail',
      Data: page,
    };
    return data;
  };

  // 提交
  const onFinish = (values: any) => {
    // console.log(values);
    var tmp = values;
    if (DataSave != null) {
      tmp.id = DataSave.id; // 如果是修改传递的 修改ID
    }
    tmp.creatorId = getCookie('id'); // 管理员 ID
    tmp.communityNum = values.community.value;
    tmp.noticScope = '' + values.community.index;
    delete tmp.community;
    // 文件名
    tmp.noticImageName = values.file ? values.file[0] : null;
    tmp.noticStartTime = values.noticStartTime.format('YYYY-MM-DD');
    tmp.noticEndTime = values.noticEndTime ? values.noticEndTime.format('YYYY-MM-DD') : null;
    // console.log(tmp);
    RA(28, tmp, module, dispatch);
  };

  // 设置之前时间不能选择
  function disabledDate(current: any) {
    return current && current <= moment().subtract(1, 'days').endOf('day');
  }

  return (
    <>
      <Spin spinning={loading}>
        <div style={{ width: '100%', padding: 20, backgroundColor: '#ffffff' }}>
          <TitleBack
            title={DataSave == null ? 'Add Announcement' : 'Edit Announcement'}
          ></TitleBack>

          <Form
            ref={formRef}
            form={form}
            // {...layout}
            onFinish={onFinish}
            validateMessages={validateMessages}
          >
            <Form.Item name={'community'} className="diyItem" label="Community" rules={Notice[0]}>
              <SelectCommunity
                checklist={DataSave == null ? null : DataSave.communityNum.split(',')}
              />
            </Form.Item>
            <Form.Item name="noticTitle" className="diyItem" label="Notice Title" rules={Notice[1]}>
              <Input style={{ width: 200 }} placeholder="Please input the notice title" />
            </Form.Item>
            <Form.Item
              name="noticText"
              className="diyItem"
              label="Notice Content"
              rules={Notice[2]}
            >
              <TextArea
                style={{ height: 100, maxWidth: 600 }}
                maxLength={1000}
                showCount={true}
                placeholder="Please input the announcement content"
              />
            </Form.Item>

            <Form.Item name={'file'} className="diyItem" label=" " colon={false}>
              <PictureOptionsRow
                action="/tos/image/upload"
                data={{
                  imageType: 'tosNotice',
                }}
                limitNums={5}
                defaultValue={ImageSrc}
              />
            </Form.Item>
            <Form.Item
              name="noticStartTime"
              className="diyItem"
              label="Effective Dates"
              rules={Notice[3]}
            >
              <DatePicker
                style={{ width: 200 }}
                placeholder="Effective Dates"
                disabledDate={disabledDate}
              />
            </Form.Item>
            <Form.Item name="noticEndTime" className="diyItem" label="Expiration Date" rules={[]}>
              <DatePicker style={{ width: 200 }} placeholder="Expiration Dates" />
            </Form.Item>
            <hr />
            <Form.Item style={{ marginBottom: 5 }} className="diyItem" label=" " colon={false}>
              <Button type="primary" htmlType="submit" loading={loading}>
                Submit
              </Button>
            </Form.Item>
          </Form>
        </div>
      </Spin>
    </>
  );
};

function map(state: any) {
  const { Result, DataSave, ImgSrc } = state[module];
  const loading = state.loading.models.CommunityAnnouncement
    ? state.loading.models.CommunityAnnouncement
    : false;
  return { Result, loading, DataSave, ImgSrc };
}
export default connect(map)(Add);
