import React, { Component } from 'react';

import { Button, Form, Input, Modal } from 'antd';
import { connect } from 'react-redux';

import { FormattedMessage } from '@/locales/localeExports';

import service from '../../api/service/notification';
import { actionCreators } from '../../containers/App/store';
import isProd from '../../utils/env';
import { findPathByWidget, isJSON } from '../../utils/utils';
import NoticeIcon from '../NoticeIcon';
import Notifier from '../Notifier';
import { ERR_OK, MESSAGE_TYPE, NEW_MESSAGE } from '../Notifier/constants';
import styles from './index.less';

const { TextArea } = Input;
/* eslint-disable */
class NoticeIconView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      noticeData: [],
      platformVisible: false,
      videoVisible: false,
      // eslint-disable-next-line react/no-unused-state
      noticeVisible: false,
      // eslint-disable-next-line react/no-unused-state
      renderVideo: null,
      // eslint-disable-next-line react/no-unused-state
      initVisible: false,
      sysTopVisible: false,
      sysMessage: {},
      alarmMessage: {},
      videoMessage: {},
    };
    // this.renderPlatform
    this.notifier = new Notifier(
      this.props.global.userInfo,
      this.renderVideo,
      this.renderPlatform,
      this.renderSysPlatform,
      this.props,
    );
  }

  async componentDidMount() {
    this.notifier.subscribe(NEW_MESSAGE, this.onNewMessage.bind(this));
    this.notifier.start();
  }

  componentWillUnmount() {
    try {
      // eslint-disable-next-line no-unused-expressions
      this.notifier && this.notifier.stop();
    } catch (error) {
      // eslint-disable-next-line no-empty
    } finally {
    }
  }

  onNewMessage = messages => {
    this.setState({
      count: messages.totalCount,
      noticeData: messages.messages,
    });
  };

  modalVisible = () => {
    const data = this.state.noticeData.filter(item => item.infoLevel === '4');

    return data.length > 0;
  };

  handleCloseVideo = () => {
    this.setState({ videoVisible: false });
    this.notifier.destoryVideo();
  };

  handleClosePlatform = event => {
    this.setState({ platformVisible: false });
    this.notifier.destoryPlatform();
  };

  renderPlatform = message => {
    const messageContent =
      this.props.global.mqtt_mess.MessageLevel === '2.0' &&
      isJSON(message.infoContent)
        ? JSON.parse(message.infoContent)
        : message.infoContent;

    this.setState({
      platformVisible: true,
      alarmMessage: {
        message,
        messageContent,
      },
    });
  };

  renderVideo = message => {
    this.setState({
      videoVisible: true,
    });
    const { props } = this;
    const infoType = message.infoType
      ? message.infoType
      : MESSAGE_TYPE.SCADA_TYPE;
    let data = [];
    if (this.props.global.mqtt_mess.MessageLevel === '2.0') {
      // eslint-disable-next-line no-shadow
      const message = this.notifier.messageThrome(
        infoType,
        // eslint-disable-next-line no-use-before-define
        JSON.parse(message.messContent),
      );
      data = message.split('\\n');
    } else {
      data = message.messContent.split('\\n');
    }

    const id = data[3];
    const name = data[0];
    const baseURI = isProd
      ? window.location.origin
      : `http://${window.location.hostname}:3020`;
    const url = `${baseURI}/civweb4/video/indexAll.html?ID=${id}&name=${name}&site=${
      props.global.userInfo.site
    }`;

    this.setState({
      // eslint-disable-next-line react/no-unused-state
      videoMessage: {
        name,
        url,
      },
    });
  };

  handlerOptions = value => {
    // eslint-disable-next-line no-undef
    service
      .postAddOptions({
        UserName: this.props.global.userInfo.fullName,
        Type: '其他问题',
        System: '熊猫智联',
        Content: value.content,
        Phone: value.phone,
        UserID: this.props.global.userInfo.OID,
        Picture: '',
      })
      .then(res => {
        if (res.statusCode === ERR_OK) {
          this.setState({
            sysTopVisible: false,
          });
        }
      });
  };

  renderSysPlatform = message => {
    const noticeContent =
      this.props.global.mqtt_mess.MessageLevel === '2.0' &&
      isJSON(message.infoContent)
        ? JSON.parse(message.infoContent)
        : message.infoContent;
    this.setState({
      sysTopVisible: true,
      platformVisible: false,
      videoVisible: false,
      sysMessage: {
        message,
        noticeContent,
      },
    });
  };

  handlerMointer = (event, item, detail) => {
    event.stopPropagation();
    this.notifier.confirmRead(false, [item.id]);
    if (detail) {
      const widgetID = 'widget_city_综合运营_管网监控_实时监控_报警监控';
      const webPath = 'product/scada/AlertMonitoring/AlertMonitoring';
      const widget = findPathByWidget(
        'productex/water/IOTMonitor/RealTimeAlarm/RealTimeAlarm',
        this.props.global.widgets,
        '',
        'url',
      );
      window.share.event.emit('listenerMointer', {
        widgetId: widgetID,
        label: '实时报警',
        url: widget.url || webPath,
      });
    }
    this.setState({
      platformVisible: false,
    });
  };

  handlerSysDetail = message => {
    this.setState({
      sysTopVisible: true,
    });
    this.renderSysPlatform(message);
  };

  render() {
    return (
      <>
        <NoticeIcon
          className={styles.action}
          count={this.state.count}
          confirmRead={this.notifier.confirmRead}
        >
          <NoticeIcon.Tab
            list={this.state.noticeData}
            title={<FormattedMessage id='component.noticeIcon.title'/>}
            emptyText={<FormattedMessage id='component.noticeIcon.allClear'/>}
            confirmRead={this.notifier.confirmRead}
            handlerSysDetail={this.handlerSysDetail}
            loadMore={this.notifier.loadMore}
            hasMore={this.notifier.hasMore}
          />
        </NoticeIcon>
        {this.state.platformVisible && this.state.alarmMessage && (
          <Modal
            title={<FormattedMessage id='component.noticeIcon.modal.alarm.title'/>}
            visible={this.state.platformVisible}
            zIndex={5000}
            className={styles.platformModal}
            footer={null}
            onCancel={() => this.handleClosePlatform()}
            centered
          >
            <div className={styles.alarmContent}>
              {/* eslint-disable-next-line jsx-a11y/alt-text */}
              <img
                src="https://panda-water.com/web4/assets/images/message/报警图标.svg"
                alt=""
              />
              <div className={styles.content}>
                <div className={styles['content-top']}>
                  <a
                    onClick={event =>
                      this.handlerMointer(
                        event,
                        this.state.alarmMessage.message,
                        true,
                      )
                    }
                  >
                    {this.state.alarmMessage &&
                      this.state.alarmMessage.messageContent &&
                      this.state.alarmMessage.messageContent.title}
                  </a>
                  <span
                    title={<FormattedMessage id='component.noticeIcon.messsage.statused'/>}
                    onClick={event =>
                      this.handlerMointer(
                        event,
                        this.state.alarmMessage.message,
                        false,
                      )
                    }
                  />
                </div>

                <div className={styles['content-mid']}>
                  <b>
                    {this.state.alarmMessage &&
                      this.state.alarmMessage.messageContent &&
                      this.state.alarmMessage.messageContent.alarmType}
                  </b>
                  {`|${this.state.alarmMessage &&
                    this.state.alarmMessage.messageContent &&
                    this.state.alarmMessage.messageContent.alarmContent}`}
                </div>
                <div className={styles['content-bottom']}>
                  <p>
                    <b>
                      {this.state.alarmMessage &&
                        this.state.alarmMessage.messageContent &&
                        this.state.alarmMessage.messageContent.alarmValue}
                      /
                    </b>
                    {this.state.alarmMessage &&
                      this.state.alarmMessage.messageContent &&
                      this.state.alarmMessage.messageContent.alarmThreshold}
                  </p>
                  <span>
                    {this.state.alarmMessage &&
                      this.state.alarmMessage.message &&
                      this.state.alarmMessage.message.time}
                  </span>
                </div>
              </div>
            </div>
          </Modal>
        )}

        {this.state.videoVisible && this.state.videoMessage && (
          <Modal
            visible={this.state.videoVisible}
            title={this.state.videoMessage.name}
            footer={null}
            centered
            width="50%"
            zIndex={1500}
            ref={videoRef => (this.videoRef = videoRef)}
            className={styles.videoPopup}
            onCancel={() => this.handleCloseVideo()}
          >
            <div className="web4_console_component">
              {/* eslint-disable-next-line jsx-a11y/iframe-has-title */}
              <iframe
                id="videoIframe"
                style={{ width: '100%', height: '100%' }}
                frameBorder="0"
                src={this.state.videoMessage.url}
              />
            </div>
          </Modal>
        )}

        {this.state.sysTopVisible && this.state.sysMessage && !this.props.global.isNewYear && (
          <Modal
            title={<FormattedMessage id='component.noticeIcon.model.system.title'/>}
            visible
            zIndex={8000}
            className={styles.noticeModal}
            onCancel={() => this.setState({ sysTopVisible: false })}
            footer={null}
            centered
          >
            <div className={styles.alarmContent}>
              <div className={styles.title}>
                {this.state.sysMessage.noticeContent.noticeTitle}
              </div>
              <div
                className={styles.content}
                dangerouslySetInnerHTML={{
                  __html: this.state.sysMessage.noticeContent.noticeContent,
                }}
              />
              <div className={styles.time}>
                {this.state.sysMessage.message.time}
              </div>
              <Form formLayout="vertical" onFinish={this.handlerOptions}>
                <div>1、您还有其他建议和反馈吗?</div>
                <Form.Item
                  name="content"
                  rules={[{ required: true, message: '请填写反馈内容' }]}
                >
                  <Input />
                </Form.Item>
                <div>
                  2、怎么联系您（您填写了建议和反馈，也请帮忙填写下您的联系方式，以便我们有不清楚的问题时，能与您联系沟通）
                </div>
                <Form.Item name="phone">
                  <Input />
                </Form.Item>
                <Form.Item>
                  <Button htmlType="submit" type="primary">
                    提交
                  </Button>
                </Form.Item>
              </Form>
            </div>
          </Modal>
        )}

        {this.state.sysTopVisible &&
          this.state.sysMessage &&
          this.props.global.isNewYear && (
            <Modal
              visible
              zIndex={9000}
              footer={null}
              centered
              className={styles.newYearMessage}
              width={876}
            >
            <div className={styles['topPopup-body']}>
              <div className={styles['topPopup-title']}>
                <img src="https://panda-water.com/web4/assets/images/message/%E5%85%B3%E9%97%AD%E6%8C%89%E9%92%AE.png" onClick={() => this.setState({ sysTopVisible: false })}/>
                <div className={styles['newYearTitle']}>
                  <img src="https://panda-water.com/web4/assets/images/message/%E7%83%9F%E8%8A%B1%E5%B7%A6.png"/>
                  <span title={this.state.sysMessage.noticeContent.noticeTitle}>{this.state.sysMessage.noticeContent.noticeTitle}</span>
                  <img src="https://panda-water.com/web4/assets/images/message/%E7%83%9F%E8%8A%B1%E5%8F%B3.png"/>
                </div>
              </div>
              <div className={styles['topPopup-content']}>
                <div className={styles['content']}>
                  <div className={styles['content-mid']}  dangerouslySetInnerHTML={{
                    __html: this.state.sysMessage.noticeContent.noticeContent,
                  }}></div>
                  <div className={styles['content-bottom']}>
                    <span className={styles['message-time']}>{this.state.sysMessage.message.time}</span>
                  </div>
                </div>
              </div>
              <div className={styles['feedbackBox']}>
                <Form layout="vertical" onFinish={this.handlerOptions}>
                  <div className={styles['question']}>您还有其他建议和反馈吗?</div>
                  <Form.Item
                    name="content"
                    rules={[{ required: true, message: '请填写反馈内容' }]}
                  >
                    <TextArea placeholder="请输入您的建议和反馈" rows={3}/>
                  </Form.Item>
                  <div className={styles['question']}>
                    请填写您的联系方式，以便我们及时与您沟通！
                  </div>
                  <div className={styles['horiztion']}>
                    <Form.Item name="phone">
                      <Input autoComplete='off' placeholder="请输入您的邮箱或者电话号码"/>
                    </Form.Item>
                    <Form.Item>
                      <Button htmlType="submit" type="primary"> </Button>
                    </Form.Item>
                  </div>

                </Form>
              </div>
            </div>
          </Modal>
        )}
      </>
    );
  }
}

const mapStateToProps = state => ({
  global: state.getIn(['global', 'globalConfig']),
});

const mapDispatchToProps = dispatch => ({
  updateConfig(config) {
    dispatch(actionCreators.getConfig(config));
  },
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(NoticeIconView);
