<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    :body-style="{ maxHeight: width >= 650 ? '76vh' : '100vh' }"
    :width="width >= 650 ? 650 : '100%'"
    draggable
    @before-ok="save"
    @close="reset"
  >
    <a-form ref="formRef" :model="form" :rules="formRules" auto-label-width :layout="width >= 700 ? 'horizontal' : 'vertical'">
      <a-form-item label="菜单类型" field="type">
        <a-radio-group 
          v-model="form.type" 
          type="button" 
          :disabled="isUpdate || loadingMenuType" 
          @change="onChangeType"
        >
          <a-radio 
            v-for="option in menuTypeOptions" 
            :key="option.value" 
            :value="option.value"
          >
            {{ option.label }}
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="上级菜单" field="parentId">
        <a-tree-select
          v-model="form.parentId"
          placeholder="请选择上级菜单"
          allow-clear
          allow-search
          :data="(menuSelectTree as any)"
          :fallback-option="false"
          :filter-tree-node="filterOptions"
          :loading="loadingMenuTree"
          :disabled="loadingMenuTree"
        />
      </a-form-item>
      <a-row>
        <a-col v-bind="colProps">
          <a-form-item label="菜单标题" field="title">
            <a-input v-model.trim="form.title" placeholder="请输入菜单标题" :max-length="30" show-word-limit allow-clear />
          </a-form-item>
        </a-col>
        <a-col v-bind="colProps">
          <a-form-item v-if="[1, 2].includes(form.type)" label="菜单图标" field="icon">
            <GiIconSelector v-model="form.icon" />
          </a-form-item>
          <a-form-item v-else label="权限标识" field="permission">
            <a-input v-model.trim="form.permission" placeholder="system:user:add" :max-length="100" show-word-limit allow-clear />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col v-bind="colProps">
          <a-form-item v-if="[1, 2].includes(form.type)" label="路由地址" field="path">
            <a-input v-model.trim="form.path" placeholder="请输入路由地址" allow-clear />
          </a-form-item>
        </a-col>
        <a-col v-bind="colProps">
          <a-form-item v-if="form.type === 1 || (form.type === 2 && !form.isExternal)" label="重定向" field="redirect">
            <a-input v-model.trim="form.redirect" placeholder="请输入重定向地址" allow-clear />
          </a-form-item>
          <a-form-item v-if="form.type === 2 && form.isExternal" label="组件路径" field="component">
            <a-input v-model.trim="form.component" placeholder="请输入组件路径" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item v-if="form.type === 2 && !form.isExternal" label="组件路径" field="component">
        <a-select v-model="form.component" placeholder="请输入或选择组件路径" allow-clear allow-create :options="componentOptions">
          <template #label="{ data }">
            {{ data?.value }}
          </template>
        </a-select>
      </a-form-item>
      <a-row>
        <a-col v-bind="colProps">
          <a-form-item v-if="form.type === 1 || (form.type === 2 && !form.isExternal)" label="组件名称" field="name">
            <a-input v-model.trim="form.name" placeholder="请输入组件名称" :max-length="50" show-word-limit allow-clear />
            <template #extra>
              <div v-if="componentName">
                <span>建议组件名称：</span>
                <a-tag checkable @check="inputComponentName">{{ componentName }}</a-tag>
              </div>
            </template>
          </a-form-item>
        </a-col>
        <a-col v-bind="colProps">
          <a-form-item v-if="form.type === 2" label="权限标识" field="permission">
            <a-input v-model.trim="form.permission" placeholder="system:user:add" :max-length="100" show-word-limit allow-clear />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row v-if="[1, 2].includes(form.type)" :gutter="16">
        <a-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8" :xxl="8">
          <a-form-item label="是否隐藏" field="hidden">
            <a-switch
              v-model="form.isHidden"
              :checked-value="true"
              :unchecked-value="false"
              checked-text="是"
              unchecked-text="否"
              type="round"
            />
          </a-form-item>
        </a-col>
        <a-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8" :xxl="8">
          <a-form-item label="是否缓存" field="keepAlive">
            <a-switch
              v-model="form.isCache"
              :checked-value="true"
              :unchecked-value="false"
              checked-text="是"
              unchecked-text="否"
              type="round"
            />
          </a-form-item>
        </a-col>
        <a-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8" :xxl="8">
          <a-form-item v-if="form.type === 2" label="是否外链" field="isExternalUrl">
            <a-switch
              v-model="form.isExternal"
              :checked-value="true"
              :unchecked-value="false"
              checked-text="是"
              unchecked-text="否"
              type="round"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="菜单排序" field="sort">
        <a-input-number v-model="form.sort" placeholder="请输入菜单排序" :min="1" mode="button" style="width: 150px" />
      </a-form-item>
      <a-form-item label="状态" field="status">
        <a-switch
          v-model="form.status"
          type="round"
          :checked-value="1"
          :unchecked-value="2"
          checked-text="启用"
          unchecked-text="禁用"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { type ColProps, type FormInstance, Message, type TreeNodeData } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { mapTree } from 'xe-utils'
