import React, { useRef, useEffect, useState, useCallback } from 'react';
import { withRouter } from 'next/router';
import * as echarts from 'echarts'
import _ from 'lodash'
import Footer from '../../../components/screen/Footer';
import Header from '../../../components/screen/Header';
import Row from '../../../components/screen/Row';
import Card from '../../../components/screen/Card';
import Chart from '../../../components/screen/Chart';
import Table from '../../../components/screen/Table';
import InfoCardList from '../../../components/screen/InfoCardList';
import io from '../../../utils/socket.io.js';

const gutter = 20;
const bottom = 20;

const polarBarOpt = {
  title: {
    text: '',
    left: 'center',
    top: 24,
  },
  legend: {
    data: ['时间稼动率', '性能稼动率', '良品率'],
    bottom: 43,
    orient: 'vertical',
    itemHeight: 18,
    textStyle: {
      fontSize: 14,
      lineHeight: 20,
    },
  },
  polar: {
    radius: ['20%', '90%'],
    center: ['50%', '40%'],
  },
  angleAxis: {
    show: false,
    max: 100,
    startAngle: 90,
  },
  radiusAxis: {
    show: false,
    type: 'category',
    data: ['%']
  },
  tooltip: {
    formatter: '{a}'
  },
  series: [{
    name: '时间稼动率',
    type: 'bar',
    barGap: '0',
    barWidth: 14,
    data: [],
    coordinateSystem: 'polar',
  }, {
    name: '性能稼动率',
    type: 'bar',
    barGap: '0',
    barWidth: 14,
    data: [],
    coordinateSystem: 'polar',
  }, {
    name: '良品率',
    type: 'bar',
    barGap: '0',
    barWidth: 14,
    data: [],
    coordinateSystem: 'polar',
  }]
};
const setPolarBarOpt = (values, title) => {
  values = values.map(i => (i * 100).toFixed(2));
  values = values.map(i => {
    if (isNaN(i)) i = '0.00';
    return i;
  });
  const names = ['时间稼动率  ', '性能稼动率  ', '良品率        '];
  let res = _.cloneDeep(polarBarOpt);
  if (title) res.title.text = title;
  values[0] !== undefined && (res.series[0].data[0] = values[0]);
  values[1] !== undefined && (res.series[1].data[0] = values[1]);
  values[2] !== undefined && (res.series[2].data[0] = values[2]);
  res.legend.data = names.map((name, index) => name = values[index] !== undefined ? name + ` ${values[index]}%` : name);
  res.series = res.series.map((item, index) => {
    values[index] !== undefined && (item.name = names[index] + ` ${values[index]}%`);
    return item;
  })
  return res;
}

const lineOpt = {
  legend: {
    data: ['OEE'],
    top: 10,
    right: 10,
    textStyle: {
      fontSize: 14,
    },
  },
  xAxis: {
    type: 'category',
    axisTick: {
      lineStyle: { opacity: 0.3 },
      alignWithLabel: true,
    },
    axisLine: {
      lineStyle: { opacity: 0.3 },
    },
    axisLabel: {
      color: 'rgba(255, 255, 255, 0.8)'
    },
  },
  yAxis: {
    type: 'value',
    max: 100,
    axisTick: {
      lineStyle: { opacity: 0.3 }
    },
    axisLine: {
      lineStyle: { opacity: 0.3 }
    },
    axisLabel: {
      formatter: '{value}%',
      color: 'rgba(255, 255, 255, 0.8)'
    },
  },
  grid: {
    bottom: 40,
    top: 110,
    left: 50,
  },
  tooltip: {
    formatter: data => `${data.value[0]}：${data.value[1]}%`,
  },
  series: {
    name: "OEE",
    data: [],
    type: 'line',
    color: "#50D9B0",
    label: {
      show: true,
      position: 'top',
      formatter: data => `${data.value[1]}%`,
      textBorderColor: 'rgba(0, 0, 0, 0)',
      color: '#fff'
    },
    symbolSize: 8,
    lineStyle: {
      color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
        offset: 0, color: 'rgba(255, 225, 50, 0.54)'
      }, {
        offset: 1, color: 'rgb(45, 240, 219)'
      }])
    },
    areaStyle: {
      opacity: 0.4,
      color: new echarts.graphic.LinearGradient(0, 1, 1, 1, [{
        offset: 0, color: 'rgba(255, 225, 50, 0)'
      }, {
        offset: 1, color: 'rgb(1, 191, 236)'
      }])
    },
  }
};
const setLineOpt = data => {
  let res = _.cloneDeep(lineOpt);
  res.series.data = data;
  return res;
}
const getOEEnearWeekTrendInfo = (data) => {
  let total = 0;
  let max = 0;
  console.log("data", data)
  data.forEach(([day, val]) => {
    total = total + val;
    if (val > max) max = val;
  })
  let average = (parseInt(total * 100 / data.length)) / 100;
  if (isNaN(average)) average = 0;
  return [max, average]
}

