import React from 'react'
import 'antd-mobile/dist/antd-mobile.css';
import { CNavBar } from '../common/navbar.jsx';
import { Button, Flex, Card, List, WingBlank, WhiteSpace, Badge, DatePicker,Grid } from 'antd-mobile';
import { Http } from '../../Utils/help'
import Format from '../../Utils/NumericFormat';
import $ from 'jquery';
import PropTypes from 'prop-types'

const F2 = require('@antv/f2');
const PieLabel = require('@antv/f2/lib/plugin/pie-label');
const Item = List.Item;
const Brief = Item.Brief;

export default class dbalert extends React.Component {
    constructor(props,context) {
        super(props,context);
       // const { func } = this.props.location.state;
        this.StockageData = this.StockageData.bind(this);
        this.makeData = this.makeData.bind(this);
        this.macseparate = this.macseparate.bind(this);
        this.displayCurData = this.displayCurData.bind(this);
        this.cur_chartRender = this.cur_chartRender.bind(this);
        this.AjaxDone = this.AjaxDone.bind(this);
        
        this.state = {
           // func: func,
            macstatus:[],
            macalert:[],
            macalertlist:[],
            gddata: { "fun": [], "data": [] },
            dbalert: [],
            dbalertmactype: [],
            dbalertwktype: [],
            curmacalert:[],
            curmacalertlist:[],
            curmac:"",
            macdevtype:[],
            tag: {"now":'primary'},
            type:0,
            devdetail:false,
            color:{"IMMEDIATELY":"red","URGENCY":"#796161","HIGH":"#d4c032","NORMAL":"blue","无警报":"white"},
        }
    }
    
    //取得json数据集
    componentWillMount() {
        window.conditionarr=[]
        console.log("componentWillMount--");
        this.dataAjax = Http.getJSON2("ds/data/kb_dashboard/thedatealert",{ "alerttype": this.state.type },this.AjaxDone);
    }

    componentDidUpdate() {
    }

    componentDidMount() {
        console.log("componentDidMount--");
        //this.AjaxDone();
    }

    AjaxDone = (result) => {//提交成功
      //this.dataAjax.done((result) => {
        console.log(result);
        try {
            this.setState(
                {   
                    macstatus: this.macseparate(result,'e'),
                    macalert: this.macseparate(result,'f'),
                    macalertlist:this.macseparate(result,'g'),
                    macdevtype:this.macseparate(result,'c'),
                    dbalert: this.packageing(result,'a'),//a报警类型分类
                    dbalertmactype: this.packageing(result,'c'),
                    dbalertwktype: this.packageing(result,'d'),
                }, () => {
                    this.makeData(this.state.macstatus);
                    this.chartRender();
                }
            )
        } catch (error) {
            console.error(error.message);
            console.error(error.stack);
        }
      //})
    }

    macseparate = (values,atype) => {
        console.log("macseparate--" + atype);
       let vdate = []
       for (let i = 0; i < values.length; i++) {
          if (values[i].a == atype) {
            vdate.push(values[i])
           }
       }
      //console.log(vdate);
      return vdate;
    }

    curseparate = (values,atype) => {
        console.log("curseparate--" + atype);
           let vdate = []
           if (values) {
                for (let i = 0; i < values.length; i++) {
                    if (values[i].typename == atype) {
                        vdate.push(values[i])
                    }
                }
          }
          //console.log(vdate);
          return vdate;
        }

    //数据重新封装
    packageing = (values,atype) => {
        console.log("packageing--" + atype);
        //console.log(values)
        var vdate = '';
        if (values && values.length>0) {
            var code = "";
            for (let i = 0; i < values.length; i++) {
                if (values[i].a == atype){
                    if (values[i].typename != code) {
                        vdate = vdate.substring(0, vdate.length - 1) + ']},{"typename":"' + values[i].typename + '","data":[' + JSON.stringify(values[i]) + ',';
                        code = values[i].typename;
                    } else {
                        vdate = vdate + (JSON.stringify(values[i])) + ',';
                    }
                }
            }
            //console.log('[' + vdate.substring(3, vdate.length - 1) + ']}]');
            if (vdate!=""){
              vdate = '[' + vdate.substring(3, vdate.length - 1) + ']}]';
            }
            else{
              vdate = '{}'
            }
            vdate = JSON.parse(vdate)
        }
        //console.log(vdate);
        return vdate;
    }

    chartRender = () => {
        console.log("chartrender...")
        this.StockageData(this.state.dbalert,this.state.dbalertmactype,this.state.dbalertwktype,this.state.macdevtype)
    }