import { type MenuResp, getMenuDetail, updateMenuNew, addMenu, type MenuAddReq, type MenuUpdateReq, getMenuTree } from '@/apis/system/menu'
import { listMenuType } from '@/apis/common/common'
import { useResetReactive } from '@/hooks'
import { filterTree, transformPathToName } from '@/utils'
import { useComponentPaths } from '@/hooks/modules/useComponentPaths'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const colProps: ColProps = { xs: 24, sm: 24, md: 12, lg: 12, xl: 12, xxl: 12 }

const dataId = ref('')
const visible = ref(false)
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改菜单' : '新增菜单'))
const formRef = ref<FormInstance>()

const menuTreeData = ref<MenuResp[]>([])
const loadingMenuTree = ref(false)

// 菜单类型选项
const menuTypeOptions = ref<Array<{ label: string; value: string | number }>>([])
const loadingMenuType = ref(false)

const [form, resetForm] = useResetReactive({
  type: 1, // 保持使用数字类型：1=目录, 2=菜单, 3=按钮
  sort: 999,
  isExternal: false,
  isCache: false,
  isHidden: false,
  status: 1,
  title: '',
  path: '',
  name: '',
  component: '',
  permission: '',
  parentId: '',
  redirect: '',
  icon: '',
})

const componentName = computed(() => transformPathToName(form.path))

const { componentOptions } = useComponentPaths()

const rules: FormInstance['rules'] = {
  parentId: [{ required: true, message: '请选择上级菜单' }],
  title: [{ required: true, message: '请输入菜单标题' }],
  path: [{ required: true, message: '请输入路由地址' }],
  name: [{ required: true, message: '请输入组件名称' }],
  component: [{ required: true, message: '请输入组件路径' }],
  permission: [{ required: true, message: '请输入权限标识' }],
}
// eslint-disable-next-line vue/return-in-computed-property
const formRules = computed(() => {
  if ([1, 2].includes(form.type)) {
    const { title, name, path } = rules
    return { title, name, path } as FormInstance['rules']
  }
  if (form.type === 3) {
    const { parentId, title, permission } = rules
    return { parentId, title, permission } as FormInstance['rules']
  }
})

// 重置
const reset = () => {
  formRef.value?.resetFields()
  resetForm()
}

// 设置建议组件名
const inputComponentName = () => {
  form.name = componentName.value
}

// 切换类型清除校验
const onChangeType = () => {
  formRef.value?.clearValidate()
}

// 加载菜单树数据
const loadMenuTree = async () => {
  try {
    loadingMenuTree.value = true
    const { data } = await getMenuTree()
    menuTreeData.value = data || []
  } catch (error) {
    console.error('加载菜单树失败:', error)
    Message.error('加载菜单树失败，请稍后重试')
    menuTreeData.value = []
  } finally {
    loadingMenuTree.value = false
  }
}

// 菜单类型映射
const menuTypeMap: Record<string, number> = {
  'catalog': 1,
  'route': 2, // 注意：API返回的是 'route' 而不是 'menu'
  'button': 3
}

// 加载菜单类型选项
const loadMenuTypeOptions = async () => {
  try {
    loadingMenuType.value = true
    const { data } = await listMenuType()
    // 转换API返回的数据格式：[{catalog: "目录"}, {route: "菜单"}, {button: "按钮"}]
    menuTypeOptions.value = data.map(item => {
      // 获取对象的第一个键值对
      const key = Object.keys(item)[0]
      const label = item[key]
      return {
        label: label,
        value: menuTypeMap[key] || 1
              }
      })
    } catch (error) {
    console.error('加载菜单类型失败:', error)
    // 如果API失败，使用默认选项
    menuTypeOptions.value = [
      { label: '目录', value: 1 },
      { label: '菜单', value: 2 },
      { label: '按钮', value: 3 }
    ]
  } finally {
    loadingMenuType.value = false
  }
}

