import React, { useEffect } from 'react';
import { Topology, registerNode } from '@topology/core';
import { register as registerFlow } from '@topology/flow-diagram';
import { register as registerActivity } from '@topology/activity-diagram';
import { register as registerClass } from '@topology/class-diagram';
import { register as registerSequence } from '@topology/sequence-diagram';
import { register as registerChart } from '@topology/chart-diagram';
import { getRealData } from '../services/index';
import { powerPointItemMap } from '../constants';
import './ltdx.css';
import './ltee.css'; 
import './style.less';
// import './fonts/iconfont.css';
// import './fonts/libs/iconfont.css';

let canvas;

const getPowerPoint = data => {
  const res = data.map(v => [v.id, v.data.powerPoint]).filter(v => v[1]);
  return res;
};

const showPowerPointData = (data, powerPoints) => {
  const powerPointsRes = powerPoints.map(v => v.value);
  const penIdList = powerPointsRes.map(v => v[0]);
  const powerPointsData = powerPointsRes.map(v => v[1]);
  data.forEach(v => {
    penIdList.forEach((penId, index) => {
      if (v.id == penId) {
        const { powerPointKey = [] } = v.data;
        const dataKey = powerPointKey;
        if (powerPointKey.length > 0) {
          const powerPointsStr = dataKey
            .map(
              key =>
                `${powerPointItemMap[key]}`.padEnd(10, ' ') +
                `${powerPointsData[index][key] ?? '无'}`,
            )
            .join(`\n`);
          v.text = powerPointsStr;
        }
      }
    });
  });
};

const Preview = props => {
  useEffect(() => {
    registerFlow();
    registerActivity();
    registerClass();
    registerSequence();
    registerChart();
    const canvasOptions = {
      rotateCursor: '/rotate.cur',
      locked: 1,
    };
    canvas = new Topology('topology-canvas-preview', canvasOptions);
    props.data.locked = 1;
    canvas.open(props.data);
  }, []);

  useEffect(() => {
    const powerPoint = getPowerPoint(props.data.pens);
    const getPowerPointRealList = async params => {
      const [penId, point_id] = params;
      // const res = await getRealData(
      //   11238,
      //   '0061859369',
      //   1,
      // );
      const res = await getRealData(
        props.number,
        props.stationId,
        point_id,
      );
      return [penId, res.data.bean];
    };

    let timer = null;

    const handleRequest = async () => {
      if (powerPoint.length) {
        const res = await Promise.allSettled(
          powerPoint.map(v => getPowerPointRealList(v)),
        );
        showPowerPointData(props.data.pens, res);
        canvas.open(props.data);
      } else {
        clearInterval(timer);
      }
    };
    timer = setInterval(handleRequest, 10000);
    return () => {
      clearInterval(timer);
    };
  }, [props.data, props.show]);

  return (
    <div id="topology-canvas-preview" className="previewContainer"></div>
  );
};

export default Preview;
