import React from 'react';
import ReactDOM from 'react-dom';
import {ListView, WhiteSpace, List, Card, WingBlank} from 'antd-mobile';
import { Http } from './../../Utils/help';
// import '../../less/Flex.less';
import './less/list.less';
import { browserHistory } from 'react-router';

//跳转到机台状态数据
window.MacClick= function(val){
    console.log(val) 
    browserHistory.push({
        pathname: '/macstatusnowinfo',
        state: {
            code: val,
            status: '',
        }
    }); 
}
//const Item = List.Item;
//const Brief = Item.Brief;
export default class AlertDetail extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.NUM_SECTIONS = 1;
        this.NUM_ROWS_PER_SECTION = 50;
        const { rowData } = this.props.location.state;
        // const { func } = this.props.location.state?{func:{}};
        this.genData = this.genData.bind(this);
        this.onEndReached = this.onEndReached.bind(this);
        const getSectionData = (dataBlob, sectionID) => dataBlob[sectionID];
        const getRowData = (dataBlob, sectionID, rowID) => dataBlob[rowID];

        const dataSource = new ListView.DataSource({
            getRowData,
            getSectionHeaderData: getSectionData,
            rowHasChanged: (row1, row2) => row1 !== row2,
            sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
        });
        // localStorage.removeItem("newData")
        // localStorage.removeItem("datalength")
        this.state = {
            dataSource: dataSource,
            // func: func,
            rowData: rowData,
            nodata: true,
            data: {},
            messageData:{},
            isLoading: false,
            page:1,
            pageSize:20,
            height: document.documentElement.clientHeight * 1,
        };

    }
    onEndReached(event){
        // load new data
        // hasMore: from backend data, indicates whether it is the last page, here is false
        if (this.state.isLoading && !this.state.hasMore) {
          return;
        }
        console.log('reach end', event);
        this.setState({ isLoading: true });
        let that = this;
        this.dataAjax = Http.getJSON2("showmessage/getunreadmessage", { "topicid": this.state.rowData['Topicid'], "page":++this.state.page,"pageSize":this.state.pageSize })
            .done((data) => {
                console.log("onEndReached:", data.data)
                if(data.data && data.data.length>0){
                    try {
                        var c=that.state.data.concat(data.data);
                        that.genData(c);
                        console.log(data, that.state)
                        that.setState({
                        dataSource: that.state.dataSource.cloneWithRowsAndSections(that.dataBlobs, that.sectionIDs, that.rowIDs),
                        data:c,
                        page:data.Page,
                        nodata:!data||data.length==0,
                        isLoading:false,
                        });
                        console.log(that.state)
                    } catch (err) {
                        console.error(err.message);
                        console.error(err.stack);
                    }
                }
            });

        // setTimeout(() => {
        //   genData(++pageIndex);
        //   this.setState({
        //     dataSource: this.state.dataSource.cloneWithRowsAndSections(dataBlobs, sectionIDs, rowIDs),
        //     isLoading: false,
        //   });
        // }, 1000);
      }

    //取得json数据集
    componentWillMount() {
        window.conditionarr=[]
        console.log("componentWillMount",this.context)
        console.log(this.state.rowData)
        this.setState({ isLoading: true });  
            this.dataAjax = Http.getJSON2("showmessage/getunreadmessage", { "topicid": this.state.rowData['Topicid'], "page":this.state.page,"pageSize":this.state.pageSize})
            .done((data) => {
                console.log("first json",data.data)
                try {
                    this.genData(data.data);
                    console.log(data, this.state)
                    this.setState({
                    page:data.Page,
                    dataSource: this.state.dataSource.cloneWithRowsAndSections(this.dataBlobs, this.sectionIDs, this.rowIDs),
                    data:data.data,
                    nodata:!data||data.length==0,
                    isLoading:false,
                    });
                    console.log("first json", this.state)
                } catch (err) {
                    console.error(err.message);
                    console.error(err.stack);
                }
            });
    }

    componentDidMount() {
        const hei = document.documentElement.clientHeight - ReactDOM.findDOMNode(this.lv).parentNode.offsetTop;
    }

    genData = (datas) => {
        this.dataBlobs = {};
        this.sectionIDs = [];
        this.rowIDs = [];
        if (!datas)
            return;

        let pIndex = 0;
        this.NUM_ROWS_PER_SECTION = datas.length;
        for (let i = 0; i < this.NUM_SECTIONS; i++) {
            const ii = (pIndex * this.NUM_SECTIONS) + i;
            const sectionName = `Section ${ii}`;
            this.sectionIDs.push(sectionName);
            this.dataBlobs[sectionName] = sectionName;
            this.rowIDs[ii] = [];

            for (let jj = 0; jj < this.NUM_ROWS_PER_SECTION; jj++) {
                const rowName = `S${ii}, R${jj}`;
                this.rowIDs[ii].push(rowName);
                this.dataBlobs[rowName] = datas[jj];
            }
        }
        this.sectionIDs = [...this.sectionIDs];
        this.rowIDs = [...this.rowIDs];
    }
    //oee机台跳转
    // MacClick = (val) => {
    //     console.log(val)
    //     const { router } = this.context;
    //     router.push({
    //         pathname: '/macstatusnowinfo',
    //         state: {
    //             code: val,
    //             status: '',
    //         }
    //     });
    // }
 
    render() {
        const separator = (sectionID, rowID) => (
            <div
                key={`${sectionID}-${rowID}`}
                style={{
                    // backgroundColor: '#F5F5F9',
                    // height: 0,
                    // borderTop: '0px solid #ECECED',
                    // borderBottom: '0px solid #ECECED',
                }}
            />
        );


        const row = (rowData, sectionID, rowID,that) => {
            // {rowData.ExtraDatas.content =  '<div>机台:<a href="/maintain">TXR004<a> 消息内容<div>'}
            // {rowData.ExtraDatas.content =  '<div>机台:<a onClick={MacClick("TYZ010")} ><u>TYZ010</u><a> 消息内容<div>'}
            return (
                 <div key={rowID} style={{backgroundColor: '#F5F5F9'}}>    
                <div style={{textAlign:'center', fontSize:'14px', backgroundColor:'#F5F5F9',}}> {rowData.CreateTime} </div>
                    <div style={{padding:'10px', backgroundColor:'#F5F5F9'}}>
                        {/* <div style ={{borderRadius:'10px',backgroundColor:'#FFFAFA',padding:'8px',lineHeight:'18px'}}>{rowData.ExtraDatas.content}</div> */}
                        <div style ={{borderRadius:'10px',backgroundColor:'#FFFAFA',padding:'8px',lineHeight:'18px'}} dangerouslySetInnerHTML={{__html: rowData.messagelistvo ===null? rowData.ExtraDatas.content:rowData.messagelistvo.content}}></div>
                    </div>
                 </div>
            );
        };
        let that = this;
        return (
            <div>
                {/* <WhiteSpace size="xs" /> */}
                <div style= { {paddingLeft:'15px'}}> <h3>{this.state.rowData.ExtraDatas.topicname}</h3> </div>
                {this.state.data && this.state.data.length>0 ? null : <div style={{paddingLeft:"15px"}}>没有数据!</div>}
                <ListView 
                // className="am-list-header"
                    ref={el => this.lv = el}
                    dataSource={this.state.dataSource}
                    //renderHeader={() => <span><h3>品质警报</h3><div >信息总数：{this.state.datalength} 未读信息数：{this.state.arraylength}</div></span>}
                    //renderHeader={ ()=> <h5>{this.state.rowData.ExtraDatas.topicname}</h5> }
                    renderRow={row}
                    renderSeparator={separator}
                    // className="am-list"
                    initialListSize={40}
                    onScroll={() => { 
                        console.log('scroll'); 
                    }}
                    scrollRenderAheadDistance={500}
                    onEndReached={this.onEndReached}
                    onEndReachedThreshold={10}
                    style={{
                        height: this.state.height,
                        overflow: 'auto',
                      }}
                />

            </div>
        );
    }


}