import React, { useRef, useEffect, useState } from 'react';
import { Button, Select, message, Popconfirm } from 'antd';

import services from '@/services/admin';

const { shopTree, shopItems } = services.ShopController;

import G6 from '@antv/g6';

export default () => {
  const ref = React.useRef(null);

  const [shopTreeData, setShopTreeData] = useState(null);
  const [shopOption, setShopOption] = useState([]);
  const [shop, setShop] = useState(0);

  const defaultLayout = {
    type: 'compactBox',
    direction: 'TB',
    getId: function getId(d) {
      return d.id;
    },
    getHeight: function getHeight() {
      return 16;
    },
    getWidth: function getWidth() {
      return 16;
    },
    getVGap: function getVGap() {
      return 40;
    },
    getHGap: function getHGap() {
      return 70;
    },
  };

  G6.registerNode(
    'icon-node',
    {
      options: {
        size: [40, 20],
        stroke: '#91d5ff',
        fill: '#91d5ff',
      },
      draw(cfg, group) {
        const styles = this.getShapeStyle(cfg);
        const { labelCfg = {} } = cfg;

        const w = styles.width;
        const h = styles.height;
        let color = 'rgb(28 25 23)';
        if (cfg.device_num === 0) {
          color = 'rgb(220 38 38)';
        }

        const keyShape = group.addShape('rect', {
          attrs: {
            ...styles,

            x: -w / 2,
            y: -h / 2,
          },
        });

        if (cfg.label) {
          group.addShape('text', {
            attrs: {
              ...labelCfg.style,
              text: cfg.label,
              fill: color,
              x: 10 - w / 2,
              y: 25 - h / 2,
            },
          });
        }
        return keyShape;
      },
      update: undefined,
    },
    'rect',
  );

  G6.registerEdge('flow-line', {
    draw(cfg, group) {
      const startPoint = cfg.startPoint;
      const endPoint = cfg.endPoint;

      const { style } = cfg;
      const shape = group.addShape('path', {
        attrs: {
          stroke: style.stroke,
          endArrow: style.endArrow,
          path: [
            ['M', startPoint.x, startPoint.y],
            ['L', startPoint.x, (startPoint.y + endPoint.y) / 2],
            ['L', endPoint.x, (startPoint.y + endPoint.y) / 2],
            ['L', endPoint.x, endPoint.y],
          ],
        },
      });

      return shape;
    },
  });

  const defaultStateStyles = {
    hover: {
      stroke: '#1890ff',
      lineWidth: 2,
    },
  };

  const defaultNodeStyle = {
    fill: '#91d5ff',
    stroke: '#40a9ff',
    radius: 5,
  };

  const defaultEdgeStyle = {
    stroke: '#91d5ff',
    endArrow: {
      path: 'M 0,0 L 12, 6 L 9,0 L 12, -6 Z',
      fill: '#91d5ff',
      d: -20,
    },
  };

  const defaultLabelCfg = {
    style: {
      fill: '#000',
      fontSize: 10,
    },
  };

  const minimap = new G6.Minimap({
    size: [150, 100],
  });

  let graph = null;

  useEffect(() => {
    shopTree({ shop_id: shop }).then(({ data, success }) => {
      if (success) {
        setShopTreeData(data || null);
      }
    }).catch(() => {

    });
  }, [shop]);


  useEffect(() => {
    if (shopTreeData) {
      graph = new G6.TreeGraph({
        container: ref.current,
        width: 1000,
        height: 500,
        linkCenter: true,
        plugins: [minimap],
        modes: {
          default: ['drag-canvas', 'zoom-canvas'],
        },
        defaultNode: {
          type: 'icon-node',
          size: [120, 40],
          style: defaultNodeStyle,
          labelCfg: defaultLabelCfg,
        },
        defaultEdge: {
          type: 'flow-line',
          style: defaultEdgeStyle,
        },
        nodeStateStyles: defaultStateStyles,
        edgeStateStyles: defaultStateStyles,
        layout: defaultLayout,
      });
      graph?.data(shopTreeData);
      graph?.render();
      graph?.fitView();
    }

  }, [shopTreeData])

  const searchShop = (value) => {
    if (graph) {
      graph.destroy()
    }
    shopItems({
      username: value
    }).then(({ data }) => {
      const arr = [];
      data?.data?.map((item) => {
        item.label = `${item.username}   ${item.mobile}`;
        arr.push(item);
      });
      setShopOption(arr);
    });
  }


  return (
    <>
      <div className='text-3xl font-bold	text-slate-900	'>投资人关系图</div>
      <div className='h-3.5'></div>
      <Select
        allowClear
        showSearch
        placeholder="请输入用户名"
        style={{ width: "100%" }}
        filterOption={false}
        onSearch={
          (e) => {
            if (!e) {
              return;
            }
            searchShop(e);
          }
        }
        onChange={(value) => {
          setShop(value);
        }}
        fieldNames={{
          label: "label",
          value: "id"
        }}
        options={shopOption}
      />
      <div className='h-6'></div>
      <Button onClick={() => {
        if (graph) {
          graph.destroy()
        }
      }}>清空画布</Button>
      <div className='h-6'></div>
      <div ref={ref}>

      </div>
    </>
  );
};
