import { defineStore } from 'pinia'
import type { Node, Edge } from '@vue-flow/core'

export interface State {
  nodes: Node[]
  edges: Edge[]
}

export interface ElementState {
  id: string
  name: string
  type: string
}

function getCustomNodes(nodes: Node[] = []) {
  return nodes.filter(node => node.type === 'custom')
}

export const useTripStore = defineStore('trip', {
  state: (): State => {
    return {
      nodes: [
        {
          id: 'start',
          type: 'start',
          label: 'Start',
          data: { label: 'Start' },
          position: { x: 0, y: 0 }
        },
        {
          id: '1',
          type: 'custom',
          label: '一级旅程节点',
          data: { label: '一级旅程节点' },
          position: { x: 360, y: 0 }
        },
        {
          id: 'end',
          type: 'end',
          label: 'End',
          data: { label: 'End' },
          position: { x: 720, y: 0 }
        }
      ],
      edges: [
        {
          id: 'start->1',
          type: 'custom',
          source: 'start',
          target: '1',
          animated: true,
          markerEnd: 'arrowclosed'
        },
        {
          id: '1->end',
          type: 'custom',
          source: '1',
          target: 'end',
          animated: true,
          markerEnd: 'arrowclosed'
        }
      ]
    }
  },
  getters: {
    // 一级节点
    node1List(state) {
      return getCustomNodes(state.nodes)
    },
    // 二级节点
    node2List() {
      return (node1Id: string) => {
        const node1 = this.nodes.find(node => node.id === node1Id)
        if (!node1 || !node1?.data?.nodes) return []
        return getCustomNodes(node1.data.nodes)
      }
    }
  },
  actions: {
    setData(data?: State) {
      if (!data?.nodes) return
      this.setNodes(data.nodes)
      this.setEdges(data.edges)
    },
    setNodes(list: Node[]) {
      this.nodes = list
    },
    setEdges(list: Edge[]) {
      this.edges = list
    }
  }
})
