<script setup>
defineOptions({ inheritAttrs: false })
import { Handle, Position } from '@vue-flow/core';
import { ref, watch, onBeforeUnmount, computed } from 'vue';
import { useFlowStore } from '../../store/flowStore';
import NodePropertyModal from '../Common/NodePropertyModal.vue';
import SchemaFormRenderer from '../Common/SchemaFormRenderer.vue';
import { createSchemaLoader } from '../../utils/schemaLoader';
import { getNodeMetadataByType } from '../../utils/nodeMetadata';

const props = defineProps({
  id: String,
  data: Object,
  selected: Boolean,
  type: String
});

const emit = defineEmits(['edit-node', 'updateNodeInternals']);

// 状态管理
const flowStore = useFlowStore();
const hover = ref(false);
const showModal = ref(false);
const localData = ref({});
const configData = ref({});
const formSchema = ref({});
const schemaLoading = ref(false);

// 计算属性
const nodeMetadata = computed(() => getNodeMetadataByType(props.type));
const schemaLoader = computed(() => createSchemaLoader(props.type));

// 监听数据变化 - 完全动态的配置处理，支持任意节点类型
watch(() => props.data, (newData) => {
  if (newData) {
    localData.value = {
      label: newData.label || nodeMetadata.value?.label || props.type,
      ...newData.config || {}
    };
    // 保持configData用于其他用途（如果需要）
    configData.value = newData.config || {};
  }
}, { immediate: true, deep: true });

// 事件处理
async function handleEdit() {
  try {
    await loadSchema();
    showModal.value = true;
  } catch (error) {
    console.error('配置加载失败:', error);
  }
}

function handleSchemaUpdate(newValue) {
  localData.value = { ...localData.value, ...newValue };
}

// 保存属性配置 - 动态提取所有配置字段，支持任意节点类型
function saveProperties(close = true) {
  const { label, ...configFields } = localData.value;
  
  try {
    flowStore.updateNodeData(props.id, {
      label: label,
      config: configFields
    });
    
    if (close) showModal.value = false;
  } catch (error) {
    console.error('保存失败:', error);
  }
}

// 键盘快捷键
function handleKeydown(e) {
  if ((e.ctrlKey || e.metaKey) && e.key === 's') {
    e.preventDefault();
    saveProperties(false);
    window.saveAgentFlow?.();
  }
}

watch(showModal, (val) => {
  if (val) {
    window.addEventListener('keydown', handleKeydown);
  } else {
    window.removeEventListener('keydown', handleKeydown);
  }
});

// Schema加载
async function loadSchema() {
  if (!schemaLoader.value) return;
  
  schemaLoading.value = true;
  try {
    formSchema.value = await schemaLoader.value();
  } finally {
    schemaLoading.value = false;
  }
}

// 清理
onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeydown);
});
</script>

<template>
  <div
    v-bind="$attrs"
    class="node"
    :class="{ selected: props.selected }"
    :style="{ 
      borderColor: props.selected ? (nodeMetadata?.color || '#6b7280') : '#cbd5e1',
      boxShadow: props.selected ? `0 0 0 1.5px ${nodeMetadata?.color || '#6b7280'}` : '0 1px 4px #e5e7eb'
    }"
    @mouseenter="hover = true"
    @mouseleave="hover = false"
    @dblclick.stop="handleEdit"
  >
    <!-- 输入连接点 -->
    <Handle 
      v-if="!localData.hide_input_handle"
      type="target" 
      id="input" 
      :position="Position.Left" 
    />
    
    <!-- 节点内容 -->
    <div class="node-content">
      <i 
        v-if="nodeMetadata?.icon" 
        :class="`fa ${nodeMetadata.icon}`"
        :style="{ color: nodeMetadata?.color || '#6b7280' }"
      />
      <span>{{ localData.label || nodeMetadata?.label || props.type }}</span>
    </div>
    
    <!-- 多输出连接点 -->
    <Handle 
      type="source" 
      id="true_output" 
      :position="Position.Right" 
      :style="{ top: '20%' }"
      class="handle-true"
      title="True输出"
    />
    
    <Handle 
      type="source" 
      id="output" 
      :position="Position.Right" 
      :style="{ top: '50%' }"
      class="handle-main"
      title="主流程输出"
    />
    
    <Handle 
      type="source" 
      id="false_output" 
      :position="Position.Right" 
      :style="{ top: '80%' }"
      class="handle-false"
      title="False输出"
    />
    
    <!-- 编辑按钮 -->
    <button 
      v-if="hover" 
      class="edit-btn" 
      @click="handleEdit"
      :disabled="schemaLoading"
    >
      <i :class="schemaLoading ? 'fa fa-spinner fa-spin' : 'fa fa-edit'"></i>
    </button>
  </div>

  <!-- 配置弹窗 -->
  <NodePropertyModal
    v-model="showModal"
    :nodeLabel="localData.label || nodeMetadata?.label || props.type"
    @save="saveProperties"
    @close="showModal = false"
  >
    <template #default>
      <!-- 基本信息 -->
      <div class="section">
        <h5>基本信息</h5>
        <div class="form-row">
          <div class="form-group">
            <label>节点名称</label>
            <input 
              v-model="localData.label" 
              class="form-control" 
              placeholder="输入节点名称"
            />
          </div>
          <div class="form-group">
            <label>节点ID</label>
            <input 
              :value="props.id" 
              class="form-control" 
              readonly 
              style="background-color: #f8f9fa; color: #6b7280;"
            />
          </div>
        </div>
      </div>
      
      <!-- 节点配置 -->
      <div class="section">
        <h5>节点配置</h5>
        
        <div v-if="schemaLoading" class="loading">
          <i class="fa fa-spinner fa-spin"></i> 正在加载...
        </div>
        
        <SchemaFormRenderer 
          v-else-if="formSchema.properties"
          :schema="formSchema"
          :modelValue="localData"
          :flowStore="flowStore"
          @update:modelValue="handleSchemaUpdate"
        />
        
        <div v-else class="no-config">
          此节点暂无可配置项
        </div>
      </div>
    </template>
  </NodePropertyModal>
