import EmptySpace from '@/components/EmptySpace';
import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';
import services from '@/services';
import { useModel } from '@umijs/max';
import ReactEcharts from 'echarts-for-react';
import { useMemo, useRef } from 'react';

interface TraceSourceOfLostPointsProps {
  data: any;
  objectId?: string;
  showLostPoints?: boolean;
  style?: React.CSSProperties;
}

const TraceSourceOfLostPoints: React.FC<TraceSourceOfLostPointsProps> = (
  props,
) => {
  const { data, showLostPoints, objectId } = props;
  const { dispatch } = useGlobalModalServices();

  const { initialState } = useModel('@@initialState');
  const { areaId } = initialState;
  const echartsRef = useRef<any>(null)

  //递归设置数据
  const deepData = (data: any[]) => {
    let newData: any = [];
    data?.forEach((item) => {
      item['value'] = item?.lostScore > 0 ? `-${item?.lostScore}` : '';
      item['collapsed'] = true;
      newData.push(item);
      if (item.children && item.children.length) {
        item.children = deepData(item.children);
      }
    });
    return newData;
  };

  const handleDataCollapsed = (data: any) => {
    data?.forEach((item: any) => {
      item.collapsed = false
      if (item.children && item.children.length) {
        item.children.forEach((v: any) => {
          v.collapsed = true;
        });
      }
    });
    return data;
  };

  const option = {
    title: {
      text: '',
    },

    tooltip: {
      show: true,
      trigger: 'item',
      formatter: showLostPoints ? '{b}: {c}' : '{b}',
    },
    toolbox: {
      show: false,
    },

    calculable: false,
    series: [
      {
        symbol: 'roundRect',
        edgeForkPosition: '20%',
        name: '树图',
        type: 'tree',
        // orient: 'horizontal', // vertical horizontal
        rootLocation: {
          x: '50%',
          y: '15%',
        }, // 根节点位置  {x: 'center',y: 10}
        // nodePadding: 20,
        // layerPadding: 40,
        roam: true,
        width: '80%',
        height: '100%',
        left: '8%',
        right: '5%',
        top: '5%',
        bottom: '0',
        itemStyle: {
          normal: {
            color: 'transparent', //节点背景色
            borderCap: 'round',
            lineStyle: {
              color: '#4C86BB',
              width: 2,
              type: 'solid', // 'curve'|'broken'|'solid'|'dotted'|'dashed'
            },
          },
          emphasis: {
            label: {
              show: true,
            },
          },
        },
        label: {
          formatter: (param: any) => {
            if (showLostPoints) {
              return [`{a|${param.data.name}}{b|${param.data.value}}`].join('\n');
            } else {
              return [`{a|${param.data.name}}`].join('\n');
            }
          },
          rich: {
            a: {
              align: 'center',
              color: '#fff',
              // width: 128,
              padding: [10, 20, 8, 20],
              height: 40,
              fontSize: 20,
              labelLayout: {
                align: 'center',
              },
              backgroundColor: '#265D90',
              borderRadius: showLostPoints ? [16, 0, 0, 16] : 16,
              borderWidth: 1,
              borderColor: '#265D90',
            },
            b: {
              align: 'center',
              fontSize: 20,
              fontWeight: 700,
              height: 40,
              padding: [10, 20, 8, 0],
              fontFamily: 'CustomFont',
              color: '#f75d5d',
              backgroundColor: '#265D90',
              borderRadius: [0, 16, 16, 0],
              borderWidth: 1,
              borderColor: '#265D90',
            },
          },
        },
        data: handleDataCollapsed(deepData(data?.children?.length ? [data] : [])),
      },
    ],
  };

  const getOptions = useMemo(() => {
    return option;
  }, [data]);

  const onChartClick = (params: any) => {
    const { data } = params;
    // data.collapsed = false
    console.log(data)
    if (data.lastFlag === '1' && showLostPoints) {
      console.log('点击了lastFlag2节点');
      console.log('jump InfluenceSign')
      dispatch.push('InfluenceSignNew', {
        title: `${data.name}问题`,
        props: {
          data: data,
          objectId: objectId
        },
      });
      // services.Physicalsign.getlistTopNItems({
      //   indexType: data.indexType,
      //   physicalSignType: 1,
      //   objectId: areaId,
      //   indexId: data.id,
      //   n: 100,
      // }).then((res) => {
      //   if (res.code === 200) {
      //     const resdata: any = res.data;
      //     if (resdata?.length) {
      //       data.children = resdata?.map((v: any) => {
      //         return {
      //           ...v,
      //           name: v.conditionName,
      //           collapsed: false,
      //           value: v.deduction > 0 ? `-${v.deduction}` : ''
      //         }
      //       })
      //       console.log(data)
      //       const series = echartsRef.current?.getEchartsInstance()?._model.option.series
      //       console.log(series)
      //       // 更新
      //       echartsRef.current?.getEchartsInstance().setOption({ series: series })
      //     }
      //   }
      // });
    }
    // if (data?.conditionId) {
    //   console.log('jump InfluenceSign')
    //   dispatch.push('InfluenceSign', {
    //     props: {
    //       data: data,
    //     },
    //   });
    // }
  };

  return (
    <>
      {data?.children?.length ? (
        <ReactEcharts
          ref={echartsRef}
          option={getOptions}
          onEvents={{ click: onChartClick }}
          style={{ height: '600px' }}
        />
      ) : (
        <EmptySpace describe="暂无数据" style={{ padding: '29% 0' }} />
      )}
    </>
  );
};
export default TraceSourceOfLostPoints;