    StockageData = (dbalert,dbalertmactype,dbalertwktype,macdevtype) => {
        let mycolor = this.state.color;
        dbalert.map((i, index) => {
            try {
                const chart = new F2.Chart({
                    id: "alert"+i.typename,
                    pixelRatio: window.devicePixelRatio,
                    plugins: PieLabel
                  });
                  chart.source(i.data);
                  chart.coord('polar', {
                    transposed: true,
                    radius: 0.9,
                    innerRadius: 0.5
                  });
                  chart.axis(false);
                  chart.legend(false);
                  chart.tooltip(false);
                  chart.guide().html({
                    position: ['50%', '50%'],
                    html: '<div style="text-align: center;width:150px;height: 50px;">\n      <p style="font-size: 12px;color: #999;margin: 0" id="name"></p>\n      <p style="font-size: 18px;color: #343434;margin: 0;font-weight: bold;" id="num"></p>\n      </div>'
                  });
                  
                  //chart.interval().position('a*num').adjust('stack').color('name', ['#1890FF', '#13C2C2', '#2FC25B', '#FACC14']);
                  chart.interval().position('a*num').adjust('stack').color('name', function (name) {
                    return mycolor[name];
                  })

                  chart.pieLabel({
                    sidePadding: 30,
                    activeShape: true,
                    label1: function label1(data) {
                      return {
                        text: '' + data.num,
                        fill: '#343434',
                        fontWeight: 'bold'
                      };
                    },
                    label2: function label2(data) {
                      return {
                        text: data.name,
                        fill: '#999'
                      };
                    },
                    onClick: function onClick(ev) {
                      var data = ev.data;
                      if (data) {
                        $('#name').text(data.name);
                        $('#num').text(data.num);
                      }
                    }
                  });
                  chart.render();
          
               } catch (error) {
                 console.error(error.message)
               }
        }, this);

        if (macdevtype!=null){
         try{
          var chart = new F2.Chart({
            id: 'macdevtype01',
            pixelRatio: window.devicePixelRatio
          });
          chart.source(macdevtype, {
            '报警机型分布': {
              tickCount: 5
            }
          });
          chart.tooltip({
            // onChange: function onChange(obj) {
            //   var legend = chart.get('legendController').legends.top[0];
            //   var tooltipItems = obj.items;
            //   var legendItems = legend.items;
            // },
            // onHide: function onHide() {
            //   var legend = chart.get('legendController').legends.top[0];
            //   legend.setItems(chart.getLegendItems().country);
            // }
          });
          //chart.interval().position('typename*num').color('name').adjust('stack');
          chart.interval().position('typename*num').adjust('stack').color('name', function (name) {
            return mycolor[name];
          })
          chart.render();
        }
        catch (error) {
           console.error(error.message)
         }
       }
      }

    getdevice = (el, index) => {
        this.setState(
            {   
                curmac:this.state.gddata.fun[index].typename,
                curmacalert: this.curseparate(this.state.macalert,this.state.gddata.fun[index].typename),
                curmacalertlist: this.curseparate(this.state.macalertlist,this.state.gddata.fun[index].typename),
            }, () => {
                this.cur_chartRender();
            }
        )
    }

    cur_chartRender = () => {
        console.log("cur_chartrender...")
        this.displayCurData(this.state.curmacalert,this.state.curmacalertlist)
    }

    displayCurData = (curmacalert,curmacalertlist) => {
           let mycolor = this.state.color;
            try {
                const chart = new F2.Chart({
                    id: "curalert",
                    pixelRatio: window.devicePixelRatio,
                    plugins: PieLabel
                  });
                  chart.source(curmacalert);
                  chart.coord('polar', {
                    transposed: true,
                    radius: 0.9,
                    innerRadius: 0.5
                  });
                  chart.axis(false);
                  chart.legend(false);
                  chart.tooltip(false);
                  chart.guide().html({
                    position: ['50%', '50%'],
                    html: '<div style="text-align: center;width:150px;height: 50px;">\n      <p style="font-size: 12px;color: #999;margin: 0" id="name"></p>\n      <p style="font-size: 18px;color: #343434;margin: 0;font-weight: bold;" id="num"></p>\n      </div>'
                  });
                 // chart.interval().position('a*num').adjust('stack').color('name', ['#1890FF', '#13C2C2', '#2FC25B', '#FACC14']);
                 chart.interval().position('a*num').adjust('stack').color('name', function (name) {
                    return mycolor[name]
                 })
                  chart.pieLabel({
                    sidePadding: 30,
                    activeShape: true,
                    label1: function label1(data) {
                      return {
                        text: '' + data.num,
                        fill: '#343434',
                        fontWeight: 'bold'
                      };
                    },
                    label2: function label2(data) {
                      return {
                        text: data.name,
                        fill: '#999'
                      };
                    },
                    onClick: function onClick(ev) {
                      var data = ev.data;
                      if (data) {
                        $('#name').text(data.name);
                        $('#num').text(data.num);
                      }
                    }
                  });
                  chart.render();
          
               } catch (error) {
                 console.error(error.message)
               }
    }

