import { ref, watch } from 'vue'

const useJumpEditorDrawer = (curNodeRef, graphRef) => {
  // 跳转模块得抽屉状态
  const jumpDrawerRef = ref(false)
  // 跳转模块得表单数据
  const jumpFormRef = ref({
    jumpNodeId: '',
    jumpNodeName: ''
  })
  // 表单规则
  const jumpFormRuleRef = ref({
    jumpNodeId: [{ required: true, message: '请选择跳转模块', trigger: 'change' }]
  })

  // 可以跳转得节点列表
  const canJumpNodeListRef = ref([])
  // 更新可以跳转节点列表
  const updataCanJumpNodeList = () => {
    const allNode = graphRef.value.getNodes()
    const curNode = curNodeRef.value
    const curModel = curNode.getModel()
    // 过滤出非自己本身和直接上级节点的所有节点
    const result = []
    for (let i = 0; i < allNode.length; i++) {
      const _node = allNode[i]
      const _model = _node.getModel()
      if (_model.type === 'jump-node' || _model.id === curModel.preNodeId) continue
      result.push({
        jumpNodeId: _model.id,
        jumpNodeName: _model.data?.name || ''
      })
    }
    canJumpNodeListRef.value = result
  }
  // 选择跳转节点之后赋值跳转节点名称
  const handleChangeJumpTarget = (jumpNodeId) => {
    const target = canJumpNodeListRef.value.find((item) => item.jumpNodeId === jumpNodeId)
    jumpFormRef.value.jumpNodeName = target.jumpNodeName
  }
  // 关闭抽屉
  const handleJumpCancel = () => {
    ElMessageBox.confirm('是否确认取消更改?')
      .then(() => {
        jumpDrawerRef.value = false
        curNodeRef.value = null
      })
      .catch(() => {
        // catch error
      })
  }
  // 保存
  const handleJumpSave = () => {
    if (!graphRef.value) return console.warn('画布不存在')
    const config = {
      data: {
        jumpNodeId: jumpFormRef.value.jumpNodeId,
        jumpNodeName: jumpFormRef.value.jumpNodeName
      }
    }
    // 更新当前节点
    graphRef.value.updateItem(curNodeRef.value, config)
    jumpDrawerRef.value = false
    curNodeRef.value = null
  }

  // 根据传入的节点初始化内容
  const init = (node) => {
    const model = node.getModel()
    const data = model.data || {}
    jumpFormRef.value = {
      jumpNodeId: data.jumpNodeId,
      jumpNodeName: data.jumpNodeName
    }
  }

  watch(
    () => curNodeRef.value,
    (node) => {
      if (!node) return
      init(node)
    }
  )

  return {
    jumpDrawerRef,
    jumpFormRef,
    jumpFormRuleRef,
    canJumpNodeListRef,
    updataCanJumpNodeList,
    handleChangeJumpTarget,
    handleJumpCancel,
    handleJumpSave
  }
}

export default useJumpEditorDrawer
