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 { validateMessages } from '@/utils/params';
import PictureOptionsRow from '@/components/PictureOptions/PictureOptionsRow';
import TextArea from 'antd/lib/input/TextArea';
import SelectCommunity from '@/components/SelectCommunity';
import './ann.less';
import { Notice } from '@/utils/tip';
import { getCookie } from '@/utils/method';
import moment from 'moment';
import { randomString } from '@/utils/string';

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); // 图片显示地址
  const [ImageName, setImageName] = useState([] as any); // 全部图片名称
  const [timeT, settimeT] = useState(true); // 结束时间是否禁止选择
  const [timeOver, settimeOver] = useState(1); // 结束时间禁止天数

  // 监听传递过来的值
  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,
      });
      if (DataSave.noticImageName) {
        // 如果存在图片 发起请求图片
        let msg = {
          type: 'tosCommunityNoticePreview',
          fileName: DataSave.noticImageName,
        };
        RA(47, msg, module, dispatch);
      }

      // 解除结束时间不可选
      settimeT(false);

      // 设置结束时间 到开始时间不能选
      let difference = moment().diff(moment(DataSave.noticStartTime.time), 'days');
      settimeOver(difference);

      // 图片名
      setImageName(DataSave.noticImageName.split(','));
    }
  }, [DataSave]);

  // 监听图片状态  ImgSrc
  useEffect(() => {
    if (ImgSrc != null) {
      let a = ImgSrc.map((item: any) => {
        let key = Object.keys(item)[0];
        return {
          uid: randomString(8),
          name: key,
          status: 'done',
          url: item[key],
        };
      });

      // 图片列表
      setImageSrc(a);
    }
  }, [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) => {
    const userInfo = localStorage.getItem('userInfo') || '';
    const id = JSON.parse(userInfo).userModel.id;

    if (values.community.value.length == 0) {
      message.error('Please select community！');
      return false;
    }
    var tmp = values;
    if (DataSave != null) {
      tmp.id = DataSave.id; // 如果是修改传递的 修改ID
    }
    tmp.creatorId = id; // 管理员 ID
    tmp.communityNum = values.community.value;
    tmp.noticScope = '' + values.community.index;
    // 文件名   如果动了。 新增删除  就传新的， 否则传旧的
    tmp.noticImageName = values.file ? values.file : ImageName; // 传递来的 和  表单的在一起
    tmp.noticStartTime = values.noticStartTime.format('YYYY-MM-DD');
    tmp.noticEndTime = values.noticEndTime ? values.noticEndTime.format('YYYY-MM-DD') : null;
    delete tmp.community;
    delete tmp.file;
    RA(28, tmp, module, dispatch);
  };

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

  function disabledDateOver(current: any) {
    return current && current <= moment().subtract(timeOver, 'days').endOf('day');
  }

  // 开始时间选择后打开结束时间
  const startTime = (date: any) => {
    settimeT(false);
    // 清除结束时间
    form.setFieldsValue({
      noticEndTime: null,
    });
    // 结束时间
    let day = moment().diff(date, 'days');
    settimeOver(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}
                onChange={startTime}
              />
            </Form.Item>
            <Form.Item name="noticEndTime" className="diyItem" label="Expiration Date" rules={[]}>
              <DatePicker
                style={{ width: 200 }}
                placeholder="Expiration Dates"
                disabledDate={disabledDateOver}
                disabled={timeT}
              />
            </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);
