<!--
  节点配置面板
  根据节点类型元数据动态生成表单
-->
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import {
  Drawer,
  Form,
  FormItem,
  Input,
  InputNumber,
  Select,
  SelectOption,
  Switch,
  Button,
  Space,
  Divider,
  Empty,
  Tooltip,
} from 'ant-design-vue'
import {
  CloseOutlined,
  SaveOutlined,
  FieldTimeOutlined,
  FunctionOutlined,
  DeleteOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons-vue'
import { useWorkflowStore } from '../stores/useWorkflowStore'
import FieldMappingSelector from './FieldMappingSelector.vue'
import { isExpression, parseFieldExpression } from '../utils/expression'
import type { FieldDefinition } from '#/types/workflow'

const { TextArea: Textarea } = Input

const workflowStore = useWorkflowStore()

/** 表单数据 */
const formData = ref<Record<string, any>>({})

/** 表单实例 */
const formRef = ref()

/** 字段选择器可见性 */
const fieldSelectorVisible = ref(false)

/** 当前编辑的字段名 */
const currentFieldName = ref<string>()

/** 字段表达式模式（静态值 / 表达式） */
const fieldExpressionMode = ref<Record<string, boolean>>({})

/**
 * 面板是否可见
 */
const visible = computed(() => !!workflowStore.selectedNodeId)

/**
 * 当前选中的节点
 */
const selectedNode = computed(() => workflowStore.selectedNode)

/**
 * 当前节点的元数据
 */
const metadata = computed(() => workflowStore.selectedNodeMetadata)

/**
 * 表单字段列表
 */
const fields = computed(() => metadata.value?.fields || [])

/**
 * 表单规则
 */
const formRules = computed(() => {
  const rules: Record<string, any[]> = {}
  fields.value.forEach((field) => {
    if (field.required) {
      rules[field.name] = [
        { required: true, message: `请输入${field.label}`, trigger: 'blur' },
      ]
    }
  })
  return rules
})

/**
 * 关闭面板
 */
function handleClose() {
  workflowStore.selectNode(null)
}

/**
 * 保存配置
 */
async function handleSave() {
  try {
    await formRef.value?.validate()

    if (selectedNode.value) {
      workflowStore.updateNodeConfig(selectedNode.value.id, formData.value)
      // 不关闭面板，允许继续编辑
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

/**
 * 删除节点
 */
function handleDelete() {
  if (selectedNode.value) {
    workflowStore.deleteNode(selectedNode.value.id)
  }
}

/**
 * 更新节点名称
 */
function handleUpdateName(name: string) {
  if (selectedNode.value) {
    workflowStore.updateNodeName(selectedNode.value.id, name)
  }
}

/**
 * 打开字段选择器
 */
function openFieldSelector(fieldName: string) {
  currentFieldName.value = fieldName
  fieldSelectorVisible.value = true
}

/**
 * 选择字段后的回调
 */
function handleFieldSelect(expression: string, fieldPath: string) {
  if (currentFieldName.value) {
    formData.value[currentFieldName.value] = expression
    fieldExpressionMode.value[currentFieldName.value] = true
  }
}

/**
 * 切换表达式模式
 */
function toggleExpressionMode(fieldName: string) {
  fieldExpressionMode.value[fieldName] = !fieldExpressionMode.value[fieldName]

  // 如果切换到静态值模式，清空表达式
  if (!fieldExpressionMode.value[fieldName]) {
    formData.value[fieldName] = ''
  }
}

/**
 * 检查字段是否为表达式
 */
function isFieldExpression(fieldName: string): boolean {
  return fieldExpressionMode.value[fieldName] || isExpression(formData.value[fieldName])
}

/**
 * 获取字段类型（用于渲染）
 */
function getFieldType(field: FieldDefinition): string {
  const isExpr = isFieldExpression(field.name)
  if (isExpr) return 'expression'
  return field.type || 'text'
}

/**
 * 获取字段映射信息（解析表达式）
 */
function getFieldMappingInfo(fieldName: string): { nodeId: string; nodeName: string; fieldPath: string } | null {
  const value = formData.value[fieldName]
  if (!isExpression(value)) return null

  const parsed = parseFieldExpression(value)
  if (!parsed) return null

  const sourceNode = workflowStore.vueFlowNodes.find((n) => n.id === parsed.nodeId)
  if (!sourceNode) return null

  return {
    nodeId: parsed.nodeId,
    nodeName: sourceNode.data.name || parsed.nodeId,
    fieldPath: parsed.fieldPath,
  }
}

/**
 * 清除字段映射
 */
function clearFieldMapping(fieldName: string) {
  formData.value[fieldName] = ''
  fieldExpressionMode.value[fieldName] = false
}

/**
 * 监听选中节点变化，加载配置数据
 */
watch(
  () => selectedNode.value,
  (node) => {
    if (node) {
      // 深拷贝配置数据
      formData.value = JSON.parse(JSON.stringify(node.data.config || {}))

      // 初始化表达式模式
      fieldExpressionMode.value = {}
      fields.value.forEach((field) => {
        const value = formData.value[field.name]
        fieldExpressionMode.value[field.name] = isExpression(value)

        // 设置默认值
        if (value === undefined && field.defaultValue !== undefined) {
          formData.value[field.name] = field.defaultValue
        }
      })
    } else {
      formData.value = {}
      fieldExpressionMode.value = {}
    }
  },
  { immediate: true },
)
</script>

<template>
  <Drawer
    :open="visible"
    title="节点配置"
    width="450"
    :closable="true"
    :footer="null"
    @close="handleClose"
  >
    <div v-if="selectedNode && metadata" class="node-config-panel">
      <!-- 节点基本信息 -->
      <div class="node-info">
        <div class="node-info-row">
          <label>节点 ID:</label>
          <span class="node-id">{{ selectedNode.id }}</span>
        </div>
        <div class="node-info-row">
          <label>节点类型:</label>
          <span>{{ metadata.displayName }}</span>
        </div>
        <div class="node-info-row">
          <label>节点名称:</label>
          <Input
            :value="selectedNode.data.name"
            placeholder="节点名称"
            @blur="handleUpdateName($event.target.value)"
          />
        </div>
      </div>

      <Divider />

      <!-- 动态表单 -->
      <Form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
        class="config-form"
      >
        <FormItem
          v-for="field in fields"
          :key="field.name"
          :label="field.label"
          :name="field.name"
          :required="field.required"
        >
          <template #label>
            <div class="field-label">
              <span>{{ field.label }}</span>
              <Space size="small">
                <!-- 表达式切换按钮 -->
                <Tooltip
                  v-if="field.supportsExpression"
                  :title="isFieldExpression(field.name) ? '切换为静态值' : '切换为表达式'"
                >
                  <Button
                    size="small"
                    type="text"
                    :class="{ active: isFieldExpression(field.name) }"
                    @click="toggleExpressionMode(field.name)"
                  >
                    <FunctionOutlined />
                  </Button>
                </Tooltip>

                <!-- 字段选择器按钮 -->
                <Tooltip v-if="field.supportsFieldMapping" title="选择字段">
                  <Button
                    size="small"
                    type="text"
                    @click="openFieldSelector(field.name)"
                  >
                    <FieldTimeOutlined />
                  </Button>
                </Tooltip>
              </Space>
            </div>
          </template>

          <!-- 动态渲染表单控件 -->
          <!-- 表达式模式 -->
          <div v-if="getFieldType(field) === 'expression'">
            <Input
              v-model:value="formData[field.name]"
              placeholder="例如: ${nodes.n1.output.field}"
            />
            <!-- 字段映射信息显示 -->
            <div v-if="getFieldMappingInfo(field.name)" class="field-mapping-info">
              <span class="mapping-icon">🔗</span>
              <span class="mapping-text">
                来自节点 <strong>{{ getFieldMappingInfo(field.name)!.nodeName }}</strong>
                的字段 <code>{{ getFieldMappingInfo(field.name)!.fieldPath }}</code>
              </span>
              <Button
                size="small"
                type="text"
                danger
                @click="clearFieldMapping(field.name)"
              >
                <CloseCircleOutlined />
              </Button>
            </div>
          </div>

          <!-- 文本输入 -->
          <Input
            v-else-if="getFieldType(field) === 'text'"
            v-model:value="formData[field.name]"
            :placeholder="field.placeholder"
          />

          <!-- 多行文本 -->
          <Textarea
            v-else-if="getFieldType(field) === 'textarea'"
            v-model:value="formData[field.name]"
            :placeholder="field.placeholder"
            :rows="4"
          />

          <!-- 数字输入 -->
          <InputNumber
            v-else-if="getFieldType(field) === 'number'"
            v-model:value="formData[field.name]"
            class="w-full"
            :placeholder="field.placeholder"
          />

          <!-- 下拉选择 -->
          <Select
            v-else-if="getFieldType(field) === 'select'"
            v-model:value="formData[field.name]"
            :placeholder="field.placeholder || '请选择'"
          >
            <SelectOption
              v-for="option in field.options"
              :key="option"
              :value="option"
            >
              {{ option }}
            </SelectOption>
          </Select>

          <!-- 开关 -->
          <Switch
            v-else-if="getFieldType(field) === 'boolean'"
            v-model:checked="formData[field.name]"
            checked-children="是"
            un-checked-children="否"
          />

          <!-- 代码编辑 -->
          <Textarea
            v-else-if="getFieldType(field) === 'code'"
            v-model:value="formData[field.name]"
            :placeholder="field.placeholder"
            :rows="8"
            class="font-mono"
          />

          <!-- 键值对编辑 -->
          <Textarea
            v-else-if="getFieldType(field) === 'key_value'"
            v-model:value="formData[field.name]"
            placeholder="key1=value1&#10;key2=value2"
            :rows="4"
          />

          <!-- 默认文本输入 -->
          <Input
            v-else
            v-model:value="formData[field.name]"
            :placeholder="field.placeholder"
          />
        </FormItem>
      </Form>

      <!-- 操作按钮 -->
      <div class="panel-actions">
        <Space>
          <Button type="primary" @click="handleSave">
            <SaveOutlined />
            保存
          </Button>
          <Button danger @click="handleDelete">
            <DeleteOutlined />
            删除节点
          </Button>
        </Space>
      </div>
    </div>

    <Empty
      v-else
      description="未选中节点"
      :image="Empty.PRESENTED_IMAGE_SIMPLE"
    />

    <!-- 字段选择器 -->
    <FieldMappingSelector
      v-if="selectedNode"
      v-model:visible="fieldSelectorVisible"
      :current-node-id="selectedNode.id"
      @select="handleFieldSelect"
    />
  </Drawer>
</template>

<style scoped lang="less">
.node-config-panel {
  .node-info {
    .node-info-row {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      label {
        width: 80px;
        font-weight: 500;
        color: #666;
      }

      .node-id {
        font-family: monospace;
        color: #1890ff;
        padding: 2px 8px;
        background: #f0f7ff;
        border-radius: 3px;
      }
    }
  }

  .config-form {
    .field-label {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;

      :deep(.ant-btn) {
        color: #999;

        &:hover,
        &.active {
          color: #1890ff;
        }
      }
    }

    .field-mapping-info {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-top: 8px;
      padding: 8px 12px;
      background: #f0f7ff;
      border: 1px solid #bae7ff;
      border-radius: 4px;
      font-size: 12px;

      .mapping-icon {
        font-size: 14px;
      }

      .mapping-text {
        flex: 1;
        color: #333;

        strong {
          color: #1890ff;
        }

        code {
          padding: 2px 6px;
          background: #fff;
          border: 1px solid #d9d9d9;
          border-radius: 2px;
          font-family: monospace;
          color: #d46b08;
        }
      }
    }
  }

  .panel-actions {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #e8e8e8;
  }
}
</style>

