<template>
  <a-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    layout="vertical"
    class="menu-form"
    @submit-success="handleSubmit"
  >
    <!-- 基本信息 -->
    <a-divider orientation="left">基本信息</a-divider>
    
    <a-row :gutter="16">
      <a-col :span="12">
        <a-form-item field="code" label="菜单编码" :rules="[{ required: true, message: '请输入菜单编码' }]">
          <a-input v-model="formData.code" placeholder="请输入菜单编码，如: menu_management" />
        </a-form-item>
      </a-col>
      
      <a-col :span="12">
        <a-form-item field="type" label="菜单类型">
          <a-select v-model="formData.type">
            <a-option :value="1">{{ formData.parent_id ? '子菜单' : '根菜单' }}</a-option>
          </a-select>
        </a-form-item>
      </a-col>
      
      <a-col :span="12">
        <a-form-item field="title" label="菜单名称" :rules="[{ required: true, message: '请输入菜单名称' }]">
          <a-input v-model="formData.title" placeholder="请输入中文菜单名称" />
        </a-form-item>
      </a-col>
      
      <a-col :span="12">
        <a-form-item field="title_en" label="英文名称" :rules="[{ required: true, message: '请输入英文名称' }]">
          <a-input v-model="formData.title_en" placeholder="请输入英文菜单名称" />
        </a-form-item>
      </a-col>
      
      <a-col :span="12">
        <a-form-item field="menu_path" label="路由路径" :rules="[{ required: true, message: '请输入路由路径' }]">
          <a-input v-model="formData.menu_path" placeholder="请输入路由路径，如: /ops/menu-management" />
        </a-form-item>
      </a-col>
      
      <a-col :span="12">
        <a-form-item field="component" label="组件路径">
          <a-input v-model="formData.component" placeholder="请输入组件路径" />
        </a-form-item>
      </a-col>
      
      <!-- 根菜单才显示图标选择 -->
      <a-col v-if="!parentId" :span="12">
        <a-form-item field="menu_icon" label="菜单图标" style="width: 100%">
          <a-input-group style="width: 100%;">
            <a-input 
              v-model="formData.menu_icon" 
              placeholder="点击选择图标"
              readonly
              style="cursor: pointer"
              @click="iconPickerVisible = true"
            >
              <template #prefix>
                <component v-if="formData.menu_icon" :is="getIconComponent(formData.menu_icon)" :size="18" />
              </template>
            </a-input>
            <a-button 
              v-if="formData.menu_icon"
              @click="clearIcon"
            >
              <template #icon><icon-close /></template>
            </a-button>
          </a-input-group>
        </a-form-item>
      </a-col>
      
      <a-col :span="24">
        <a-form-item field="description" label="菜单描述">
          <a-textarea v-model="formData.description" placeholder="请输入菜单描述" :auto-size="{ minRows: 3, maxRows: 5 }" />
        </a-form-item>
      </a-col>
    </a-row>
    
    <!-- 路由配置 -->
    <a-divider orientation="left">路由配置</a-divider>
    
    <a-row :gutter="16">
      <a-col :span="12">
        <a-form-item field="is_new_tab">
          <a-switch v-model="formData.is_new_tab" />
          <span class="switch-label">在新窗口打开</span>
        </a-form-item>
      </a-col>
      
      <a-col :span="12">
        <a-form-item field="is_web_page">
          <a-switch v-model="formData.is_web_page" />
          <span class="switch-label">嵌入网页</span>
        </a-form-item>
      </a-col>
      
      <a-col :span="12">
        <a-form-item field="is_full">
          <a-switch v-model="formData.is_full" />
          <span class="switch-label">单独页面（不包含菜单）</span>
        </a-form-item>
      </a-col>
      
      <a-col :span="12">
        <a-form-item field="hide_menu">
          <a-switch v-model="formData.hide_menu" />
          <span class="switch-label">隐藏菜单栏</span>
        </a-form-item>
      </a-col>
    </a-row>
    
    <!-- 网页嵌入配置 -->
    <a-divider orientation="left">网页嵌入配置</a-divider>
    
    <a-row :gutter="16">
      
      <a-col v-if="formData.is_web_page" :span="24">
        <a-form-item field="web_url" label="网页地址">
          <a-input v-model="formData.web_url" placeholder="请输入要嵌入的网页URL" />
        </a-form-item>
      </a-col>
    </a-row>
    
    <!-- 操作按钮 -->
    <div class="form-actions">
      <a-space>
        <a-button type="primary" html-type="submit" :loading="loading">
          保存
        </a-button>
        <a-button @click="$emit('cancel')">
          取消
        </a-button>
      </a-space>
    </div>
    
    <!-- 图标选择器 -->
    <a-modal
      v-model:visible="iconPickerVisible"
      title="选择图标"
      :footer="false"
      width="600px"
    >
      <div class="icon-search">
        <a-input v-model="iconSearch" placeholder="搜索图标" allow-clear>
          <template #prefix><icon-search /></template>
        </a-input>
      </div>
      <div class="icon-grid">
        <div
          v-for="icon in filteredIcons"
          :key="icon"
          class="icon-item"
          :class="{ 'is-selected': formData.menu_icon === icon }"
          @click="selectIcon(icon)"
        >
          <component :is="getIconComponent(icon)" :size="24" class="icon-preview" />
          <span class="icon-name">{{ icon }}</span>
        </div>
      </div>
    </a-modal>
  </a-form>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import type { FormInstance } from '@arco-design/web-vue'
