import React from 'react';
import 'antd-mobile/dist/antd-mobile.css';
import {Toast, ListView, List, Icon, Checkbox,InputItem, Flex,Button,SearchBar} from 'antd-mobile';
import { Http } from '../../Utils/help';
import './less/list.less';

const Item = List.Item;
const Brief = Item.Brief;
export default class spotcheck extends React.Component {
    constructor(props) {
        super(props);
        this.NUM_SECTIONS = 1;
        this.NUM_ROWS_PER_SECTION = 50;
        this.genData = this.genData.bind(this);
        this.onEndReached = this.onEndReached.bind(this);
        this.isEmpty=this.isEmpty.bind(this);
        this.onSubmit = this.onSubmit.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,
            isLoading:false, 
            nodata: true,
            data: {},
            page:1,
            pageSize:10,
            my:false,
            creator:'',
            height: document.documentElement.clientHeight * 1,
            searchevalue:"",
            //条件保存
            ifin:false,//是否已保存过一次
            i:{},//若有，保存的对象，取出进行条件刷新
        };
    }
    //机台搜索调用函数
    onSubmit = () =>{
        //保存条件s
        //判断是否已存过一次
        window.conditionarr.map((data=>{
            // keys.push()
            if(data['key']==='spotcheck'){
                this.state.ifin=true
                this.state.i=data
                this.setState({ifin:true,i:data})
                return
            }
        }))
        if(this.state.ifin){
            this.state.i['value']['page']=this.state.page
            this.state.i['value']['pagesize']=this.state.pageSize
            this.state.i['value']['devcode']=this.state.searchevalue
        }
        else{
            window.conditionarr.push({key:'spotcheck',value:{page:1,pagesize:this.state.pageSize,devcode:this.state.searchevalue}})
            //保存条件S
            window.conditionarr.map((data=>{
            // keys.push()
            if(data['key']==='spotcheck'){
                this.state.ifin=true
                this.state.i=data
                this.setState({ifin:true,i:data})
                return
            }
            }))
        }
        //E
        this.setState({page:1})
        this.dataAjax = Http.getJSON2("machealthchecklog/devcodequery", {"devcode":this.state.searchevalue,"page":1, "pageSize":this.state.pageSize})
        .done(data=>{
            if(data.length==0){
                    if(this.state.searchevalue !== "" || this.state.searchevalue){
                        Toast.info('查无对应数据,请重新查询', 2);}
                    else{
                        Toast.info('没有点检单数据', 2);
                    }
            }
            this.genData(data);
            this.setState({
            dataSource: this.state.dataSource.cloneWithRowsAndSections(this.dataBlobs, this.sectionIDs, this.rowIDs),
            data:data,
            nodata:!data||data.length==0,
            isLoading:false,
            });                          
        })
    }
    //是否为空
    isEmpty = (obj) => {
        if (typeof obj === 'undefined' || obj == null || obj === '') {
            return true;
        } else {
            return false;
        }
    }
    onEndReached(event){
        if (this.state.isLoading && !this.state.hasMore) {
          return;
        }
        console.log('reach end', event);
        this.setState({ isLoading: true });
        let that = this;
        console.log(this.state.searchevalue)
        console.log('之前',this.state.page)
        //判断是直接加载全部还是按机台搜索
        if(this.state.searchevalue !== "" || this.state.searchevalue){
            this.dataAjax = Http.getJSON2("machealthchecklog/devcodequery", {"devcode":this.state.searchevalue,"page":++this.state.page, "pageSize":this.state.pageSize})
            .done((data) => {
                console.log("onEndReached:", data)
                if(data && data.length>0){
                    try {
                        var c = that.state.data.concat(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);
                    }
                }
            });      
        }
        else{
        //获取所有的点检单
            this.dataAjax = Http.getJSON2("machealthchecklog", {"page":++this.state.page, "pageSize":this.state.pageSize,"orderby": 'createtime desc'})
                .done((data) => {
                    console.log("onEndReached:", data.data)
                    if(data.data && data.data.length>0){
                        try {
                            //var c=data.data.concat(that.state.data);
                            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);
                        }
                    }
                });
        }
            this.setState({page:this.state.page})
            console.log('当前',this.state.page)
      }
    componentWillMount(){
        if(typeof(window.conditionarr)=="undefined"){window.conditionarr=[]}
        console.log("componentWillMount")
        window.conditionarr.map((data=>{
            // keys.push()
            if(data['key']==='spotcheck'){
                this.state.ifin=true
                this.state.i=data
                this.setState({
                    ifin:true,
                    i:data,
                    searchevalue:data['value']['devcode'],
                })
                return
            }
        }))
       
    }
    componentDidUpdate() {
    }
    componentDidMount() {
        console.log("componentDidMount")
        const creator = localStorage['loginid']
        this.setState({creator})
        this.setState({ isLoading: true });  
        //按照存储的条件请求
        window.conditionarr.map((data=>{
        // keys.push()
        if(data['key']==='spotcheck'){
        this.state.ifin=true
        this.state.i=data
        this.setState({ifin:true,i:data},()=>{
            if(this.state.ifin){
            this.setState({page:1}, () =>{
                Http.getJSON2("machealthchecklog/devcodequery", 
                {   'page':this.state.page,
                    'pagesize': this.state.pageSize,
                    'devcode':this.state.i['value']['devcode']
                }).done((data) =>{
                    try {
                        if(data.length==0){
                            if(this.state.searchevalue !== "" || this.state.searchevalue){
                                Toast.info('查无对应数据,请重新查询', 2);}
                            else{
                                Toast.info('没有点检单数据', 2);
                            }
                        }
                        this.genData(data);
                        this.setState({
                            dataSource: this.state.dataSource.cloneWithRowsAndSections(this.dataBlobs, this.sectionIDs, this.rowIDs),
                            data: data,
                            nodata: !data || data.length == 0,
                            isLoading: false,
                        });
                    } catch (err) {
                        console.error(err.message);
                        console.error(err.stack);
                    }
                })
            }) 
        }               
        })
        
    }
    }))
    if(!this.state.ifin){
        //获取所有的点检单
        this.dataAjax = Http.getJSON2("machealthchecklog", {"page":this.state.page, "pageSize":this.state.pageSize, "orderby": 'createtime desc'})
            .done((data) => {
                if(data.data.length==0){
                    Toast.info('没有点检单数据', 2);
                }
                if(data.data && data.data.length>0){
                    try {
                        //var c=data.data.concat(that.state.data);
                        this.genData(data.data);
                        this.setState({
                        dataSource: this.state.dataSource.cloneWithRowsAndSections(this.dataBlobs, this.sectionIDs, this.rowIDs),
                        data:data.data,
                        nodata:!data||data.length==0,
                        isLoading:false,
                        });
                    } 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];
    }

    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: '/spotcheckdetail',
                            state: {
                                func: this.state.func,//没有这段代码，页面不能跳转
                                rowData: rowData,
                            }
                        });
                    }
                }} 
                // extra={ rowData.isdone }
                >
                {/* {rowData.ExtraDatas.devicecode}:{rowData.ExtraDatas.devicename} */}
                
                机台:{rowData.ExtraDatas.devicecode}              
                <Flex>
                <Flex.Item><Brief>点检人:{!this.isEmpty(rowData.checker)?rowData.ExtraDatas.checkername:"暂无指定"}</Brief></Flex.Item>
                <Flex.Item><Brief>状态:{ rowData.isdone === 'True'? "已完成":"未完成"}</Brief></Flex.Item>
                </Flex>
                <Flex>
                <Flex.Item><Brief>单据日期:{rowData.BillDate}</Brief></Flex.Item>

                </Flex>
                
                </Item>
                </List>
                </div>
            );
        };
        return (
        <div>
            <div>
            <Flex>
                <Flex.Item style={{flex:1}}>
                    <SearchBar
                        placeholder='可输入机台号搜索'
                        value={this.state.searchevalue}
                        onSubmit={this.onSubmit}
                        onChange={(searchevalue)=>{
                            this.setState({searchevalue})
                        }}
                        onCancel={()=>{
                            console.log('取消')
                            this.setState({searchevalue:""},this.onSubmit)

                        }}

                    />
                </Flex.Item>
            </Flex>
           </div>
            <div>
                <ListView className= "am-list-header"
                    ref={el => this.lv = el}
                    dataSource={this.state.dataSource}
                    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>
    </div>
        );
    }
}