import { message, Form } from 'ant-design-vue/es';
import { reactive, watch } from 'vue';
import { graphG6 } from './useGraph';
import useI18n from '@/hooks/useI18n';

export default function useNode() {
  const { t } = useI18n();

  /**图节点内置边类型 */
  const nodeTypeOptions = [
    {
      value: 'circle',
      label: t('views.monitor.topologyBuild.nodeTypeCircle'),
    },
    {
      value: 'rect',
      label: t('views.monitor.topologyBuild.nodeTypeRect'),
    },
    {
      value: 'ellipse',
      label: t('views.monitor.topologyBuild.nodeTypeEllipse'),
    },
    {
      value: 'diamond',
      label: t('views.monitor.topologyBuild.nodeTypeDiamond'),
    },
    {
      value: 'triangle',
      label: t('views.monitor.topologyBuild.nodeTypeTriangle'),
    },
    {
      value: 'star',
      label: t('views.monitor.topologyBuild.nodeTypeStar'),
    },
    {
      value: 'image',
      label: t('views.monitor.topologyBuild.nodeTypeImage'),
    },
    // {
    //   value: 'donut',
    //   label: '面包圈',
    // },
    {
      value: 'circle-animate-shape-r',
      label: t('views.monitor.topologyBuild.nodeTypeCircleAnimateShapeR'),
    },
    {
      value: 'circle-animate-shape-stroke',
      label: t('views.monitor.topologyBuild.nodeTypeCircleAnimateShapeStroke'),
    },
    {
      value: 'rect-animate-state',
      label: t('views.monitor.topologyBuild.nodeTypeRectAnimateState'),
    },
    {
      value: 'image-animate-state',
      label: t('views.monitor.topologyBuild.nodeTypeImageAnimateState'),
    },
  ];

  /**图节点标签文本位置 */
  const nodeLabelPositionOptions = [
    {
      value: 'top',
      label: t('views.monitor.topologyBuild.nodeLabelPositionTop'),
    },
    {
      value: 'left',
      label: t('views.monitor.topologyBuild.nodeLabelPositionLeft'),
    },
    {
      value: 'right',
      label: t('views.monitor.topologyBuild.nodeLabelPositionRight'),
    },
    {
      value: 'bottom',
      label: t('views.monitor.topologyBuild.nodeLabelPositionBottom'),
    },
    {
      value: 'center',
      label: t('views.monitor.topologyBuild.nodeLabelPositionCenter'),
    },
  ];

  /**图节点三角形方向 */
  const nodeDirectionOptions = [
    { value: 'up', label: t('views.monitor.topologyBuild.nodeDirectionUp') },
    {
      value: 'down',
      label: t('views.monitor.topologyBuild.nodeDirectionDown'),
    },
    {
      value: 'left',
      label: t('views.monitor.topologyBuild.nodeDirectionLeft'),
    },
    {
      value: 'right',
      label: t('views.monitor.topologyBuild.nodeDirectionRight'),
    },
  ];

  /**图节点图片裁剪的形状 */
  const nodeImageClipCfgOptions = [
    {
      value: 'circle',
      label: t('views.monitor.topologyBuild.nodeImageClipCircle'),
    },
    {
      value: 'rect',
      label: t('views.monitor.topologyBuild.nodeImageClipRect'),
    },
    {
      value: 'ellipse',
      label: t('views.monitor.topologyBuild.nodeImageClipEllipse'),
    },
  ];

  /**图节点图片来源 */
  const nodeImageOptions = [
    {
      value: '/svg/base.svg',
      label: t('views.monitor.topologyBuild.nodeImageBase'),
    },
    {
      value: '/svg/cloud.svg',
      label: t('views.monitor.topologyBuild.nodeImageCloud'),
    },
    {
      value: '/svg/service.svg',
      label: t('views.monitor.topologyBuild.nodeImageService'),
    },
    {
      value: '/svg/service_db.svg',
      label: t('views.monitor.topologyBuild.nodeImageServiceDB'),
    },
    {
      value: '/svg/firewall.svg',
      label: t('views.monitor.topologyBuild.nodeImageFirewall'),
    },
    {
      value: '/svg/mobile.svg',
      label: t('views.monitor.topologyBuild.nodeImageMobile'),
    },
    {
      value: '/svg/user.svg',
      label: t('views.monitor.topologyBuild.nodeImageUser'),
    },
  ];

  /**图节点信息状态类型 */
  type NodeStateType = {
    /**图节点原始数据 */
    origin: Record<string, any>;
    /**图节点表单数据 */
    form: Record<string, any>;
  };

  /**图节点信息状态 */
  let nodeState: NodeStateType = reactive({
    origin: {},
    form: {
      id: '',
      comboId: '',
      x: 0,
      y: 0,
      type: 'rect',
      size: [80, 40],
      anchorPoints: false,
      style: {
        fill: '#ffffff',
        stroke: '#ffffff',
        lineWidth: 1,
      },
      label: '',
      labelCfg: {
        position: 'center',
        offset: 0,
        style: {
          fill: '#000000',
          fontSize: 12,
          fontWeight: 500,
        },
      },
    },
  });

  /**图节点对话框内表单属性和校验规则 */
  const nodeStateForm = Form.useForm(
    nodeState.form,
    reactive({
      id: [
        {
          required: true,
          message: t('views.monitor.topologyBuild.nodeFormIdPlease'),
        },
      ],
      type: [{ required: true, message: 'line' }],
    })
  );

  /**图节点编辑监听更新视图 */
  watch(nodeState.form, node => {
    const info = JSON.parse(JSON.stringify(node));
    // 新增不监听变化
    const nodeOriginId = nodeState.origin.id;
    const nodeId = info.id;
    if (nodeId && nodeId === nodeOriginId) {
      // 图片类型需要移除style属性，避免填充
      if (info.type.startsWith('image')) {
        Reflect.deleteProperty(info, 'style');
      }
      graphG6.value.clearItemStates(nodeId, 'selected');
      graphG6.value.updateItem(nodeId, info);
      // 三角和图片的样式变更需要重绘才生效
      if (
        info.type === 'triangle' ||
        info.type.startsWith('image') ||
        info.comboId !== nodeState.origin.comboId
      ) {
        graphG6.value.read(graphG6.value.save());
      }
    }
  });

  /**图节点类型输入限制 */
  function handleNodeTypeChange(type: any) {
    // 设置图标属性
    if (
      ['circle', 'ellipse', 'diamond', 'star', 'donut'].includes(type) ||
      type.startsWith('circle')
    ) {
      let size: number[] | number = [40, 30];
      if (
        ['circle', 'star', 'donut'].includes(type) ||
        type.startsWith('circle')
      ) {
        size = 60;
      }
      const origin = nodeState.origin;
      if (origin.icon) {
        nodeState.form = Object.assign(nodeState.form, {
          size,
          icon: origin.icon,
        });
      } else {
        nodeState.form = Object.assign(nodeState.form, {
          size,
          icon: {
            show: false,
            img: '',
            width: 25,
            height: 25,
          },
        });
      }
    } else if (type === 'triangle') {
      // 三角
      const origin = nodeState.origin;
      if (origin.icon) {
        nodeState.form = Object.assign(nodeState.form, {
          size: 40,
          direction: origin.direction || 'up', // triangle 三角形的方向
          icon: Object.assign({ offset: 20 }, origin.icon),
        });
      } else {
        nodeState.form = Object.assign(nodeState.form, {
          size: 30,
          direction: 'up', // triangle 三角形的方向
          icon: {
            show: false,
            img: '/svg/service.svg',
            width: 25,
            height: 25,
            offset: 20, // triangle 特有
          },
        });
      }
    }
    // 设置图片属性
    if (type.startsWith('image')) {
      const origin = nodeState.origin;
      if (origin.img) {
        nodeState.form = Object.assign(nodeState.form, {
          size: [30, 30],
          img: origin.img,
          clipCfg: origin.clipCfg,
        });
      } else {
        nodeState.form = Object.assign(nodeState.form, {
          size: [30, 30],
          img: '/svg/service.svg',
          clipCfg: {
            show: false,
            width: 0,
            height: 0,
            type: 'circle',
          },
        });
      }
      nodeState.form.style.fill = 'transparent';
      // Reflect.deleteProperty(nodeState.form.style, 'fill');
    } else {
      // 当切换非图片时补充style属性
      if (!nodeState.form.style.fill) {
        nodeState.form.style.fill = '#ffffff';
      }
    }
    // 设置矩形大小
    if (type.startsWith('rect')) {
      nodeState.form = Object.assign(nodeState.form, {
        size: [80, 40],
      });
    }
  }

  /**图节点新增或更新 */
  function handleOkNode() {
    return nodeStateForm
      .validate()
      .then(e => {
        const node = JSON.parse(JSON.stringify(nodeState.form));
        if (!node.id) {
          message.warn({
            content: t('views.monitor.topologyBuild.nodeFormIdNot'),
            duration: 3,
          });
          return false;
        }

        // 图片需要删除style属性，避免填充色问题
        if (node.type.startsWith('image')) {
          node.style.fill = 'transparent';
          // Reflect.deleteProperty(node.style, 'fill');
        }

        // 存在更新，新增不监听变化
        const item = graphG6.value.findById(node.id);
        if (item) {
          graphG6.value.updateItem(item, node);
        } else {
          graphG6.value.addItem('node', node);
        }

        // 三角和图片的样式变更需要重绘才生效
        if (
          node.type === 'triangle' ||
          node.type.startsWith('image') ||
          node.comboId !== nodeState.origin.comboId
        ) {
          graphG6.value.read(graphG6.value.save());
        }

        nodeStateForm.resetFields();
        nodeState.origin = {};
        return true;
      })
      .catch(e => {
        message.error(
          t('common.errorFields', { num: e.errorFields.length }),
          3
        );
        return false;
      });
  }

  /**图节点取消还原 */
  function handleCancelNode() {
    // 新增无原始数据
    const origin = JSON.parse(JSON.stringify(nodeState.origin));
    if (origin.id) {
      graphG6.value.updateItem(origin.id, origin);

      // 三角和图片的样式变更需要重绘才生效
      if (
        origin.type === 'triangle' ||
        origin.type.startsWith('image') ||
        origin.comboId !== nodeState.form.comboId
      ) {
        graphG6.value.read(graphG6.value.save());
      }
    }
    nodeStateForm.resetFields();
    nodeState.origin = {};
  }

  return {
    nodeTypeOptions,
    nodeLabelPositionOptions,
    nodeDirectionOptions,
    nodeImageClipCfgOptions,
    nodeImageOptions,
    nodeState,
    nodeStateForm,
    handleNodeTypeChange,
    handleOkNode,
    handleCancelNode,
  };
}
