import React, { Component } from 'react';

import { connect } from 'react-redux';
import { Form, Input, Button, Modal } from 'antd';
import isProd from '../../utils/env';
import NoticeIcon from '../NoticeIcon';
import Notifier from '../Notifier';
import { ERR_OK, MESSAGE_TYPE, NEW_MESSAGE } from '../Notifier/constants';
import styles from './index.less';
import { findPathByWidget, isJSON } from '../../utils/utils';
import { actionCreators } from '../../containers/App/store';
import service from '../../api/service/notification';
import i18n from '../../utils/share';
const app = i18n.getI18n('component');
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={app.get('noticeIcon.title')}
            emptyText={app.get('noticeIocn.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={app.get('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={app.get('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 && (
          <Modal
            title={app.get('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>
        )}
      </>
    );
  }
}

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

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

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