import React from 'react';
import 'antd-mobile/dist/antd-mobile.css';
import { Card, WingBlank, WhiteSpace, Button, Flex } from 'antd-mobile';
import { Http } from '../../Utils/help';
import Format from '../../Utils/NumericFormat';
import PropTypes from 'prop-types';


const F2 = require('@antv/f2');
const PieLabel = require('@antv/f2/lib/plugin/pie-label');

export default class MacStatusOEE extends React.Component {
    constructor(props, context) {
        super(props, context);
        const { func } = this.props.location.state;
        this.state = {
            func: func,
            oeedata: [],
            topdev: [],
            tag: { 'DAY': 'primary' },
            type: 'DAY',
            typech: '日',
            orderby: '升序',
        };
    }

    componentDidMount() {
        window.conditionarr=[]
        console.log("componentDidMount...")
        this.loadData_t();
    }

    loadData_t = () => {
        this.dataAjax = Http.getJSON2("ds/data/macstatusoee/oee", { "type": this.state.type }).done((result) => {
            // try {
            console.log(result)
            this.setState({
                oeedata: this.getChartData(result, 'data'),
                topdev: this.getChartData(result, 'dev')
            }, () => {
                this.chartRender();
            });
            // } catch (err) {
            //     console.error(err.message);
            //     console.error(err.stack);
            // }
        });
    }

    getChartData = (data, sign) => {
        if(data.length <= 0)
        return
        let redata = []
        if (data) {
            data.map(val => {
                if (val.type === sign) {
                    redata.push(val)
                }
            })
        }
        return redata
    }

    chartRender = () => {
        if (this.state.oeedata && JSON.stringify(this.state.oeedata) !== '[]')//机台今日开机时间占比
            this.ChartRender(this.state.oeedata, 'oee')
        // if (this.state.topdev && JSON.stringify(topdev) !== '[]')
        //     this.chartRender(this.state.topdev, 'dev')

    }

    ChartRender = (linedata, sign) => {
        console.log('ChartRender:', linedata, sign, this.state.type)
        //排序
        function sortdayweek(a, b){
            return a.ddate.replace(/[-]/g,'') - b.ddate.replace(/[-]/g,'')
        }
        function sortmonth(a, b){
            return Date.parse(a.ddate) - Date.parse(b.ddate)
        }
        if(this.state.type === 'DAY'){
            linedata.sort(sortdayweek)
        }
        if(this.state.type === 'WEEK'){
            linedata.sort(sortdayweek)
        }
        if(this.state.type === 'MONTH'){
            linedata.sort(sortmonth)
        }
        try {
            var chart = new F2.Chart({
                id: sign,
                pixelRatio: window.devicePixelRatio
            });
            chart.source(linedata, {
                ratio: {
                    tickCount: 4
                }
            });
            // console.log(this.state.type)
            if (this.state.type === 'DAY') {
                chart.scale('ddate', {
                    type: 'timeCat',
                    tickCount: 6,
                    mask: 'MM-DD',
                    range: [0, 1],
                });

                chart.axis('ddate', {
                    line: null,
                    label: {
                        rotate: -Math.PI / 2,
                        textAlign: 'end',
                        textBaseline: 'middle'
                      }
                });
            } else if(this.state.type === 'WEEK'){
                chart.scale('ddate', {
                    type: 'cat',
                    tickCount: 6,
                    formatter:function formatter(value){
                        let retval = value.substring(2,7)
                        return retval
                    }
                });
                chart.axis('ddate', {
                    line: null,
                    label: {
                        rotate: -Math.PI / 2,
                        textAlign: 'end',
                        textBaseline: 'middle'
                      }
                });
            }else if(this.state.type === 'MONTH'){
                chart.scale('ddate', {
                    type: 'cat',
                    tickCount: 6,
                    formatter: function formatter(value) {
                        //let retval = value.replace(/\s*/g, "")//.substring(4, 20)
                        let retval = value.substring(2,7)
                        return retval
                    }
                });
                chart.axis('ddate', {
                    line: null,
                    label: {
                        rotate: -Math.PI / 2,
                        textAlign: 'end',
                        textBaseline: 'middle'
                      }
                });
            }
            chart.axis('ratio', {
                grid: function grid(text) {
                    if (text === '0%') {
                        return {
                            lineDash: null,
                            lineWidth: 1
                        };
                    }
                }
            });

            chart.tooltip({
                showCrosshairs: true,
                showItemMarker: false,
                onShow: function onShow(ev) {
                    console.log(ev)
                    var items = ev.items;
                    if (items && JSON.stringify(items) !== '[]') {
                        items.map((val, ind) => {
                            items[ind].name = items[ind].name;
                            items[ind].value = items[ind].value + '%';
                        })
                    }
                }
            });

            chart.legend({
                position: 'bottom',
                offsetY: -5
            });
            chart.line().position('ddate*ratio').color('querytype').shape('smooth');
            chart.point().position('ddate*ratio').color('querytype').shape('smooth');
            chart.render();
        } catch (error) {
            console.error(error.message)
            console.error(error.stack)
        }
    }

    ButtonOnChange = (value) => {
        if (value !== this.state.type) {
            let tag = this.state.tag
            tag = {}
            tag[value] = 'primary'
            this.setState({
                tag: tag,
                type: value,
                typech: value === 'DAY' ? '日' : value === 'WEEK' ? '周' : '月',
            }, () => {
                this.loadData_t()
            });
        }
    };

