import React from 'react';
import 'antd-mobile/dist/antd-mobile.css';
import { ListView, List, Icon, Button} from 'antd-mobile';
import { Http } from '../../Utils/help';
import './less/list.less';

const Item = List.Item;
const Brief = Item.Brief;
export default class machealthchecklog extends React.Component {
    constructor(props) {
        super(props);
        this.NUM_SECTIONS = 1;
        this.NUM_ROWS_PER_SECTION = 50;
        // const { func } = this.props.location.state?{func:{}};
        this.genData = this.genData.bind(this);
        this.addMaccheck = this.addMaccheck.bind(this)
        this.getNowFormatDate = this.getNowFormatDate.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,
        });
        this.state = {
            dataSource: dataSource,
            // func: func,
            isLoading:false, 
            nodata: true,
            data: {},
            page:1,
            pageSize:10,
            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("maintenance", {"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,
                        });
                    } catch (err) {
                        console.error(err.message);
                        console.error(err.stack);
                    }
                }
            });
      }
    componentWillMount(){
        console.log("componentWillMount")
       
    }
    componentDidUpdate() {
    }
    componentDidMount() {
        console.log("componentDidMount")
        this.setState({ isLoading: true });  
        this.dataAjax = Http.getJSON2("machealthchecklog", {"page":this.state.page, "pageSize":this.state.pageSize})
        .done((data) => {
            console.log(data.data)
            try {
                this.genData(data.data);
                console.log(data.data, this.state)
                this.setState({
                dataSource: this.state.dataSource.cloneWithRowsAndSections(this.dataBlobs, this.sectionIDs, this.rowIDs),
                data:data.data,
                nodata:!data||data.length==0,
                isLoading:false,
                });
                console.log("this.state", this.state)
            } catch (err) {
                console.error(err.message);
                console.error(err.stack);
            }
        });
       
    }

    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];
    }

    getNowFormatDate = () =>{//获取当前时间
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1<10? "0"+(date.getMonth() + 1):date.getMonth() + 1;
        var strDate = date.getDate()<10? "0" + date.getDate():date.getDate();
        var currentdate = date.getFullYear() + seperator1  + month  + seperator1  + strDate
                + " "  + date.getHours()  + seperator2  + date.getMinutes()
                + seperator2 + date.getSeconds();
        return currentdate;
    }

    addMaccheck =()=>{
        const { history } = this.props;
        var rowData = {}
        rowData.BillDate = this.getNowFormatDate()
        rowData.CreateTime = this.getNowFormatDate()
        rowData.deviceid = ''
        rowData.status = 'New'
        rowData.Items = {}
        history.push({
            pathname: '/machealthchecklogdetail',
            state: {
                func: this.state.func,//没有这段代码，页面不能跳转
                rowData: rowData,
            }
        });
    }

    render() {
        const separator = (sectionID, rowID) => (
            <div
                key={`${sectionID}-${rowID}`}
                style={{
                    backgroundColor: '#F5F5F9',
                    height: 4,
                    borderTop: '1px solid #ECECED',
                    borderBottom: '1px solid #ECECED',
                }}
            />
        );


        const row = (rowData, sectionID, rowID) => {
            return (
                <div key={rowID} >
                <List className="am-list-content">
                <Item multipleLine onClick={() => { 
                    console.log("rowData", rowData)
                    if (null != rowID && '' != rowID) {
                        const { history } = this.props;
                        history.push({
                            pathname: '/machealthchecklogdetail',
                            state: {
                                func: this.state.func,//没有这段代码，页面不能跳转
                                rowData: rowData,
                            }
                        });
                    }
                }} 
                // extra={ rowData.isdone === true ? <Icon type='check-circle' color='#0f0'/>:"未完成"}
                >
                {rowData.ExtraDatas.devicecode}:{rowData.ExtraDatas.devicename}
                <Brief>单据日期:{rowData.BillDate}</Brief>
                
                </Item>
                </List>
                </div>
            );
        };
        return (
            <div>
                <Button onClick={this.addMaccheck}>新增</Button>
                <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>}
                    renderRow={row}
                    renderSeparator={separator}
                    className="am-list"
                    initialListSize={40}
                    // useBodyScroll
                    onScroll={() => { console.log('scroll'); }}
                    scrollRenderAheadDistance={500}
                    onEndReached={this.onEndReached}
                    onEndReachedThreshold={10}
                    style={{
                        height: this.state.height,
                        overflow: 'auto',
                      }}
                />
            </div>
        );
    }
}