import React, { useEffect, useState, useCallback } from 'react';
import { Button, Icon, Form, Modal, Input } from 'antd';
import { Link } from "react-router-dom";
import { getNoticeDetail, addReader } from '../api';
import { noticeType } from '../static';
import './index.scss';

const noticeTypeArr = [];
for (const item of noticeType) {
  noticeTypeArr[item.code] = item.name;
}

export default Form.create()(({ match, history, showNotification, form }) => {
  const { getFieldDecorator, validateFields, setFieldsValue } = form;

  const [reload, setReload] = useState(0);
  const [noticeData, setNoticeData] = useState({});
  const [visible, setVisible] = useState(false);

  const [readerName,setReaderName]=useState('');

  const id = match.params.noticeId;

  useEffect(() => {
    id && getNoticeDetail(id).then(data => {
      if (data) {
        data.publishDate = data.publishDate.split(' ')[0];
        data.createdAt = data.createdAt.split(' ')[0];
        data.closingDate = data.closingDate.split(' ')[0];
      }
      setNoticeData(data || {});
    })
  }, [id, reload]);

  // form表单公共处理函数
  const helper = useCallback(
    (label, name, rules, widget) => (
      <Form.Item label={label}>
        {getFieldDecorator(name, { rules, validateFirst: true ,getValueFromEvent: e=>e.target.value.replace(/(^\s*)|(\s*$)/g, "") })(widget)}
      </Form.Item>
    ),
    []
  );

  function pushInfo() {
    validateFields((err, values) => {
      if (!err) {
        addReader({
          ...values,
          annId: noticeData.id,
        }).then(res => {
          if (res.message === "success") {
            setVisible(false);
            setReload(Math.random());
          } else {
            res && Modal.error({ content: res.message });
          }
        })
      }
    });
  }


  return (
    <div className="centerbox notice-detail">
      <div className="head-navigation">
        <Link to="/">首页<span className="greater">&nbsp;&gt;&nbsp;</span></Link>
        <Link to="/notice">公告<span className="greater">&nbsp;&gt;&nbsp;</span></Link>
        <span>公告详情</span>
      </div>
      <div className="center-content">
        {/* <div className="notice-center-content"> */}
        <div className="notice-title">
          {noticeData.title}
        </div>
        <div className="notice-detail-content">
          <div className="center-author">
            <p key={0}>公告类型：{noticeTypeArr[noticeData.type]}</p>
            {noticeData.publisher && <p key={1}>发布单位：{noticeData.publisher}</p>}
            <p key={2}>发布时间：{noticeData.publishDate || noticeData.createdAt}</p>
            <p key={3}>截止时间：{noticeData.closingDate}</p>
            <p key={4}>浏览：{noticeData.visits || 0}</p>
          </div>

          <div className="content-text">
            <div className="notice-content-title"><Icon type="caret-right" />公告主要内容</div>
            <div className="editor-w-text" dangerouslySetInnerHTML={{ __html: noticeData.text }}>
            </div>
          </div>

          {
            noticeData.contactInfo ? <React.Fragment>
              <div className="notice-content-title"><Icon type="caret-right" />联系方式</div>
              <div className="content-secret" dangerouslySetInnerHTML={{ __html: noticeData.contactInfo && noticeData.contactInfo.replace(/\n/g, '</br>') }}>
              </div>
              {
                noticeData.blockedView && <Button type="primary" onClick={() => { setVisible(true) }}>申请查看加密内容</Button>
              }
            </React.Fragment> : ''
          }


          {
            noticeData.fileDownloadPath &&
            <React.Fragment>
              <div className="notice-content-title"><Icon type="caret-right" />公告附件</div>
              <p className="notice-content-download"  >
                <span onClick={() => { window.open(noticeData.fileDownloadPath) }}>
                  <i className="iconfont icon-fujian color-green font-14 mr3"></i>{noticeData.fileName}
                </span>
                <span className="link" onClick={() => { window.open(noticeData.fileDownloadPath) }}>下载</span>
              </p>
            </React.Fragment>
          }


        </div>
      </div>

      <Modal
        title="提交信息"
        visible={visible}
        onOk={pushInfo}
        onCancel={() => { setVisible(false) }}
        className="form-edit-modal"
      >

        {
          helper('用户姓名',
            'readerName',
            [{ required: true, message: "请输入用户姓名" }, { max: 50, message: '不能超过50字符' }],
            <Input
              placeholder="请输入用户姓名"
            />
          )
        }

        {
          helper('公司名称',
            'companyName',
            [{ required: true, message: "请输入公司名称" }, { max: 100, message: '不能超过100字符' }],
            <Input
              placeholder="请输入公司名称"
            />
          )
        }

        {
          helper('联系方式',
            'contactInfo',
            [{ required: true, message: "请输入联系方式" }, 
             { max: 100, message: '不能超过100字符' },
             { validator: (rule,val,callback) =>{
                const pattern = /^((\+)?86|((\+)?86)?)0?1[3458]\d{9}$/; 
                if(pattern.test(val)){
                  callback();
                }else {
                  callback('请输入正确的手机号码！');
                }
             }}],
            <Input
              placeholder="请输入联系方式"
            />
          )
        }
      </Modal>

    </div>

  )
}
)