// 转换为菜单树 - 适配新的菜单树数据结构
const menuSelectTree = computed(() => {
  const menus = JSON.parse(JSON.stringify(menuTreeData.value)) as any[]
  // 过滤只显示目录和菜单类型，不显示按钮类型
  const data = filterTree(menus, (i) => {
    const menuType = i.menuType || i.type
    // 支持新API的字符串类型和旧API的数字类型
    return ['catalog', 'route', 'menu', '1', '2', 1, 2].includes(menuType)
  })
  const treeData = mapTree(data, (i) => ({
    key: i.menuId || i.id, // 适配新API的menuId字段
    title: i.menuName || i.title, // 适配新API的menuName字段
    children: i.children,
  }))
  
  // 添加"无上级菜单"选项作为根节点
  const result = [
    {
      key: '0',
      title: '无上级菜单',
      children: treeData,
    }
  ]
  
  return result
})

// 过滤树
const filterOptions = (searchKey: string, nodeData: TreeNodeData) => {
  if (nodeData.title) {
    return nodeData.title.toLowerCase().includes(searchKey.toLowerCase())
  }
  return false
}

// 数字类型转换为API需要的字符串类型
const convertTypeToApiFormat = (type: number): string => {
  const reverseMap: Record<number, string> = {
    1: 'catalog',
    2: 'route', // 修正：API使用 'route' 而不是 'menu'
    3: 'button'
  }
  return reverseMap[type] || String(type)
}

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.validate()
    if (isInvalid) return false
    if (isUpdate.value) {
      // 将表单数据转换成符合新修改接口的格式
      const updateMenuData: MenuUpdateReq = {
        menuName: form.title,
        menuType: convertTypeToApiFormat(form.type),
        orderNum: form.sort,
        parentId: form.parentId || '0',
        perms: form.permission || '',
        terminalType: '', // 可选值，根据实际需要填充
        url: form.path || '',
        visible: form.isHidden ? '0' : '1' // 修正：隐藏时为'0'，显示时为'1'
      }
      
      await updateMenuNew(dataId.value, updateMenuData)
      Message.success('修改成功')
    } else {
      // 将表单数据转换成符合新接口的格式
      const newMenuData: MenuAddReq = {
        menuName: form.title,
        menuType: convertTypeToApiFormat(form.type),
        orderNum: form.sort,
        parentId: form.parentId || '0',
        perms: form.permission || '',
        terminalType: '', // 可选值，根据实际需要填充
        url: form.path || '',
        visible: form.isHidden ? '0' : '1' // 修正：隐藏时为'0'，显示时为'1'
      }
      
      // 直接使用新接口
      await addMenu(newMenuData)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

// 新增
const onAdd = async (id?: string) => {
  reset()
  form.parentId = id || ''
  dataId.value = ''
  // 在打开弹窗时加载菜单树和菜单类型
  await Promise.all([loadMenuTree(), loadMenuTypeOptions()])
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  reset()
  dataId.value = id
  // 在打开弹窗时加载菜单树和菜单类型
  await Promise.all([loadMenuTree(), loadMenuTypeOptions()])
  
  try {
    // 使用新的菜单详情接口
    const { data } = await getMenuDetail(id)
    
    // 将新接口返回的数据映射到表单，处理类型转换
    form.title = data.menuName || ''
    
    // 处理菜单类型转换，支持字符串和数字格式
    form.type = menuTypeMap[data.menuType] || Number(data.menuType) || 1
    
    // 基础信息回显
    form.sort = data.orderNum || 999
    form.parentId = data.parentId || '0' // 确保parentId有默认值
    form.permission = data.perms || ''
    form.path = data.url || ''
    
    // 可见性状态回显 - 根据API文档：'0'表示隐藏，'1'表示显示
    form.isHidden = String(data.visible) === '0'
    
    // 使用any类型处理可能存在的额外字段
    const anyData = data as any
    
    // 如果API返回了完整数据，回显其他字段
    if (anyData.name) form.name = anyData.name
    if (anyData.component) form.component = anyData.component
    if (anyData.redirect) form.redirect = anyData.redirect
    if (anyData.icon) form.icon = anyData.icon
    
    // 处理布尔值字段，支持多种格式
    if (anyData.isExternal !== undefined) {
      form.isExternal = String(anyData.isExternal) === '1' || anyData.isExternal === true
    }
    if (anyData.isCache !== undefined) {
      form.isCache = String(anyData.isCache) === '1' || anyData.isCache === true
    }
    if (anyData.status !== undefined) {
      form.status = String(anyData.status) === '1' || anyData.status === true ? 1 : 2
    }
    
    console.log('菜单详情数据回显完成:', {
      原始数据: data,
      表单数据: form
    })
  } catch (error) {
    console.error('获取菜单详情失败:', error)
    Message.error('获取菜单详情失败')
  }
  
  visible.value = true
}

defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss"></style>
