<script setup lang="ts">
import { computed, ref, watch, onMounted, onUnmounted } from 'vue'
import { NInput, NButton, NIcon } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { getRecords } from '@/shared/api/common'
import { pageTypeToSlug } from '@/shared/utils/slug'
import axios from 'axios'
import { get_session_api_headers } from '@/shared/api/auth'
import { t } from '@/shared/i18n'

const props = defineProps<{ df: any; record: Record<string, any>; canEdit: boolean; ctx: any }>()

// Label布局：上下结构(vertical) 或 左右结构(horizontal)
const labelLayout = computed(() => props.df.label_layout || 'vertical')

// 响应式数据
const inputValue = ref('')
const displayValue = ref('')
const searchQuery = ref('')
const showButtons = ref(false)
const showDropdown = ref(false)
const dropdownOptions = ref<any[]>([])
const isLoading = ref(false)
const pageTypeConfig = ref<any>({})
const titleFieldCache = ref<Record<string, string>>({})

// 计算属性
const options = computed(() => props.df.options || '')
const hasValue = computed(() => !!inputValue.value)
const maxOptions = computed(() => props.df.max_options || 20)

// 监听record变化，同步到inputValue
watch(() => props.record[props.df.fieldname], async (newValue) => {
  if (newValue !== inputValue.value) {
    inputValue.value = newValue || ''
    if (newValue && options.value) {
      // 获取标题字段的值
      displayValue.value = await getRecordTitle(options.value, newValue)
    } else {
      displayValue.value = ''
    }
  }
}, { immediate: true })

// 监听inputValue变化，同步到record
watch(inputValue, (newValue) => {
  if (props.record[props.df.fieldname] !== newValue) {
    props.record[props.df.fieldname] = newValue
  }
})

// 获取页面类型配置
async function getPageTypeConfig(pagetype: string) {
  if (!pagetype) return {}
  
  // 检查缓存
  if (pageTypeConfig.value[pagetype]) {
    return pageTypeConfig.value[pagetype]
  }
  
  try {
    const response = await axios.get(`/api/data/PageType/${encodeURIComponent(pagetype)}`, {
      headers: get_session_api_headers(),
      withCredentials: true
    })
    
    const config = response.data?.data || {}
    pageTypeConfig.value[pagetype] = config
    return config
  } catch (error) {
    console.error('获取页面类型配置失败:', error)
    return {}
  }
}

// 获取记录的标题字段值
async function getRecordTitle(pagetype: string, recordName: string) {
  if (!pagetype || !recordName) return recordName
  
  // 检查缓存
  const cacheKey = `${pagetype}_${recordName}`
  if (titleFieldCache.value[cacheKey]) {
    return titleFieldCache.value[cacheKey]
  }
  
  try {
    // 获取页面类型配置
    const config = await getPageTypeConfig(pagetype)
    const titleField = config.title_field || 'name'
    
    // 如果标题字段就是name，直接返回
    if (titleField === 'name') {
      titleFieldCache.value[cacheKey] = recordName
      return recordName
    }
    
    // 获取记录数据
    const response = await axios.get(`/api/data/${encodeURIComponent(pagetype)}/${encodeURIComponent(recordName)}`, {
      headers: get_session_api_headers(),
      withCredentials: true
    })
    
    const recordData = response.data?.data || {}
    const titleValue = recordData[titleField] || recordName
    
    // 缓存结果
    titleFieldCache.value[cacheKey] = titleValue
    return titleValue
    
  } catch (error) {
    console.error('获取记录标题失败:', error)
    return recordName
  }
}
// 创建新建选项
function createNewOption() {
  return {
    label: `${t('Create')}${t(options.value)}`,
    value: 'create_new',
    type: 'create'
  }
}

// 搜索链接选项
async function searchOptions(query: string = '') {
  if (!options.value) return
  
  isLoading.value = true
  
  try {
    // 获取页面类型配置
    const config = await getPageTypeConfig(options.value)
    const titleField = config.title_field || 'name'
    
    // 构建要获取的字段列表
    const fields = ['name']
    if (titleField !== 'name') {
      fields.push(titleField)
    }
    
    // 构建搜索过滤器
    const filters = []
    if (query.trim()) {
      // 如果有搜索查询，优先搜索标题字段
      if (titleField !== 'name') {
        // 优先搜索标题字段
        filters.push([titleField, 'like', `%${query}%`])
      } else {
        // 如果标题字段就是name，搜索name字段
        filters.push(['name', 'like', `%${query}%`])
      }
    }
    
    // 使用标准API获取记录列表
    const result = await getRecords(options.value, filters, fields, 'modified desc', 0, maxOptions.value)
    
    if (result.success && result.data) {
      // 处理记录数据，优先显示标题字段
      const processedRecords = result.data.map((item: any) => {
        const title = titleField === 'name' ? item.name : (item[titleField] || item.name)
        return {
          label: title,
          value: item.name,
          title: title
        }
      })
      
      dropdownOptions.value = [...processedRecords, createNewOption()]
    } else {
      dropdownOptions.value = [createNewOption()]
    }
  } catch (error) {
    console.error('搜索选项失败:', error)
    dropdownOptions.value = [createNewOption()]
  } finally {
    isLoading.value = false
  }
}

