import React, { Component } from 'react';

import { Modal } from 'antd';
import { connect } from 'react-redux';

import isProd from '../../utils/env';
import NoticeIcon from '../NoticeIcon';
import Notifier from '../Notifier';
import { NEW_MESSAGE } from '../Notifier/constants';
import styles from './index.less';

class NoticeIconView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      noticeData: [],
      platformVisible: true,
      videoVisible: false,
      noticeVisible: false,
      renderVideo: null,
      initVisible: false
    };
    //this.renderPlatform
    this.notifier = new Notifier(this.props.global.userInfo, this.renderVideo, this.renderPlatform);
  }

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

  componentWillUnmount(){
    try {
      this.notifier && this.notifier.stop();
    }catch(error) {
      console.log(error);
    }finally{
      
    }
  }

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

    console.log("newMessages", messages)

  };

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

    return data.length > 0 ? true: false;
  }

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


  renderPlatform = (message) => {
    this.setState({
      platformVisible: true
    })
    return (
      <Modal title="报警消息" 
          visible={this.state.platformVisible} 
          zIndex={5000} 
          className={styles.platformModal} 
          footer={null} 
          onCancel={() => this.handleClosePlatform()}
          centered>
            <div className={styles.alarmContent}>
              <img src="https://panda-water.com/web4/assets/images/message/报警图标.svg"/>
              <div className={styles.content}>
                <div className={styles['content-top']}>
                  <a onClick={() => this.handlerMointer(message, true)}>{message.infoContent.alarmDevice}</a>
                  <span title="点击标为已读" onClick={() => this.handlerMointer(message, false)}></span>
                </div>
               
                <div className={styles['content-mid']}>
                  <b>{message.infoContent.alarmType}</b>
                  {
                    '|' + message.infoContent.alarmContent
                  }
                </div>
                 <div className={styles['content-bottom']}>
                    <p>
                      <b>{message.infoContent.alarmValue}/</b>
                      {message.infoContent.alarmThreshold}
                    </p>
                    <span>{message.time}</span>
                </div>
                </div>
            </div>
         </Modal>
    )
  }

  renderVideo = (message) => {
    this.setState({
      videoVisible: true
    });
    const props = this.props;
    const data = message && message.messContent && 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}`;
    return (
      <Modal visible={this.state.videoVisible} 
            title={name} 
            footer={null} 
            centered width="50%" 
            zIndex={1500}
            ref={videoRef => this.videoRef = videoRef} 
            className={styles.videoPopup} 
            onCancel={() => this.handleCloseVideo() }>
        <div className="web4_console_component">
          <iframe id="videoIframe" style={{width: '100%', height: '100%'}} frameBorder="0" src={url}></iframe>
        </div>
      </Modal>
    );
  }

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

  handlePopupVisibleChange = (bool) => {
    this.setState({
      noticeVisible: bool
    })
  }

 
  render() {
    return (
      <>
        <NoticeIcon
          className={styles.action}
          count={this.state.count}
          confirmRead={this.notifier.confirmRead}
        >
          <NoticeIcon.Tab
            list={this.state.noticeData}
            title="通知"
            emptyText="你已查看所有通知"
            confirmRead={this.notifier.confirmRead}
            loadMore={this.notifier.loadMore}
            hasMore = {this.notifier.hasMore}
          />
        </NoticeIcon>
        {/* {
          this.state.platformVisible ? <Modal title="未读消息" 
          visible={this.state.platformVisible} 
          zIndex={5000} 
          className={styles.platformModal} 
          footer={null} 
          centered 
          maskClosable={false}
          onCancel={(event) => this.handleClosePlatform(event)}>
            <List 
                itemLayout="vertical"
                dataSource={this.state.noticeData.filter(item => item.infoLevel === "4")}
                pagination={{
                  size:"small",
                  onChange: page => {
                    console.log(page);
                  },
                  pageSize: 1,
                }}
                renderItem={
                  item => (
                    <List.Item 
                        key={item.id} 
                        extra={<img width={16} alt="点击标为已读" src="https://panda-water.com/web4/assets/images/message/%E5%B7%B2%E8%AF%BB-%E9%BB%98%E8%AE%A4.svg" onClick={() => this.handlerMointer(item, false)}/>}>
                        <List.Item.Meta
                            avatar={<img size="63" src="https://panda-water.com/web4/assets/images/message/%E6%8A%A5%E8%AD%A6%E5%9B%BE%E6%A0%87.svg" />}
                            title={<a onClick={() => this.handlerMointer(item, true)}>{item.infoContent.alarmDevice}</a>}
                            description={
                              <>
                                <div className={styles.content}>
                                  <b>{item.infoContent.alarmType}</b>
                                  {
                                    '|' + item.infoContent.alarmContent
                                  }
                                </div>
                                <div>
                                  <span>
                                    <b>{item.infoContent.alarmValue}/</b>
                                    {item.infoContent.alarmThreshold}
                                  </span>
                                  <span>{item.time}</span>
                                </div>
                              </>
                            }
                          />
                    </List.Item>
                  )
                }>
            </List>
         </Modal>: null
        } */}
        {
          this.state.platformVisible ? this.notifier.renderPlatformElement: null
          // this.renderPlatform()
        }
        
        {
          this.state.videoVisible ? this.notifier.renderVideoElement: null
        }
     </> 
    );
  }
}

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

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