const getQueryVariable = (variable) => {
  let query = window.location.search.substring(1);
  let vars = query.split("&");
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split("=");
    if (pair[0] == variable) { return pair[1]; }
  }
  return (false);
}

let data = {
  "code": "0000",
  "extra": {
    "PieChart": {
      "SY_TIME": 0.442,
      "DT_GOODPRODUCT": 0.12,
      "SY_GOODPRODUCT": 0.12,
      "DY_GOODPRODUCT": 0.12,
      "DT_PERFORMANCE": 0.52,
      "DT_TIME": 0.27,
      "DY_TIME": 0.33999999999999997,
      "DY_PERFORMANCE": 0.32999999999999996,
      "SY_PERFORMANCE": 0.431
    },
    "TrendChart": {
      "03-31": 0.0514,
      "04-10": 0.9423,
      "04-11": 0.2197,
      "04-12": 0.8591,
      "04-13": 0.3331,
      "04-08": 0.2534,
      "04-09": 0.4141
    },
    "EquipStatus": [{
      "phenomenonCode": "YC001",
      "equipName": "窑炉1号",
      "phenomenonName": "1002,1003,啊啊啊啊啊啊",
      "equipCode": "YL001"
    }, {
      "phenomenonCode": "BBB",
      "equipName": "111",
      "phenomenonName": "1003,iiiiiiiii",
      "equipCode": "YL006"
    }, {
      "phenomenonCode": "请求",
      "equipName": "除磁001",
      "phenomenonName": "请求",
      "equipCode": "CC001"
    }],
    // "EquipData": {
    //   "C001": [{
    //       "code": "code",
    //       "name": "name",
    //       "temp": "32", // 温度
    //       "rps": "11", // 转速
    //       "ia": "12", // 电流
    //       "ua": "13", // 电压
    //       "runningstatus": "87" // 运行状态
    //   }]
    // },
    "EquipData": {
      "CC": [
        {
          "equipCode": "123456789",
          "equipName": "测试设备-dwj",
          "fileCode": "9NO0EXP6MXQ3VHSN1OTS5OXZ2463PWZ8F247B02EF9CKHCP90F0TJHIV6HFMX148YIS3GONKYDAWLLWXS4GNPJUGG4O17PF6DEFIN94B549A0Y5XCWMB4IUDKSY62D0F7ZWQ32364DF7D9FB3E584D63QM5JHMLU33T5NXWQGPWDOXWL0K9I71RCUXY1OJ64FSXW9NB912L9J7NYUFK45YF8YLXYQA402E667DAA82A558675E26D345EFD35747",
          "opCode": "CC",
          "opName": "除磁",
          "runningstatus": null,
          "shipList": []
        }
      ],
      "XM": [
        {
          "equipCode": "eqtest419",
          "equipName": "设备测试419",
          "fileCode": "01TR2HYCOOH6APN22DUFA9P5EHCQ6WK9FA1B789C3CU087W5R57HC704LEOFQK69SAX02I2T329SKVELGB686CEC5KLJPA6ML7J8S3451196V9KYFSFSELQA0CINDS2B4HBCIAFF389A4BC89DCHQVSFX41AY8PAI7HTZC8UKY00ZZ1KDM3LHSLNMWDEE3X0YA81EZ0BGMLMHXSW4R1INRW7ZCYIA7XU7BB35C97C67D63F9390C342479E1A150",
          "opCode": "XM",
          "opName": "细磨",
          "runningstatus": null,
          "shipList": [
            {
              "data": null,
              "deleted": false,
              "displayWork": false,
              "fieldSort": "1",
              "flag": null,
              "gid": "1681416533722673152",
              "iotField": "ty1",
              "iotFieldDescribe": "信号1",
              "iotIsMainField": true,
              "iotIsalarm": false,
              "iottype": "string",
              "relationGid": "1621704831515373568",
              "serialNumber": null,
              "status": true
            },
            {
              "data": null,
              "deleted": false,
              "displayWork": false,
              "fieldSort": "2",
              "flag": null,
              "gid": "1681424290735599616",
              "iotField": "ty2",
              "iotFieldDescribe": "信号2",
              "iotIsMainField": true,
              "iotIsalarm": false,
              "iottype": "string",
              "relationGid": "1621704831515373568",
              "serialNumber": null,
              "status": true
            },
            {
              "data": null,
              "deleted": false,
              "displayWork": false,
              "fieldSort": "4",
              "flag": null,
              "gid": "1681424290769154048",
              "iotField": "ty4",
              "iotFieldDescribe": "信号4",
              "iotIsMainField": true,
              "iotIsalarm": false,
              "iottype": "string",
              "relationGid": "1621704831515373568",
              "serialNumber": null,
              "status": true
            },
            {
              "data": null,
              "deleted": false,
              "displayWork": false,
              "fieldSort": "5",
              "flag": null,
              "gid": "1681424290802708480",
              "iotField": "ty5",
              "iotFieldDescribe": "信号5",
              "iotIsMainField": true,
              "iotIsalarm": false,
              "iottype": "string",
              "relationGid": "1621704831515373568",
              "serialNumber": null,
              "status": true
            },
            {
              "data": null,
              "deleted": false,
              "displayWork": false,
              "fieldSort": "3",
              "flag": null,
              "gid": "1681556221980717056",
              "iotField": "ty3",
              "iotFieldDescribe": "信号3",
              "iotIsMainField": true,
              "iotIsalarm": false,
              "iottype": "string",
              "relationGid": "1621704831515373568",
              "serialNumber": null,
              "status": true
            }
          ]
        }
      ],
      "BZ": [
        {
          "equipCode": "PP001",
          "equipName": "设备小明 001",
          "fileCode": "1LM22ETECZCV25GCIUBNQRI5P96TA4I3AAE19CD0FCKWVLO17UI4KHG9HDX1R0MHMRKYWRTGCRF0IZ3HVL2EOTQUWZELDJS0OORIB44AB680W7K2DTXZVRF68FAI8SKPAOJ3UD0D203F20551EANV7C8580PMMRN4I67F070AN0IZJL76S2UKUQ7O6ATMKMGZ8NWPOAIEW75LRMZMNPD0GLZ06AKTD5W7FA073DC704B06D1FE9CDC08E156FB61",
          "opCode": "BZ",
          "opName": "包装",
          "runningstatus": null,
          "shipList": []
        }
      ],
      "TL": [
        {
          "equipCode": "L5_TLXT_B01",
          "equipName": "L5_TLXT_B01设备",
          "fileCode": "ZCFNP5MUJORD07O3N3SYM81VRH443R8F4A20A141A68H75DL162LU6XYA5QS4TWZN2CEKIKOJOVX6UE2CL6YRFMV6EFN0YAVH0SEZ14945A57UZ9JD466RKDULDMONJU3XPZMEA4E868EFF6BEDJ8YCQG2P61SKEJS4M82JBYXEV7L7S41E02S3NMC6S7JJ9EIO0EORRZP2STV73L0LGPKH6N6JXVCL163615505CB9899AD60CABB886B5E2B92",
          "opCode": "TL",
          "opName": "投料",
          "runningstatus": "2",
          "shipList": [
            {
              "data": "104.9",
              "deleted": false,
              "displayWork": false,
              "fieldSort": "1",
              "flag": null,
              "gid": "1682683971810504704",
              "iotField": "ChnSL_WG1_TL2_TL2_DB_AI_DB4_472",
              "iotFieldDescribe": "信号472",
              "iotIsMainField": true,
              "iotIsalarm": false,
              "iottype": "string",
              "relationGid": "1682681371711123456",
              "serialNumber": null,
              "status": true
            },
            {
              "data": "746.7",
              "deleted": false,
              "displayWork": false,
              "fieldSort": "2",
              "flag": null,
              "gid": "1682683971894390784",
              "iotField": "ChnSL_WG1_TL2_TL2_DB_AI_DB4_148",
              "iotFieldDescribe": "信号148",
              "iotIsMainField": true,
              "iotIsalarm": false,
              "iottype": "string",
              "relationGid": "1682681371711123456",
              "serialNumber": null,
              "status": true
            },
            {
              "data": "699.4",
              "deleted": false,
              "displayWork": false,
              "fieldSort": "3",
              "flag": null,
              "gid": "1682683971860836352",
              "iotField": "ChnSL_WG1_TL2_TL2_DB_AI_DB4_168",
              "iotFieldDescribe": "信号168",
              "iotIsMainField": true,
              "iotIsalarm": false,
              "iottype": "string",
              "relationGid": "1682681371711123456",
              "serialNumber": null,
              "status": true
            },
            {
              "data": "462",
              "deleted": false,
              "displayWork": false,
              "fieldSort": "5",
              "flag": null,
              "gid": "1682853205282795520",
              "iotField": "ChnSL_WG1_TL2_TL2_DB_AI_DB4_400",
              "iotFieldDescribe": "信号400",
              "iotIsMainField": true,
              "iotIsalarm": false,
              "iottype": "string",
              "relationGid": "1682681371711123456",
              "serialNumber": null,
              "status": true
            }
          ]
        },
        {
          "equipCode": "L5_YMXT_A01",
          "equipName": "L5_YMXT_A01设备",
          "fileCode": "NGERX0JN0T2MNEZ8Z98XT7LKTKZ4D266EC596DDD8BVZM0KFO36T79MYAF4VY15VH76T12ID0XRJV6P2RG53MBE1U5HP0FDPAH8V554BC6A42BS7SB79ZP0X8S2U655EPDF3MC9309151D5558D4JQYD6CB3JQJ5J0H82EJOHJUTWOBUL5Y4L9I97OMP5BWP2I7K1E7ACEDWOC88TZOL48H4THCXA0AV15D0290575E73FB8B736A503522EE1D3",
          "opCode": "TL",
          "opName": "投料",
          "runningstatus": "2",
          "shipList": [
            {
              "data": "0",
              "deleted": false,
              "displayWork": false,
              "fieldSort": "1",
              "flag": null,
              "gid": "1682898429577146368",
              "iotField": "ChnSL_WG1_YM1_YM1_DB4_DB4_350",
              "iotFieldDescribe": "350信号",
              "iotIsMainField": true,
              "iotIsalarm": true,
              "iottype": "string",
              "relationGid": "1682897844270411776",
              "serialNumber": null,
              "status": true
            }
          ]
        }
      ],
      "FS": [
        {
          "equipCode": "CS001",
          "equipName": "测试1号设备aaa",
          "fileCode": null,
          "opCode": "FS",
          "opName": "粉碎",
          "runningstatus": null,
          "shipList": []
        }
      ]
    }
  },
  "message": "OK",
  "success": true
}
data = JSON.stringify(data);