// 处理输入变化
function handleInputChange(value: string) {
  searchQuery.value = value
  if (showDropdown.value) {
    searchOptions(value)
  }
}

// 处理输入框点击
async function handleInputClick() {
  if (!props.canEdit) return
  
  // 防止重复调用
  if (showDropdown.value) return
  
  // 先加载数据，再显示下拉框
  await searchOptions(searchQuery.value)
  showDropdown.value = true
}

// 处理选项选择
async function handleOptionSelect(option: any) {
  if (option.type === 'create') {
    const pagetypeSlug = pageTypeToSlug(options.value)
    const randomStr = Math.random().toString(36).substring(2, 12)
    const tempName = `new-${pagetypeSlug}-${randomStr}`
    window.open(`/app/${pagetypeSlug}/${tempName}`, '_blank')
    showDropdown.value = false
    return
  }
  
  inputValue.value = option.value
  displayValue.value = option.title || option.label
  searchQuery.value = ''
  showDropdown.value = false
}

// 清除值
function clearValue() {
  inputValue.value = ''
  displayValue.value = ''
  searchQuery.value = ''
  showDropdown.value = false
}

// 打开链接详情页
function openLinkDetail() {
  if (!inputValue.value || !options.value) return
  
  const pagetypeSlug = pageTypeToSlug(options.value)
  window.open(`/app/${pagetypeSlug}/${inputValue.value}`, '_blank')
}

// 显示/隐藏按钮
function showLinkButtons() {
  showButtons.value = hasValue.value
}

function hideLinkButtons() {
  showButtons.value = false
}

// 点击外部关闭下拉框
function handleClickOutside(event: Event) {
  const target = event.target as HTMLElement
  if (!target.closest('.link-field-container')) {
    showDropdown.value = false
  }
}

// 组件挂载时添加事件监听
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<template>
  <div :class="['field-wrapper', `layout-${labelLayout}`]">
    <label class="field-label">
      {{ ctx.t(df.label || df.fieldname) }}
      <span v-if="df.reqd" class="required">*</span>
    </label>
    
    <div class="link-field-container" @mouseenter="showLinkButtons" @mouseleave="hideLinkButtons">
      <div class="input-wrapper">
        <n-input 
          :value="hasValue ? displayValue : searchQuery" 
          :placeholder="ctx.t(df.fieldname)"
          :disabled="!canEdit"
          @update:value="handleInputChange"
          @click="handleInputClick"
          @focus="handleInputClick"
          class="link-input"
        />
        
        <!-- 操作按钮 -->
        <div v-if="showButtons && hasValue" class="link-buttons">
          <n-button
            v-if="canEdit"
            size="small"
            quaternary
            @click.stop="clearValue"
            :title="t('Clear')"
            class="action-btn"
          >
            <template #icon>
              <n-icon><Icon icon="mdi:close" /></n-icon>
            </template>
          </n-button>
          
          <n-button
            size="small"
            quaternary
            @click.stop="openLinkDetail"
            :title="t('Open Detail')"
            class="action-btn"
          >
            <template #icon>
              <n-icon><Icon icon="mdi:arrow-right" /></n-icon>
            </template>
          </n-button>
        </div>
      </div>
      
      <!-- 下拉选项 -->
      <div v-if="showDropdown" class="dropdown-menu">
        <div class="dropdown-content">
          <div
            v-for="option in dropdownOptions"
            :key="option.value"
            class="dropdown-item"
            :class="{ 'create-item': option.type === 'create' }"
            @click="handleOptionSelect(option)"
          >
            <span v-if="option.type === 'create'" class="create-icon">
              <Icon icon="mdi:plus" />
            </span>
            <span class="item-label">{{ option.label }}</span>
          </div>
          
          <div v-if="dropdownOptions.length === 0 && !isLoading" class="empty-state">
            {{ t('No Data') }}
          </div>
          
          <div v-if="isLoading" class="loading-state">
            {{ t('Loading') }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.field-wrapper :deep(.link-field-container) {
  flex: 1;
  position: relative;
}

.link-field-container {
  position: relative;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.link-input {
  flex: 1;
}

.link-buttons {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  gap: 4px;
  background: white;
  padding: 2px;
  border-radius: 4px;
}

.action-btn {
  width: 24px;
  height: 24px;
  min-width: 24px;
  padding: 0;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 1000;
  margin-top: 4px;
}

.dropdown-content {
  background: white;
  border: 1px solid #e0e0e6;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  max-height: 200px;
  overflow-y: auto;
}

.dropdown-item {
  padding: 8px 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.dropdown-item:last-child {
  border-bottom: none;
}

.dropdown-item:hover {
  background-color: #f5f5f5;
}

.create-item {
  color: #18a058;
  font-weight: 500;
}

.create-icon {
  color: #18a058;
}

.item-label {
  flex: 1;
}

.empty-state,
.loading-state {
  padding: 12px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.field-wrapper :deep(.n-input) {
  flex: 1;
}
</style>