    //排序
    compare = (x, y) => {
        if (this.state.orderby === '升序') {
            return y.ind - x.ind
        } else {
            return x.ind - y.ind
        }
    }
    MacClick = (val) => {
        console.log(val)
        const { router } = this.context;
        router.push({
            pathname: '/macstatusnowinfo',
            state: {
                code: val,
                status: '',
            }
        });
    }

    render() {
        return (
            <div>
                <WhiteSpace size="md" />
                <WingBlank size="md">
                    <div style={{ height: 'auto', textAlign: 'center' }}>
                        <Flex>
                            <Flex.Item>
                                <Button key='DAY' size="small" type={this.state.tag['DAY']} onClick={(e) => this.ButtonOnChange('DAY')} >日</Button>
                            </Flex.Item>
                            <Flex.Item>
                                <Button key='WEEK' size="small" type={this.state.tag['WEEK']} onClick={(e) => this.ButtonOnChange('WEEK')}>周</Button>
                            </Flex.Item>
                            <Flex.Item>
                                <Button key='MONTH' size="small" type={this.state.tag['MONTH']} onClick={(e) => this.ButtonOnChange('MONTH')}>月</Button>
                            </Flex.Item>
                        </Flex>
                    </div>
                </WingBlank>
                <WhiteSpace size="md" />
                <WingBlank size="md">
                    <Card style={{ height: 'auto' }}>
                        <Card.Body >
                            <div style={{ paddingBottom: '30px', borderBottom: '2px solid #ddd' }}>
                                <div style={{ fontSize: '15px', color: '#111E27', fontWeight: "bold", position: 'absolute', left: '20px', top: '15px' }}>{"当前" + this.state.typech + "OEE"}</div>
                                <div style={{ position: 'absolute', right: '20px', top: '10px' }}>
                                    <Button type="ghost" size="small" inline onClick={() => {
                                        const { router } = this.context;
                                        router.push({
                                            pathname: '/oee',
                                            state: {
                                                func: '',
                                            }
                                        });
                                    }}>详情</Button>
                                </div>
                            </div>
                            {this.state.oeedata&&this.state.oeedata>0?
                            <div style={{ width: '100%', height: 'auto', margin: "0 auto" }}>
                                <canvas id='oee' style={{ width: '100%', height: 'auto' }}></canvas>
                            </div>
                            :
                            <div style={{ textAlign:'center'}}>
                            <p>暂无数据</p>
                            </div>
                            }
                        </Card.Body>
                    </Card>
                </WingBlank>
                <WhiteSpace size="md" />
                <WingBlank size="md">
                    <Card style={{ height: 'auto' }}>
                        <Card.Body >
                            <div style={{ height: '30px', borderBottom: '2px dashed #ddd' }}>
                                <div style={{ fontSize: '15px', color: '#111E27', fontWeight: "bold", position: 'absolute', left: '20px', top: '15px' }}>{"当前" + this.state.typech + "OEE机台"}</div>
                                <div style={{ position: 'absolute', right: '20px', top: '10px' }}>
                                    <Button type="ghost" size="small" inline onClick={() => {
                                        this.state.topdev.sort(this.compare)
                                        this.setState({ orderby: this.state.orderby === '升序' ? '降序' : '升序' })
                                    }}>{this.state.orderby}</Button>
                                </div>
                            </div>
                            <div style={{ height: '25px' }}>
                                <div style={{ paddingTop: '10px', width: '25%', float: 'left', textAlign: 'center' }}>机台 </div>
                                <div style={{ paddingTop: '10px', width: '25%', float: 'left', textAlign: 'center' }}>时间</div>
                                <div style={{ paddingTop: '10px', width: '25%', float: 'left', textAlign: 'center' }}>性能</div>
                                <div style={{ paddingTop: '10px', width: '25%', float: 'left', textAlign: 'center' }}>OEE</div>
                            </div>
                            <WhiteSpace size="md" />
                            <div>
                                {this.state.topdev && this.state.topdev.length > 0 ? this.state.topdev.map((dataItem, ind) =>
                                    <div
                                        key={dataItem.ddate}
                                        style={{ backgroundColor: ind % 2 > 0 ? '' : '#FDF5E6', width: '100%', height: '20px', fontSize: '14px', paddingBottom: '6px', borderTop: '3px solid #ddd' }}
                                    >
                                        <div style={{ paddingTop: '6px', width: '25%', float: 'left', textAlign: 'center' }} onClick={(e) => this.MacClick(dataItem.ddate)}><u>{dataItem.ddate}</u>  </div>
                                        <div style={{ paddingTop: '6px', width: '25%', float: 'left', textAlign: 'center' }}>{dataItem.timeratio ? dataItem.timeratio + '%' : ''}</div>
                                        <div style={{ paddingTop: '6px', width: '25%', float: 'left', textAlign: 'center' }}>{dataItem.speedratio ? dataItem.speedratio + '%' : ''}</div>
                                        <div style={{ paddingTop: '6px', width: '25%', float: 'left', textAlign: 'center' }}>{dataItem.devratio}%</div>
                                    </div>
                                ) : 
                                <div style={{ textAlign:'center'}}>
                                <p>暂无数据</p>
                               </div>
                                
                                }
                            </div>
                        </Card.Body>
                    </Card>
                </WingBlank>
                <WhiteSpace size="md" />
            </div >
        )
    }
}

MacStatusOEE.contextTypes = {
    router: PropTypes.object.isRequired
}