function Equipment(props) {
  const { config: { ioSocketUrl, equipmentConfig = {} } = {} } = global;
  const { equipListNext: listToNextPage, equipAbnormalNext: tableToNextPage } = equipmentConfig;

  const { router } = props;

  const socket = useRef();
  const getData = () => {
    // let {workCenterCode} = router.query;
    let workCenterCode = getQueryVariable('workCenterCode');
    let date = getQueryVariable('date');
    console.log("fetch", workCenterCode)
    if (!workCenterCode) return;

    // console.log("00000", {
    //   workCenterCode,
    //   date,
    //   screenType: "EquipDashBoardType",
    // });
    let query = {
      workCenterCode,
      screenType: "EquipDashBoardType",
    }
    if (date) query.date = date;
    else {
      query.date = new Date().toJSON().split("T").join(" ").substr(0, 10);
    }
    
    // console.log("query", {query})
    socket.current.emit('timePerformanceGoodProduct', 'channel', {query})

    // update(data)
  };

  const OEEonDay = useRef();
  const OEEonMonth = useRef();
  const OEELastMonth = useRef();
  const OEEnearWeekTrend = useRef();
  const equipTableRef = useRef();
  const infoCardListRef = useRef();
  const [oEEnearWeekTrendInfo, setOEEnearWeekTrendInfo] = useState([0, 0]);

  const tableTimeoutRef = useRef();
  const listTimeoutRef = useRef();
  
  const [{DT_OEE, DY_OEE, SY_OEE}, setOEE] = useState({})

  const update = useCallback(data => {
    try { data = JSON.parse(data) } catch (e) { console.log(e) }
    const { PieChart = {}, TrendChart = {}, EquipStatus = [], EquipData = [],energySummary = [],recentAlert = []} = data.extra || {};
  // energySummary = {
  //   "2022-08-19": {
  //     packingWeight: 0.0,
  //     packingQty: 0.0,
  //     gas: 10626.98,
  //     electricity: 101161.97,
  //     feedingWeight: 76002.0,
  //     water: 60551.0,
  //   },
  //   "2022-08-20": {
  //     packingWeight: 861.0,
  //     packingQty: 2.0,
  //     gas: 3555.55,
  //     electricity: 50378.71,
  //     feedingWeight: 27102.0,
  //     water: 24655.0,
  //   }
  // };

  // recentAlert = [
  //   {
  //     duration: 18677,
  //     eliminationTime: "2022-08-20 11:20:18",
  //     field: "ChnSL_WG1_TL2_TL2_BJ_DB3_0_4",
  //     fuzzyDate: "5小时12分钟",
  //     phenomenonName: " SL-101下料阀故障2",
  //     equipCode: "L5_TLXT_B01",
  //     alertTime: "2022-08-20 06:09:01",
  //   },
  //   {
  //     duration: 18574,
  //     eliminationTime: "2022-08-20 11:20:20",
  //     field: "ChnSL_WG1_TL2_TL2_BJ_DB3_1_6",
  //     fuzzyDate: "5小时10分钟",
  //     phenomenonName: " SL-103下料阀故障2",
  //     equipCode: "L5_TLXT_B01",
  //     alertTime: "2022-08-20 06:10:46",
  //   },
  //   {
  //     duration: 16931,
  //     eliminationTime: "2022-08-20 06:04:13",
  //     field: "ChnSL_WG1_TL2_TL2_BJ_DB3_0_4",
  //     fuzzyDate: "4小时43分钟",
  //     phenomenonName: " SL-101下料阀故障2",
  //     equipCode: "L5_TLXT_B01",
  //     alertTime: "2022-08-20 01:22:02",
  //   },
  //   {
  //     duration: 16832,
  //     eliminationTime: "2022-08-20 06:04:17",
  //     field: "ChnSL_WG1_TL2_TL2_BJ_DB3_1_6",
  //     fuzzyDate: "4小时41分钟",
  //     phenomenonName: " SL-103下料阀故障2",
  //     equipCode: "L5_TLXT_B01",
  //     alertTime: "2022-08-20 01:23:45",
  //   },
  //   {
  //     duration: 9365,
  //     eliminationTime: "2022-08-20 06:44:59",
  //     field: "ChnSL_WG5_HDSS_HDSS_BJ_DB25_9_2",
  //     fuzzyDate: "2小时37分钟",
  //     phenomenonName: "QF-616阀门故障",
  //     equipCode: "HDSSZDX001",
  //     alertTime: "2022-08-20 04:08:54",
  //   },
  //   {
  //     duration: 9203,
  //     eliminationTime: "2022-08-20 13:58:34",
  //     field: "ChnSL_WG1_TL2_TL2_BJ_DB3_0_4",
  //     fuzzyDate: "2小时34分钟",
  //     phenomenonName: " SL-101下料阀故障2",
  //     equipCode: "L5_TLXT_B01",
  //     alertTime: "2022-08-20 11:25:11",
  //   },
  //   {
  //     duration: 9054,
  //     eliminationTime: "2022-08-20 13:58:37",
  //     field: "ChnSL_WG1_TL2_TL2_BJ_DB3_1_6",
  //     fuzzyDate: "2小时31分钟",
  //     phenomenonName: " SL-103下料阀故障2",
  //     equipCode: "L5_TLXT_B01",
  //     alertTime: "2022-08-20 11:27:43",
  //   },
  //   {
  //     duration: 7636,
  //     eliminationTime: "2022-08-20 13:35:05",
  //     field: "ChnSL_WG5_HDSS_HDSS_BJ_DB25_9_2",
  //     fuzzyDate: "2小时8分钟",
  //     phenomenonName: "QF-616阀门故障",
  //     equipCode: "HDSSZDX001",
  //     alertTime: "2022-08-20 11:27:49",
  //   },
  //   {
  //     duration: 7221,
  //     eliminationTime: "2022-08-20 01:17:08",
  //     field: "ChnSL_WG1_TL2_TL2_BJ_DB3_0_4",
  //     fuzzyDate: "2小时1分钟",
  //     phenomenonName: " SL-101下料阀故障2",
  //     equipCode: "L5_TLXT_B01",
  //     alertTime: "2022-08-19 23:16:47",
  //   },
  //   {
  //     duration: 7084,
  //     eliminationTime: "2022-08-20 01:17:10",
  //     field: "ChnSL_WG1_TL2_TL2_BJ_DB3_1_6",
  //     fuzzyDate: "1小时59分钟",
  //     phenomenonName: " SL-103下料阀故障2",
  //     equipCode: "L5_TLXT_B01",
  //     alertTime: "2022-08-19 23:19:06",
  //   },
  //   {
  //     duration: 6484,
  //     eliminationTime: "2022-08-20 08:38:23",
  //     field: "ChnSL_WG5_HDSS_HDSS_BJ_DB25_9_2",
  //     fuzzyDate: "1小时49分钟",
  //     phenomenonName: "QF-616阀门故障",
  //     equipCode: "HDSSZDX001",
  //     alertTime: "2022-08-20 06:50:19",
  //   },
  //   {
  //     duration: 4652,
  //     eliminationTime: "2022-08-20 15:46:19",
  //     field: "ChnSL_WG5_HDSS_HDSS_BJ_DB25_9_2",
  //     fuzzyDate: "1小时18分钟",
  //     phenomenonName: "QF-616阀门故障",
  //     equipCode: "HDSSZDX001",
  //     alertTime: "2022-08-20 14:28:47",
  //   },
  //   {
  //     duration: 2331,
  //     eliminationTime: "2022-08-20 13:05:20",
  //     field: "ChnSL_WG1_YM1_YM1_BJ_M150_7",
  //     fuzzyDate: "39分钟",
  //     phenomenonName: " 粗磨机1总故障",
  //     equipCode: "L5_YMXT_A01",
  //     alertTime: "2022-08-20 12:26:29",
  //   },
  //   {
  //     duration: 2331,
  //     eliminationTime: "2022-08-20 13:05:20",
  //     field: "ChnSL_WG1_YM1_YM1_BJ_M150_4",
  //     fuzzyDate: "39分钟",
  //     phenomenonName: " 粗磨机1出料温度报警",
  //     equipCode: "L5_YMXT_A01",
  //     alertTime: "2022-08-20 12:26:29",
  //   },
  //   {
  //     duration: 1898,
  //     eliminationTime: "2022-08-20 15:33:21",
  //     field: "ChnSL_WG1_YM1_YM1_BJ_M150_7",
  //     fuzzyDate: "32分钟",
  //     phenomenonName: " 粗磨机1总故障",
  //     equipCode: "L5_YMXT_A01",
  //     alertTime: "2022-08-20 15:01:43",
  //   },
  //   {
  //     duration: 1898,
  //     eliminationTime: "2022-08-20 15:33:21",
  //     field: "ChnSL_WG1_YM1_YM1_BJ_M150_4",
  //     fuzzyDate: "32分钟",
  //     phenomenonName: " 粗磨机1出料温度报警",
  //     equipCode: "L5_YMXT_A01",
  //     alertTime: "2022-08-20 15:01:43",
  //   },
  //   {
  //     duration: 1667,
  //     eliminationTime: "2022-08-20 11:23:50",
  //     field: "ChnSL_WG1_YM1_YM1_BJ_M150_7",
  //     fuzzyDate: "28分钟",
  //     phenomenonName: " 粗磨机1总故障",
  //     equipCode: "L5_YMXT_A01",
  //     alertTime: "2022-08-20 10:56:03",
  //   },
  //   {
  //     duration: 1667,
  //     eliminationTime: "2022-08-20 11:23:50",
  //     field: "ChnSL_WG1_YM1_YM1_BJ_M150_4",
  //     fuzzyDate: "28分钟",
  //     phenomenonName: " 粗磨机1出料温度报警",
  //     equipCode: "L5_YMXT_A01",
  //     alertTime: "2022-08-20 10:56:03",
  //   },
  //   {
  //     duration: 1280,
  //     eliminationTime: "2022-08-20 04:54:41",
  //     field: "ChnSL_WG2_ylzdx1_ylzdx_1_bj_DBX85_3",
  //     fuzzyDate: "22分钟",
  //     phenomenonName: "下方输送管道故障_11",
  //     equipCode: "YLZDX001",
  //     alertTime: "2022-08-20 04:33:21",
  //   },
  //   {
  //     duration: 1160,
  //     eliminationTime: "2022-08-20 13:32:12",
  //     field: "ChnSL_WG1_YM1_YM1_BJ_M150_7",
  //     fuzzyDate: "20分钟",
  //     phenomenonName: " 粗磨机1总故障",
  //     equipCode: "L5_YMXT_A01",
  //     alertTime: "2022-08-20 13:12:52",
  //   },
  // ];
    console.log("data", data)

    // 1 OEE趋势
    let {
      DT_TIME, DT_PERFORMANCE, DT_GOODPRODUCT,
      DY_TIME, DY_PERFORMANCE, DY_GOODPRODUCT,
      SY_TIME, SY_PERFORMANCE, SY_GOODPRODUCT,
    } = PieChart;
    let DT_OEE = DT_TIME * DT_PERFORMANCE * DT_GOODPRODUCT;
    let DY_OEE = DY_TIME * DY_PERFORMANCE * DY_GOODPRODUCT;
    let SY_OEE = SY_TIME * SY_PERFORMANCE * SY_GOODPRODUCT;
    DT_OEE = (DT_OEE * 100).toFixed(2) + "%";
    DY_OEE = (DY_OEE * 100).toFixed(2) + "%";
    SY_OEE = (SY_OEE * 100).toFixed(2) + "%";
    setOEE({DT_OEE, DY_OEE, SY_OEE})
    try {
      OEEonDay.current.setOption(setPolarBarOpt([
        DT_TIME, DT_PERFORMANCE, DT_GOODPRODUCT
      ], "当日OEE"));
      OEEonMonth.current.setOption(setPolarBarOpt([
        DY_TIME, DY_PERFORMANCE, DY_GOODPRODUCT,
      ], "当月OEE"));
      OEELastMonth.current.setOption(setPolarBarOpt([
        SY_TIME, SY_PERFORMANCE, SY_GOODPRODUCT,
      ], "上月OEE"));
    } catch (e) { }

    // 2 近一周OEE趋势图
    let lineData = [];
    try {
      for (let time in TrendChart || {}) {
        let timeCode = new Date(time).getTime()
        lineData.push([time, parseFloat((TrendChart[time] * 100).toFixed(2)), timeCode])
      }
      // console.log("lineData", lineData)
      lineData.sort((a, b) => {
        let [,,code1] = a;
        let [,,code2] = b;
        return code1 - code2;
      })
      OEEnearWeekTrend.current.setOption(setLineOpt(lineData));
      setOEEnearWeekTrendInfo(getOEEnearWeekTrendInfo(lineData));
    } catch (e) { }

    // 3 设备异常监控
    try {
      recentAlert.map(item=>{
        item.alertTime=item.alertTime.substring(5,item.alertTime.length);
        item.eliminationTime=item.eliminationTime.substring(5,item.eliminationTime.length);
      })
      equipTableRef.current.setData(recentAlert);
      let getNextPage = () => {
        clearTimeout(tableTimeoutRef.current);
        tableTimeoutRef.current = setTimeout(() => {
          equipTableRef.current.nextPage();
          getNextPage();
        }, tableToNextPage)
      };
      getNextPage();
    } catch (e) { }

    // 4 设备运行状态
    let withClassifyData = [];
    // console.log("EquipData", EquipData)
    console.log("res get")
    try {
      for (let name in EquipData) {
        withClassifyData.push({ name, children: EquipData[name] })
      }
      infoCardListRef.current.setData(withClassifyData);
      try {
      infoCardListRef.current.setEnergy(energySummary);
      } catch (error) {
        console.log(error)

      }
      let getNextPage = () => {
        clearTimeout(listTimeoutRef.current);
        listTimeoutRef.current = setTimeout(() => {
          infoCardListRef.current.nextPage();
          getNextPage();
        }, listToNextPage)
      };
      getNextPage();
    } catch (e) { }
  }, [])

  const listFinished = useCallback(() => {
    console.log("finished")
    clearTimeout(listTimeoutRef.current);
    clearTimeout(tableTimeoutRef.current);
    getData();
  }, [update])

  useEffect(() => {
    const { workCenterCode } = router.query;
    if (!workCenterCode) return;

    console.log("ioSocketUrl", ioSocketUrl)
    socket.current = io.connect(ioSocketUrl, {transports:['websocket']});

    socket.current.on('connect', function () {
      console.log("msg页面连接成功！");
      getData();
    });

    socket.current.on('timePerformanceGoodProduct', function (data) {
      // console.log("data", data)
      update(data)
    });

    // update(data)

  }, [router])

  return (// 683 733 424
    <div className='screen-container'>
      <Header title={"设备看板"} />
      <div className="screen-container-content">
        <Row style={{ height: '50.55%' }} gutter={gutter} bottom={bottom}>
          <Row.Col style={{ width: '33%' }}>
            <Card title="OEE趋势" titleSpace={true} overVisible={true}>
              <Row className='height-100'>
                <Row.Col span={8} gutter={10}>
                  {DT_OEE && <div className="OEE"> {DT_OEE} </div>}
                  <Chart ref={OEEonDay} />
                </Row.Col>
                <Row.Col span={8}>
                  {DY_OEE && <div className="OEE"> {DY_OEE} </div>}
                  <Chart ref={OEEonMonth} />
                </Row.Col>
                <Row.Col span={8}>
                  {SY_OEE && <div className="OEE"> {SY_OEE} </div>}
                  <Chart ref={OEELastMonth} />
                </Row.Col>
              </Row>
            </Card>
          </Row.Col>
          <Row.Col style={{ width: '33%' }}>
            <Card title="近一周OEE趋势图" overVisible={true}>
              <div className="OEEnearWeekTrend-info">
                <span className="item">最高OEE ：{oEEnearWeekTrendInfo[0]}%</span>
                <span className="item">平均OEE ：{oEEnearWeekTrendInfo[1]}%</span>
              </div>
              <Chart ref={OEEnearWeekTrend} />
            </Card>
          </Row.Col>
          <Row.Col style={{ width: '34%' }}>
            <Card title="设备异常监控" titleSpace={true} padding={`${gutter}px`}>
              <Table
                ref={equipTableRef}
                mainKey="equipCode"
                columns={[
                  { title: "设备编码", code: "equipCode" },
                  { title: "告警内容", code: "phenomenonName" },
                  { title: "告警发生时间", code: "alertTime" },
                  { title: "告警消除时间", code: "eliminationTime" },
                  { title: "告警时长", code: "fuzzyDate" },
                ]}
              />
            </Card>
          </Row.Col>
        </Row>
        <Row style={{ height: '49.45%' }} gutter={gutter}>
          <Row.Col span={24}>
            <Card title="设备运行状态&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" titleSpace={false} padding={`0px ${gutter}px`}>
              <InfoCardList
                ref={infoCardListRef}
                mainKey={"code"}
                type={'page'}
                withClassify={true}
                classifyKey={{ name: 'name', children: 'children' }}
                autoNext={false}
                pageFinished={listFinished}
                span={equipmentConfig.equipListSpan}
                imgKey={"fileCode"}
                status={{
                  key: "runningstatus",
                  value: val => {
                    if (val === '1') return "待机中";
                    if (val === '2') return "运行中";
                    if (val === '3') return "停机中";
                  },
                  color: val => {
                    if (val === '1') return "#F5A623";
                    if (val === '2') return "#58BC17";
                    if (val === '3') return "#FF005A";
                  },
                }}
                columns={[
                  { title: "设备编号", code: "equipCode" },
                  { title: "设备名称", code: "equipName" },
                ]}
                extraColumnsOpt={{
                  key: "shipList",
                  name: "iotFieldDescribe",
                  val: "data",
                  max: equipmentConfig.equipItemLength - 2
                }}
                contentHeight={12 + 28 * equipmentConfig.equipItemLength}
              />
            </Card>
          </Row.Col>
        </Row>
      </div>
      <Footer />
      <style jsx>{`
        .screen-container{
          height: 100vh;
          min-height: 1080px;
          min-width: 1920px;
          overflow: auto;
          background: url('/img/bg.png') center center;
          position: relative;
          padding-top: 96px;
          padding-bottom: 82px;
        }
        .screen-container-content{
          height: 100%;
          padding: 0 ${gutter}px;
        }
        .OEEnearWeekTrend-info{
          position: absolute;
          top: 46px;
          left: 20px;
          z-index: 1;
          font-size: 16px;
          background: rgba(216, 216, 216, 0.08);
          padding: 8px 12px;
        }
        .OEEnearWeekTrend-info > .item{
          margin-right: 40px;
        }
        .OEE{
          font-size: 18px;
          position: absolute;
          top: 38%;
          left: 50%;
          transform: translateX(-50%);
          font-family: 'RubikRegular';
        }
       
      `}</style>
    </div>
  );
}

export default withRouter(Equipment)