    makeData = (nodedata) => {
        if (!nodedata || !Array.isArray(nodedata)) {
          return;
        }
        let newdata = {};
        nodedata.map((data, index) => {
          // console.log("data数据：",data)
          let nd = {};
          let nodeimg;
         //nodeimg = data.name == '0' ? 'h2.png' : data.name != '0' ? (data.name == '1' ? 'h3.png' : 'red1.png') : 'h2.png';
          nodeimg = 'red1.png';
          nd["icon"] = require('../../images/' + nodeimg);
          nd["text"] = data.typename
          nd["status"] = data.name
          if (!newdata.fun)
          newdata = { "fun": [], "data": [] };
          newdata.fun[newdata.fun.length] = data;
          newdata.data[newdata.data.length] = nd;
        });
        this.setState({
          gddata: newdata,
        });
    }

    onChange = (value) => {
        let type = this.state.type==0?"now":"before"
        let ntype =value=="now"?0:1
        if (value !== type) {
                let tag = this.state.tag
                tag = {}
                tag[value] = 'primary'
                this.setState({
                    tag: tag,
                    type: ntype,
                    curmac:""
        },()=>{
            this.onOk();
          });
        }
        //this.dataAjax = Http.getJSON2("ds/data/kbmacalertcon/kbmacalertlist", { "devcode": this.state.mac[1], "type": this.state.type },this.dataProcess);
    };

    onOk = () => {
         this.dataAjax = Http.getJSON2("ds/data/kb_dashboard/thedatealert", { "alerttype": this.state.type },this.AjaxDone);
    }

    onswitchDev = (value) => {
      this.setState(
          {   
            devdetail:this.state.curmac == value?this.state.devdetail+1:0,
          },
        )
    }

    onClickLink = (val, code) => {
      console.log(val)
      const { router } = this.context;
      if(val==="dbalert"){
      router.push({
          pathname: '/macstatusnowinfo',
          state: {
              code: code,
              type: 'day',
          }
      }); }
    }