import type { MenuRouteRequest, MenuNode } from '../types'
import { COMMON_ICONS, iconNames, getIconComponent } from '../menuIcons'
import { IconSearch } from '@tabler/icons-vue'

const props = defineProps<{
  mode: 'add' | 'edit' | 'add_child'
  parentId?: number | null
  initialValues?: MenuNode | null
  parentName?: string
}>()

const emit = defineEmits<{
  (e: 'save', data: MenuRouteRequest): void
  (e: 'cancel'): void
}>()

const formRef = ref<FormInstance>()
const loading = ref(false)
const iconPickerVisible = ref(false)
const iconSearch = ref('')

// 表单数据
const formData = ref<MenuRouteRequest>({
  code: '',
  description: '',
  menu_icon: '',
  menu_path: '',
  component: '',
  parent_id: undefined,
  title: '',
  title_en: '',
  type: 1,
  is_web_page: false,
  web_url: '',
  is_new_tab: false,
  is_full: false,
  hide_menu: false,
  // 编辑时需要的额外字段
  id: undefined,
  identity: undefined,
  app_id: undefined,
  sort_key: undefined,
  created_at: undefined,
})

// 图标列表
const iconList = iconNames

// 过滤图标
const filteredIcons = computed(() => {
  if (!iconSearch.value) return iconList
  return iconList.filter(icon => 
    icon.toLowerCase().includes(iconSearch.value.toLowerCase())
  )
})

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入菜单编码' }],
  title: [{ required: true, message: '请输入菜单名称' }],
  title_en: [{ required: true, message: '请输入英文名称' }],
  menu_path: [{ required: true, message: '请输入路由路径' }],
}

// 重置表单
const resetForm = () => {
  formData.value = {
    code: '',
    description: '',
    menu_icon: '',
    menu_path: '',
    component: '',
    parent_id: props.parentId || undefined,
    title: '',
    title_en: '',
    type: 1,
    is_web_page: false,
    web_url: '',
    is_new_tab: false,
    is_full: false,
    hide_menu: false,
    id: undefined,
    identity: undefined,
    app_id: undefined,
    sort_key: undefined,
    created_at: undefined,
  }
  formRef.value?.clearValidate()
}

// 监听 mode 和 initialValues 变化
watch(
  () => [props.mode, props.initialValues] as const,
  ([mode, initialValues]) => {
    if (mode === 'add' || mode === 'add_child') {
      resetForm()
    } else if (mode === 'edit' && initialValues) {
      // 编辑模式：保留所有原始数据，只更新表单字段
      formData.value = {
        id: initialValues.id,
        identity: initialValues.identity,
        app_id: initialValues.app_id ?? 2,
        sort_key: initialValues.sort_key,
        created_at: initialValues.created_at,
        code: initialValues.code || '',
        description: initialValues.description || '',
        menu_icon: initialValues.menu_icon || '',
        menu_path: initialValues.menu_path || '',
        component: initialValues.component || '',
        parent_id: initialValues.parent_id,
        title: initialValues.title || '',
        title_en: initialValues.title_en || '',
        type: initialValues.type || 1,
        is_web_page: initialValues.is_web_page || false,
        web_url: initialValues.web_url || '',
        is_new_tab: initialValues.is_new_tab || false,
        is_full: initialValues.is_full || false,
        hide_menu: initialValues.hide_menu || false,
      }
    }
  },
  { immediate: true }
)

// 监听父ID变化
watch(() => props.parentId, (val) => {
  if (props.mode === 'add_child') {
    formData.value.parent_id = val || undefined
  }
}, { immediate: true })

// 选择图标
const selectIcon = (icon: string) => {
  formData.value.menu_icon = icon
  iconPickerVisible.value = false
  iconSearch.value = ''
}

// 清空图标
const clearIcon = () => {
  formData.value.menu_icon = ''
}

// 提交表单
const handleSubmit = async () => {
  try {
    loading.value = true
    const valid = await formRef.value?.validate()
    if (valid) return
    
    emit('save', { ...formData.value })
  } catch (error) {
    console.error('Form validation error:', error)
  } finally {
    loading.value = false
  }
}
</script>

<script lang="ts">
export default {
  name: 'MenuForm',
}
</script>

<style scoped lang="less">
.menu-form {
  .switch-label {
    margin-left: 8px;
    color: var(--color-text-2);
  }
  
  .form-actions {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid var(--color-border);
    text-align: right;
  }
}

.icon-search {
  margin-bottom: 16px;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
  max-height: 400px;
  overflow-y: auto;
  overflow-x: hidden;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 8px;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    border-color: rgb(var(--primary-6));
    background-color: rgb(var(--primary-1));
  }
  
  &.is-selected {
    border-color: rgb(var(--primary-6));
    background-color: rgb(var(--primary-1));
    position: relative;
    
    &::after {
      content: '✓';
      position: absolute;
      top: 4px;
      right: 4px;
      color: rgb(var(--primary-6));
      font-size: 12px;
    }
  }
  
  .icon-preview {
    font-size: 24px;
    color: var(--color-text-1);
  }
  
  .icon-name {
    margin-top: 4px;
    font-size: 10px;
    color: var(--color-text-3);
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
  }
}
</style>