</template>

<style scoped>
.node {
  width: 130px;
  height: 50px;
  border: 1.5px solid;
  border-radius: 8px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 12px;
  color: #374151;
  position: relative;
  cursor: pointer;
  transition: all 0.2s;
}

.node-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 0 8px;
  width: 100%;
  overflow: hidden;
}

.node-content i {
  font-size: 14px;
  flex-shrink: 0;
}

.node-content span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.edit-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 20px;
  height: 20px;
  border: 1px solid #cbd5e1;
  border-radius: 50%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s;
}

.edit-btn:hover:not(:disabled) {
  background: #f3f4f6;
  color: #374151;
}

.edit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.section {
  margin: 24px 0;
}

.section h5 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 8px;
}

.form-row {
  display: flex;
  gap: 16px;
  margin: 16px 0;
  flex-wrap: wrap;
}

.form-group {
  flex: 1;
  margin-bottom: 0;
  min-width: 200px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 12px;
  }
  
  .form-group {
    min-width: auto;
  }
}

@media (max-width: 480px) {
  .form-row {
    gap: 8px;
  }
  
  .form-group {
    margin-bottom: 8px;
  }
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.form-control:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.loading {
  padding: 16px;
  text-align: center;
  color: #6b7280;
}

.no-config {
  padding: 16px;
  text-align: center;
  color: #6b7280;
  font-style: italic;
}

/* 多输出接口样式 */
.handle-true,
.handle-true.vue-flow__handle {
  background: #fff !important;
  border: 2.5px solid #10b981 !important;
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.15) !important;
  transition: all 0.2s ease;
  width: 14px !important;
  height: 14px !important;
}

.handle-true:hover,
.handle-true.vue-flow__handle:hover {
  background: #f0fdf4 !important;
  box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.2) !important;
  border-color: #059669 !important;
}

.handle-main,
.handle-main.vue-flow__handle {
  background: #fff !important;
  border: 2.5px solid #3b82f6 !important;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.15) !important;
  transition: all 0.2s ease;
  width: 14px !important;
  height: 14px !important;
}

.handle-main:hover,
.handle-main.vue-flow__handle:hover {
  background: #eff6ff !important;
  box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.2) !important;
  border-color: #2563eb !important;
}

.handle-false,
.handle-false.vue-flow__handle {
  background: #fff !important;
  border: 2.5px solid #ef4444 !important;
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.15) !important;
  transition: all 0.2s ease;
  width: 14px !important;
  height: 14px !important;
}

.handle-false:hover,
.handle-false.vue-flow__handle:hover {
  background: #fef2f2 !important;
  box-shadow: 0 0 0 4px rgba(239, 68, 68, 0.2) !important;
  border-color: #dc2626 !important;
}

/* 接口连接线样式 */
.handle-true + .vue-flow__edge-path {
  stroke: #10b981;
  stroke-width: 2;
}

.handle-main + .vue-flow__edge-path {
  stroke: #3b82f6;
  stroke-width: 2;
}

.handle-false + .vue-flow__edge-path {
  stroke: #ef4444;
  stroke-width: 2;
}
</style>