    render() {
        return (
            <div key={"key1"} style={{ height: '100%' }}>
            <Card style={{ marginTop: 5 }}>
                <Card.Header
                   title={
                    <div><div style={{ fontSize: '16px', color: 'gray'}}></div>
                      <div style={{ height: 'auto', textAlign: 'center' }}>
                        <Flex>
                          <Flex.Item>
                            <Button key="now" checked={this.state.tag["now"]} size="small"    style={{backgroundColor:this.state.tag["now"]?"#108ee9":"white"}}  onClick={e => this.onChange("now")}>当前警报</Button>
                          </Flex.Item>
                          <Flex.Item>
                            <Button key="before" checked={this.state.tag["before"]} size="small"  style={{backgroundColor:this.state.tag["before"]?"#108ee9":"white"}}  onClick={e =>this.onChange("before")}>历史警报</Button>
                          </Flex.Item>
                        </Flex>
                     </div> 
                   </div>}

                    // extra={
                    //     <Button type="ghost" size="small" inline onClick={() => {
                    //         if (true) {
                    //             console.log("Click 更多");
                    //             const { history } = this.props;
                    //             history.push({
                    //                 pathname: '/macstatuslist',
                    //                 state: {
                    //                 }
                    //             });
                    //         }
                    //     }}>更多>></Button>
                    //    }  
                 />
                <Card.Body >
                        <Grid data={this.state.gddata.data}
                            columnNum={5}
                            hasLine={false}
                            
                            renderItem={dataItem => (
                                <div style={(this.state.devdetail%2==0 && this.state.curmac==dataItem.text)?{display:"block", float:left,border:"1px solid gray"}:{}} >
                                <img onClick={e => this.onswitchDev(dataItem.text)}
                                      src={dataItem.icon} style={{ width: '60%', height: '60%', marginTop: '0px',border:2 }}/>
                                <div style={{ fontSize: '11px', marginTop: '0px' }}>
                                    <span>{<div style={{ color: dataItem.status == 0 ? 'gray' : dataItem.status == 1 ? 'gray' : 'gray'}}>{dataItem.text}</div>} </span>
                                </div>
                                </div>
                            )}
                            onClick={this.getdevice}
                        />
                       {this.state.curmac!="" && this.state.devdetail%2==0?
                        <Card>
                            <Card.Header
                               title={<div style={{ fontSize: '13px', color: 'gray'} } onClick={() => this.onClickLink('dbalert', this.state.curmac)}><u>{this.state.curmac}</u> {" 报警"}</div>}
                            />
                            <Card.Body>
                                <div style={{ width: "100%", height: "200px", margin: "0 auto" }}>
                                    <canvas id={"curalert" } style={{ width: "100%", height: "100%" }}></canvas>
                                </div>
                              <Card.Header
                                title={<div style={{ fontSize: '13px', color: '#1890FF'}}>{"报警明细"}</div>}
                              />
                              <Card.Body>
                                {this.state.curmacalertlist.map((i, index) => (
                                <Card>
                                    <Card.Header
                                        title={<div style={{ fontSize: '13.5px', color: 'gray'}}>{i.alertname}</div>}
                                    />
                                    <Card.Body>
                                        <div style={{fontSize:'13px',width: "100%", height: "100px", margin: "0 auto" }}>
                                          <span>{<div><div style={{color:'gray',display:'inline'}}>{"等级: "}</div><div style={{color:i.name=='NORMAL'?'gray':'red',display:'inline'}}>{i.name}</div></div>}</span>
                                          <br></br>
                                          <span>{<div style={{color:'gray'}}>{"发生时间: "+i.btime}</div>} </span>
                                          <br></br>
                                          <span>{<div style={{color:'gray'}}>{"结束时间: "+i.etime}</div>} </span>
                                          <br></br>
                                          <span>{<div><div style={{color:'gray',display:'inline'}}>{"时长: "}</div><div style={{color:i.delaytime<'30'?'gray':'red',display:'inline'}}>{i.delaytime}</div><div style={{color:'gray',display:'inline'}}>{" 分"}</div></div>}</span>
                                        </div>
                                    </Card.Body>
                                </Card>
                              ))}
                              </Card.Body>
                            </Card.Body>
                        </Card>
                       :
                       <div style={{textAlign:'center',width: "100%", height: "200px", margin: "0 auto" }}>
                          <p>暂无数据</p>
                       </div>  
                       }
                </Card.Body>
            </Card>
       
            <WhiteSpace size="lg" />
             <Card key={"key2"} >
                    <Card.Header
                       title={<div style={{ fontSize: '16px', color: 'gray'}}>报警--类型分布</div>}
                    />
                    <Card.Body>
                      {this.state.dbalert &&this.state.dbalert>0?
                      <div>
                      {this.state.dbalert.map((i, index) => (
                        <Card>
                            <Card.Header
                              title={<div style={{ fontSize: '13px', color: 'gray'}}>{i.typename + " 报警"}</div>}
                            />
                            <Card.Body>
                                <div style={{ width: "100%", height: "200px", margin: "0 auto" }}>
                                    <canvas id={"alert" + (i.typename)} style={{ width: "100%", height: "100%" }}></canvas>
                                </div>
                            </Card.Body>
                        </Card>
                        ))}
                  </div>
                  :
                  <div style={{ textAlign:'center'}}>
                  <p>暂无数据</p>
                  </div>
                  }
                   </Card.Body>
              </Card>
              <WhiteSpace size="lg" />

              <Card key={"key3"}>
                    <Card.Header
                        title={<div style={{ fontSize: '16px', color: 'gray'}}>报警--机型分布</div>}
                    />
                    <Card.Body>
                      {this.state.macdevtype && this.state.macdevtype.length>0?
                         <div style={{ width: "100%", height: "200px", margin: "0 auto" }}>
                           <canvas id={"macdevtype01"} style={{ width: "100%", height: "100%" }}></canvas>
                        </div>
                        :
                        <div style={{textAlign:'center',width: "100%", height: "200px", margin: "0 auto" }}>
                          <p>暂无数据</p>
                        </div>  
                      }
                     </Card.Body>
                </Card>
                <WhiteSpace size="lg" />

                {/* <Card key={"key4"}>
                    <Card.Header
                            title={<div style={{ fontSize: '16px', color: 'gray'}}>报警--车间分布</div>}
                    />
                    <Card.Body>
                      {this.state.dbalertwktype.map((i, index) => (
                        <Card>
                            <Card.Header
                                title={<div style={{ fontSize: '13px', color: 'gray'}}>{i.typename + " 报警"}</div>}
                            />
                            <Card.Body>
                                <div  key={"wktype"+index} style={{ width: "100%", height: "200px", margin: "0 auto" }}>
                                    <canvas id={"wktype" + (i.typename)} style={{ width: "100%", height: "100%" }}></canvas>
                                </div>
                            </Card.Body>
                        </Card>
                        ))}
                   </Card.Body>
                </Card>
                <WhiteSpace size="lg" /> */}
            </div>
        )
    }
}
dbalert.contextTypes = {
  router: PropTypes.object.isRequired
}