'use client'
import { useState } from 'react'
import { Plus, Upload, Download, X, ChevronDown, ChevronUp, Smartphone, Package, Trash2, Layers, Monitor, Globe } from 'lucide-react'
import { useApi } from '@/lib/hooks'

interface AppPlatform { id: number; app_id: number; platform_type: number; platform_name: string; description: string; file_types: string[]; dist_types: { value: string; label: string }[] }
interface AppVersion { id: number; app_id: number; platform_id: number; major_version: number; minor_version: number; patch_version: number; version_name: string; description: string; file_type: string; file_url: string; file_size: number; distribution_type: string; primary_url: string; min_support_version: string; os_min_version: string; status: number; is_force_update: number; release_date: string; changelog: string[]; platform_name: string }
interface AppItem { id: number; name: string; package_name: string; description: string; status: number; create_time: string; platforms: { id: number; platform_type: number; platform_name: string }[]; versionCount: number }
interface AppDetail extends Omit<AppItem, 'versionCount'> { platforms: AppPlatform[]; versions: AppVersion[] }

const PLATFORM_OPTIONS = [
  { value: 1, label: 'iOS', icon: Smartphone },
  { value: 2, label: 'Android', icon: Smartphone },
  { value: 3, label: 'HarmonyOS', icon: Smartphone },
  { value: 4, label: 'Windows', icon: Monitor },
  { value: 5, label: 'macOS', icon: Monitor },
  { value: 6, label: 'Linux', icon: Monitor },
  { value: 7, label: 'Web', icon: Globe },
]

const FILE_TYPES: Record<number, string[]> = { 1: ['ipa'], 2: ['apk', 'aab'], 3: ['hap'], 4: ['exe', 'msi', 'appx'], 5: ['dmg', 'pkg'], 6: ['deb', 'rpm', 'AppImage'], 7: [] }
const DIST_TYPES: Record<number, { value: string; label: string }[]> = {
  1: [{ value: 'app_store', label: 'App Store' }, { value: 'testflight', label: 'TestFlight' }, { value: 'enterprise', label: '企业签名' }],
  2: [{ value: 'google_play', label: 'Google Play' }, { value: 'direct', label: '直接下载' }, { value: 'huawei', label: '华为应用市场' }],
  3: [{ value: 'huawei', label: '华为应用市场' }, { value: 'direct', label: '直接下载' }],
  4: [{ value: 'microsoft_store', label: 'Microsoft Store' }, { value: 'direct', label: '直接下载' }],
  5: [{ value: 'app_store', label: 'Mac App Store' }, { value: 'direct', label: '直接下载' }],
  6: [{ value: 'direct', label: '直接下载' }], 7: [{ value: 'direct', label: '直接访问' }],
}

function vStatusStyle(s: number) {
  return s === 1 ? { backgroundColor: '#F6FFED', color: '#52C41A', border: '1px solid #B7EB8F' }
    : s === 0 ? { backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.45)', border: '1px solid #D9D9D9' }
    : { backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.45)', border: '1px solid #D9D9D9' }
}
const vStatusText = (s: number) => s === 1 ? '启用' : '禁用'

export default function AppManagePage() {
  const { data: apps, loading, refetch } = useApi<AppItem[]>('/api/app-versions', [])
  const [selectedAppId, setSelectedAppId] = useState<number | null>(null)
  const [appDetail, setAppDetail] = useState<AppDetail | null>(null)
  const [appDrawer, setAppDrawer] = useState(false)
  const [platformDrawer, setPlatformDrawer] = useState(false)
  const [versionDrawer, setVersionDrawer] = useState(false)
  const [appForm, setAppForm] = useState({ name: '', package_name: '', description: '', platform_type: 2, major: 1, minor: 0, patch: 0, file_type: '', file_size: '', distribution_type: '', os_min_version: '', is_force_update: false, changelog: '' })
  const [platForm, setPlatForm] = useState({ platform_type: 2, description: '' })
  const [verForm, setVerForm] = useState({ platform_id: 0, major: 0, minor: 0, patch: 0, description: '', file_type: '', file_size: '', distribution_type: '', os_min_version: '', is_force_update: false, changelog: '' })
  const [expandedVerId, setExpandedVerId] = useState<number | null>(null)

  const loadDetail = async (id: number) => {
    setSelectedAppId(id)
    const r = await fetch(`/api/app-versions?app_id=${id}`)
    setAppDetail(await r.json())
  }
  const handleCreateApp = async () => {
    // 1. 创建应用
    const appRes = await fetch('/api/app-versions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'create_app', name: appForm.name, package_name: appForm.package_name, description: appForm.description }) })
    const { id: appId } = await appRes.json()
    // 2. 创建平台
    const platRes = await fetch('/api/app-versions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'add_platform', app_id: appId, platform_type: appForm.platform_type }) })
    const { id: platformId } = await platRes.json()
    // 3. 创建首个版本
    const vn = `${appForm.major}.${appForm.minor}.${appForm.patch}`
    await fetch('/api/app-versions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'add_version', app_id: appId, platform_id: platformId, major_version: appForm.major, minor_version: appForm.minor, patch_version: appForm.patch, version_name: vn, file_type: appForm.file_type, file_size: parseInt(appForm.file_size) || 0, distribution_type: appForm.distribution_type, os_min_version: appForm.os_min_version, is_force_update: appForm.is_force_update, changelog: appForm.changelog.split('\n').filter(Boolean) }) })
    refetch(); setAppDrawer(false); loadDetail(appId)
  }
  const handleAddPlatform = async () => {
    if (!selectedAppId) return
    await fetch('/api/app-versions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'add_platform', app_id: selectedAppId, platform_type: platForm.platform_type, description: platForm.description }) })
    loadDetail(selectedAppId); setPlatformDrawer(false)
  }
  const handleAddVersion = async () => {
    if (!selectedAppId || !verForm.platform_id) return
    const vn = `${verForm.major}.${verForm.minor}.${verForm.patch}`
    await fetch('/api/app-versions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'add_version', app_id: selectedAppId, platform_id: verForm.platform_id, major_version: verForm.major, minor_version: verForm.minor, patch_version: verForm.patch, version_name: vn, description: verForm.description, file_type: verForm.file_type, file_size: parseInt(verForm.file_size) || 0, distribution_type: verForm.distribution_type, os_min_version: verForm.os_min_version, is_force_update: verForm.is_force_update, changelog: verForm.changelog.split('\n').filter(Boolean) }) })
    loadDetail(selectedAppId); setVersionDrawer(false)
  }
  const handleVerStatus = async (id: number, status: number) => {
    await fetch('/api/app-versions', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'update_version_status', id, status }) })
    if (selectedAppId) loadDetail(selectedAppId)
  }
  const handleDeleteApp = async (id: number) => {
    await fetch(`/api/app-versions?id=${id}&type=app`, { method: 'DELETE' })
    refetch(); if (selectedAppId === id) { setSelectedAppId(null); setAppDetail(null) }
  }
  const handleDeletePlatform = async (pid: number) => {
    await fetch(`/api/app-versions?id=${pid}&type=platform`, { method: 'DELETE' })
    if (selectedAppId) loadDetail(selectedAppId)
  }

  // 当前选中平台的文件类型和分发类型
  const selectedPlatform = appDetail?.platforms.find(p => p.id === verForm.platform_id)

  if (loading) return <div style={{ padding: 24 }}>加载中...</div>

  return (
    <div style={{ padding: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <div>
          <h2 style={{ fontSize: 20, fontWeight: 600, margin: 0 }}>应用管理</h2>
          <p style={{ fontSize: 14, color: 'rgba(0,0,0,0.45)', margin: '4px 0 0' }}>管理应用、平台与版本发布</p>
        </div>
        <button onClick={() => { setAppDrawer(true); setAppForm({ name: '', package_name: '', description: '', platform_type: 2, major: 1, minor: 0, patch: 0, file_type: '', file_size: '', distribution_type: '', os_min_version: '', is_force_update: false, changelog: '' }) }} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 16px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}><Plus size={16} />新建应用</button>
      </div>

      <div style={{ display: 'flex', gap: 24 }}>
        {/* 左侧应用列表 */}
        <div style={{ width: 300, flexShrink: 0 }}>
          <div style={{ backgroundColor: '#fff', borderRadius: 8, boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
            <div style={{ padding: '14px 16px', borderBottom: '1px solid #F0F0F0', fontSize: 14, fontWeight: 600 }}>应用列表（{apps.length}）</div>
            {apps.length === 0 ? (
              <div style={{ padding: 32, textAlign: 'center', color: 'rgba(0,0,0,0.25)', fontSize: 13 }}>暂无应用</div>
            ) : apps.map(app => (
              <div key={app.id} onClick={() => loadDetail(app.id)} style={{ padding: '14px 16px', borderBottom: '1px solid #F0F0F0', cursor: 'pointer', backgroundColor: selectedAppId === app.id ? '#eef5f0' : '#fff', borderLeft: selectedAppId === app.id ? '3px solid #4a7c59' : '3px solid transparent' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
                  <span style={{ fontSize: 14, fontWeight: 500 }}>{app.name}</span>
                  <span style={{ fontSize: 11, color: app.status === 1 ? '#52C41A' : 'rgba(0,0,0,0.45)' }}>{app.status === 1 ? '启用' : '禁用'}</span>
                </div>
                <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.45)', marginBottom: 4 }}>{app.package_name || '-'}</div>
                <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                  {app.platforms.map(p => <span key={p.id} style={{ padding: '1px 6px', borderRadius: 3, fontSize: 10, backgroundColor: '#F0F5FF', color: '#597EF7', border: '1px solid #ADC6FF' }}>{p.platform_name}</span>)}
                  <span style={{ fontSize: 10, color: 'rgba(0,0,0,0.35)' }}>{app.versionCount}个版本</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 右侧详情 */}
        <div style={{ flex: 1, minWidth: 0 }}>
          {!appDetail ? (
            <div style={{ backgroundColor: '#fff', borderRadius: 8, padding: 48, textAlign: 'center', boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
              <Layers size={40} style={{ color: 'rgba(0,0,0,0.15)', marginBottom: 12 }} />
              <div style={{ fontSize: 14, color: 'rgba(0,0,0,0.25)' }}>选择左侧应用查看详情</div>
            </div>
          ) : (
            <>
              {/* 应用信息 */}
              <div style={{ backgroundColor: '#fff', borderRadius: 8, padding: 20, marginBottom: 16, boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <div>
                    <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 4 }}>{appDetail.name}</div>
                    <div style={{ fontSize: 13, color: 'rgba(0,0,0,0.45)' }}>{appDetail.package_name || '未设置包名'}</div>
                    {appDetail.description && <div style={{ fontSize: 13, color: 'rgba(0,0,0,0.65)', marginTop: 4 }}>{appDetail.description}</div>}
                  </div>
                  <button onClick={() => handleDeleteApp(appDetail.id)} style={{ color: '#FF4D4F', cursor: 'pointer', border: 'none', background: 'none', fontSize: 13, display: 'flex', alignItems: 'center', gap: 4 }}><Trash2 size={14} />删除</button>
                </div>
              </div>

              {/* 平台管理 */}
              <div style={{ backgroundColor: '#fff', borderRadius: 8, padding: 20, marginBottom: 16, boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                  <h3 style={{ fontSize: 15, fontWeight: 600, margin: 0 }}>支持平台</h3>
                  <button onClick={() => { setPlatformDrawer(true); setPlatForm({ platform_type: 2, description: '' }) }} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '4px 12px', border: '1px solid #4a7c59', borderRadius: 6, backgroundColor: '#fff', color: '#4a7c59', cursor: 'pointer', fontSize: 13 }}><Plus size={14} />添加平台</button>
                </div>
                {appDetail.platforms.length === 0 ? (
                  <div style={{ padding: 20, textAlign: 'center', color: 'rgba(0,0,0,0.25)', fontSize: 13 }}>暂无平台</div>
                ) : (
                  <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                    {appDetail.platforms.map(p => {
                      const count = appDetail.versions.filter(v => v.platform_id === p.id).length
                      return (
                        <div key={p.id} style={{ padding: '12px 16px', borderRadius: 8, border: '1px solid #F0F0F0', backgroundColor: '#FAFAFA', display: 'flex', alignItems: 'center', gap: 10, minWidth: 150 }}>
                          <Smartphone size={18} style={{ color: '#4a7c59' }} />
                          <div style={{ flex: 1 }}>
                            <div style={{ fontSize: 14, fontWeight: 500 }}>{p.platform_name}</div>
                            <div style={{ fontSize: 11, color: 'rgba(0,0,0,0.45)' }}>{count}个版本</div>
                          </div>
                          <button onClick={(e) => { e.stopPropagation(); handleDeletePlatform(p.id) }} style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'rgba(0,0,0,0.25)', padding: 2 }}><Trash2 size={12} /></button>
                        </div>
                      )
                    })}
                  </div>
                )}
              </div>

              {/* 版本列表 */}
              <div style={{ backgroundColor: '#fff', borderRadius: 8, boxShadow: '0 1px 2px rgba(0,0,0,0.05)', overflow: 'hidden' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 20px', borderBottom: '1px solid #F0F0F0' }}>
                  <h3 style={{ fontSize: 15, fontWeight: 600, margin: 0 }}>版本列表（{appDetail.versions.length}）</h3>
                  <button onClick={() => { setVersionDrawer(true); setVerForm({ platform_id: appDetail.platforms[0]?.id || 0, major: 0, minor: 0, patch: 0, description: '', file_type: '', file_size: '', distribution_type: '', os_min_version: '', is_force_update: false, changelog: '' }) }} disabled={appDetail.platforms.length === 0} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '6px 14px', border: 'none', borderRadius: 6, backgroundColor: appDetail.platforms.length > 0 ? '#4a7c59' : '#D9D9D9', color: '#fff', cursor: appDetail.platforms.length > 0 ? 'pointer' : 'not-allowed', fontSize: 13 }}><Upload size={14} />上传新版本</button>
                </div>
                {appDetail.versions.length === 0 ? (
                  <div style={{ padding: 32, textAlign: 'center', color: 'rgba(0,0,0,0.25)', fontSize: 13 }}>暂无版本</div>
                ) : appDetail.versions.map(ver => {
                  const isExp = expandedVerId === ver.id
                  return (
                    <div key={ver.id} style={{ borderBottom: '1px solid #F0F0F0' }}>
                      <div style={{ padding: '14px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, flexWrap: 'wrap' }}>
                          <span style={{ fontSize: 15, fontWeight: 600 }}>{ver.version_name}</span>
                          <span style={{ ...vStatusStyle(ver.status), padding: '2px 8px', borderRadius: 4, fontSize: 11 }}>{vStatusText(ver.status)}</span>
                          {ver.is_force_update ? <span style={{ padding: '2px 6px', borderRadius: 4, fontSize: 10, backgroundColor: '#FFF1F0', color: '#FF4D4F', border: '1px solid #FFCCC7' }}>强制更新</span> : null}
                          <span style={{ padding: '2px 6px', borderRadius: 4, fontSize: 10, backgroundColor: '#F0F5FF', color: '#597EF7', border: '1px solid #ADC6FF' }}>{ver.platform_name}</span>
                          {ver.distribution_type && <span style={{ padding: '2px 6px', borderRadius: 4, fontSize: 10, backgroundColor: '#FFFBE6', color: '#FAAD14', border: '1px solid #FFE58F' }}>{ver.distribution_type}</span>}
                          <span style={{ fontSize: 12, color: 'rgba(0,0,0,0.45)' }}>{ver.release_date}</span>
                        </div>
                        <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                          {ver.status === 1 && <button onClick={() => handleVerStatus(ver.id, 0)} style={{ padding: '4px 10px', border: '1px solid #D9D9D9', borderRadius: 4, backgroundColor: '#fff', cursor: 'pointer', fontSize: 12 }}>禁用</button>}
                          {ver.status === 0 && <button onClick={() => handleVerStatus(ver.id, 1)} style={{ padding: '4px 10px', border: 'none', borderRadius: 4, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 12 }}>启用</button>}
                          <button onClick={() => setExpandedVerId(isExp ? null : ver.id)} style={{ padding: '4px 10px', border: '1px solid #D9D9D9', borderRadius: 4, backgroundColor: '#fff', cursor: 'pointer', fontSize: 12, color: '#4a7c59' }}>{isExp ? '收起' : '详情'}</button>
                        </div>
                      </div>
                      {isExp && (
                        <div style={{ padding: '0 20px 16px' }}>
                          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                            <div style={{ padding: 14, backgroundColor: '#FAFAFA', borderRadius: 6, border: '1px solid #F0F0F0', fontSize: 13, lineHeight: 2 }}>
                              <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>版本号：</span>{ver.major_version}.{ver.minor_version}.{ver.patch_version}</div>
                              <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>显示名称：</span>{ver.version_name}</div>
                              <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>平台：</span>{ver.platform_name}</div>
                              <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>最低系统版本：</span>{ver.os_min_version || '-'}</div>
                              <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>最低支持版本：</span>{ver.min_support_version || '-'}</div>
                              <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>强制更新：</span>{ver.is_force_update ? '是' : '否'}</div>
                            </div>
                            <div style={{ padding: 14, backgroundColor: '#FAFAFA', borderRadius: 6, border: '1px solid #F0F0F0', fontSize: 13, lineHeight: 2 }}>
                              <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>文件类型：</span>{ver.file_type || '-'}</div>
                              <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>文件大小：</span>{ver.file_size ? `${(ver.file_size / 1024 / 1024).toFixed(1)}MB` : '-'}</div>
                              <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>分发类型：</span>{ver.distribution_type || '-'}</div>
                              <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>下载链接：</span>{ver.primary_url || ver.file_url || '-'}</div>
                              {(ver.file_url || ver.primary_url) && <button style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 4, padding: '3px 10px', border: '1px solid #4a7c59', borderRadius: 4, backgroundColor: '#fff', color: '#4a7c59', cursor: 'pointer', fontSize: 12 }}><Download size={12} />下载</button>}
                            </div>
                          </div>
                          {ver.changelog.length > 0 && (
                            <div style={{ marginTop: 12, padding: 14, backgroundColor: '#FAFAFA', borderRadius: 6, border: '1px solid #F0F0F0' }}>
                              <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 8 }}>更新日志</div>
                              <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, color: 'rgba(0,0,0,0.65)', lineHeight: 1.8 }}>
                                {ver.changelog.map((log, i) => <li key={i}>{log}</li>)}
                              </ul>
                            </div>
                          )}
                          {ver.description && <div style={{ marginTop: 12, padding: 14, backgroundColor: '#FAFAFA', borderRadius: 6, border: '1px solid #F0F0F0', fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>{ver.description}</div>}
                        </div>
                      )}
                    </div>
                  )
                })}
              </div>
            </>
          )}
        </div>
      </div>

      {/* 新建应用抽屉 */}
      {appDrawer && (() => {
        const ft = FILE_TYPES[appForm.platform_type] || []
        const dt = DIST_TYPES[appForm.platform_type] || []
        return (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
          <div onClick={() => setAppDrawer(false)} style={{ position: 'absolute', inset: 0, backgroundColor: 'rgba(0,0,0,0.45)' }} />
          <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 580, backgroundColor: '#fff', boxShadow: '-2px 0 8px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 24px', borderBottom: '1px solid #F0F0F0' }}>
              <h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>新建应用</h3>
              <button onClick={() => setAppDrawer(false)} style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 4 }}><X size={20} /></button>
            </div>
            <div style={{ flex: 1, overflow: 'auto', padding: 24 }}>
              {/* 应用基本信息 */}
              <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 16, paddingBottom: 8, borderBottom: '1px solid #F0F0F0', marginTop: 0 }}>应用信息</h4>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}><span style={{ color: '#FF4D4F' }}>*</span> 应用名称</label>
                <input value={appForm.name} onChange={e => setAppForm({ ...appForm, name: e.target.value })} placeholder="如 GeoApp" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
              </div>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}>应用包名</label>
                <input value={appForm.package_name} onChange={e => setAppForm({ ...appForm, package_name: e.target.value })} placeholder="如 com.geomative.app" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}>应用描述</label>
                <textarea value={appForm.description} onChange={e => setAppForm({ ...appForm, description: e.target.value })} rows={2} placeholder="应用描述" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box', resize: 'vertical' }} />
              </div>

              {/* 平台选择 */}
              <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 16, paddingBottom: 8, borderBottom: '1px solid #F0F0F0', marginTop: 0 }}>平台与版本</h4>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 8 }}><span style={{ color: '#FF4D4F' }}>*</span> 目标平台</label>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {PLATFORM_OPTIONS.map(p => (
                    <button key={p.value} onClick={() => setAppForm({ ...appForm, platform_type: p.value, file_type: '', distribution_type: '' })} style={{ padding: '6px 14px', borderRadius: 6, fontSize: 13, cursor: 'pointer', border: appForm.platform_type === p.value ? '1px solid #4a7c59' : '1px solid #D9D9D9', backgroundColor: appForm.platform_type === p.value ? '#eef5f0' : '#fff', color: appForm.platform_type === p.value ? '#4a7c59' : 'rgba(0,0,0,0.65)', display: 'flex', alignItems: 'center', gap: 4 }}>
                      <p.icon size={13} />{p.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* 版本号 */}
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}><span style={{ color: '#FF4D4F' }}>*</span> 版本号</label>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <input type="number" min={0} value={appForm.major} onChange={e => setAppForm({ ...appForm, major: parseInt(e.target.value) || 0 })} style={{ width: 70, padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, textAlign: 'center', boxSizing: 'border-box' }} />
                  <span style={{ fontSize: 18, color: 'rgba(0,0,0,0.45)' }}>.</span>
                  <input type="number" min={0} value={appForm.minor} onChange={e => setAppForm({ ...appForm, minor: parseInt(e.target.value) || 0 })} style={{ width: 70, padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, textAlign: 'center', boxSizing: 'border-box' }} />
                  <span style={{ fontSize: 18, color: 'rgba(0,0,0,0.45)' }}>.</span>
                  <input type="number" min={0} value={appForm.patch} onChange={e => setAppForm({ ...appForm, patch: parseInt(e.target.value) || 0 })} style={{ width: 70, padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, textAlign: 'center', boxSizing: 'border-box' }} />
                  <span style={{ fontSize: 13, color: 'rgba(0,0,0,0.45)', marginLeft: 8 }}>→ {appForm.major}.{appForm.minor}.{appForm.patch}</span>
                </div>
              </div>

              {/* 安装包上传 */}
              <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 16, paddingBottom: 8, borderBottom: '1px solid #F0F0F0', marginTop: 0 }}>安装包</h4>
              <div style={{ marginBottom: 16 }}>
                <div style={{ border: '2px dashed #D9D9D9', borderRadius: 8, padding: 24, textAlign: 'center', cursor: 'pointer', backgroundColor: '#FAFAFA' }}>
                  <Upload size={28} style={{ color: 'rgba(0,0,0,0.25)', marginBottom: 6 }} />
                  <div style={{ fontSize: 13, color: 'rgba(0,0,0,0.45)' }}>点击或拖拽上传安装包</div>
                  {ft.length > 0 && <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.25)', marginTop: 4 }}>支持格式：{ft.join(' / ')}</div>}
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
                {ft.length > 0 && (
                  <div>
                    <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>文件类型</label>
                    <select value={appForm.file_type} onChange={e => setAppForm({ ...appForm, file_type: e.target.value })} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
                      <option value="">请选择</option>
                      {ft.map(f => <option key={f} value={f}>{f}</option>)}
                    </select>
                  </div>
                )}
                {dt.length > 0 && (
                  <div>
                    <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>分发类型</label>
                    <select value={appForm.distribution_type} onChange={e => setAppForm({ ...appForm, distribution_type: e.target.value })} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
                      <option value="">请选择</option>
                      {dt.map(d => <option key={d.value} value={d.value}>{d.label}</option>)}
                    </select>
                  </div>
                )}
                <div>
                  <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>文件大小（字节）</label>
                  <input value={appForm.file_size} onChange={e => setAppForm({ ...appForm, file_size: e.target.value })} placeholder="如 47185920" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>最低系统版本</label>
                  <input value={appForm.os_min_version} onChange={e => setAppForm({ ...appForm, os_min_version: e.target.value })} placeholder="如 Android 10" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
                </div>
              </div>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 14, cursor: 'pointer' }}>
                  <input type="checkbox" checked={appForm.is_force_update} onChange={e => setAppForm({ ...appForm, is_force_update: e.target.checked })} />强制更新
                </label>
              </div>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}>更新日志（每行一条）</label>
                <textarea value={appForm.changelog} onChange={e => setAppForm({ ...appForm, changelog: e.target.value })} rows={3} placeholder="新增XX功能&#10;修复XX问题" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box', resize: 'vertical' }} />
              </div>
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button onClick={() => setAppDrawer(false)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
              <button onClick={handleCreateApp} disabled={!appForm.name} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: appForm.name ? '#4a7c59' : '#D9D9D9', color: '#fff', cursor: appForm.name ? 'pointer' : 'not-allowed', fontSize: 14 }}>创建应用</button>
            </div>
          </div>
        </div>
        )
      })()}

      {/* 添加平台抽屉 */}
      {platformDrawer && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
          <div onClick={() => setPlatformDrawer(false)} style={{ position: 'absolute', inset: 0, backgroundColor: 'rgba(0,0,0,0.45)' }} />
          <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 480, backgroundColor: '#fff', boxShadow: '-2px 0 8px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 24px', borderBottom: '1px solid #F0F0F0' }}>
              <h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>添加平台</h3>
              <button onClick={() => setPlatformDrawer(false)} style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 4 }}><X size={20} /></button>
            </div>
            <div style={{ flex: 1, overflow: 'auto', padding: 24 }}>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}><span style={{ color: '#FF4D4F' }}>*</span> 平台类型</label>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {PLATFORM_OPTIONS.map(p => (
                    <button key={p.value} onClick={() => setPlatForm({ ...platForm, platform_type: p.value })} style={{ padding: '8px 16px', borderRadius: 6, fontSize: 13, cursor: 'pointer', border: platForm.platform_type === p.value ? '1px solid #4a7c59' : '1px solid #D9D9D9', backgroundColor: platForm.platform_type === p.value ? '#eef5f0' : '#fff', color: platForm.platform_type === p.value ? '#4a7c59' : 'rgba(0,0,0,0.65)', display: 'flex', alignItems: 'center', gap: 6 }}>
                      <p.icon size={14} />{p.label}
                    </button>
                  ))}
                </div>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}>描述</label>
                <input value={platForm.description} onChange={e => setPlatForm({ ...platForm, description: e.target.value })} placeholder="平台描述" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
              </div>
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button onClick={() => setPlatformDrawer(false)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
              <button onClick={handleAddPlatform} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>添加</button>
            </div>
          </div>
        </div>
      )}

      {/* 上传版本抽屉 */}
      {versionDrawer && appDetail && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
          <div onClick={() => setVersionDrawer(false)} style={{ position: 'absolute', inset: 0, backgroundColor: 'rgba(0,0,0,0.45)' }} />
          <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 560, backgroundColor: '#fff', boxShadow: '-2px 0 8px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 24px', borderBottom: '1px solid #F0F0F0' }}>
              <h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>上传新版本</h3>
              <button onClick={() => setVersionDrawer(false)} style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 4 }}><X size={20} /></button>
            </div>
            <div style={{ flex: 1, overflow: 'auto', padding: 24 }}>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}><span style={{ color: '#FF4D4F' }}>*</span> 目标平台</label>
                <select value={verForm.platform_id} onChange={e => setVerForm({ ...verForm, platform_id: Number(e.target.value), file_type: '', distribution_type: '' })} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
                  {appDetail.platforms.map(p => <option key={p.id} value={p.id}>{p.platform_name}</option>)}
                </select>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}><span style={{ color: '#FF4D4F' }}>*</span> 版本号</label>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <input type="number" min={0} value={verForm.major} onChange={e => setVerForm({ ...verForm, major: parseInt(e.target.value) || 0 })} placeholder="主版本" style={{ width: 80, padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, textAlign: 'center', boxSizing: 'border-box' }} />
                  <span style={{ fontSize: 18, color: 'rgba(0,0,0,0.45)' }}>.</span>
                  <input type="number" min={0} value={verForm.minor} onChange={e => setVerForm({ ...verForm, minor: parseInt(e.target.value) || 0 })} placeholder="次版本" style={{ width: 80, padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, textAlign: 'center', boxSizing: 'border-box' }} />
                  <span style={{ fontSize: 18, color: 'rgba(0,0,0,0.45)' }}>.</span>
                  <input type="number" min={0} value={verForm.patch} onChange={e => setVerForm({ ...verForm, patch: parseInt(e.target.value) || 0 })} placeholder="修订" style={{ width: 80, padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, textAlign: 'center', boxSizing: 'border-box' }} />
                  <span style={{ fontSize: 13, color: 'rgba(0,0,0,0.45)', marginLeft: 8 }}>→ {verForm.major}.{verForm.minor}.{verForm.patch}</span>
                </div>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}>安装包</label>
                <div style={{ border: '2px dashed #D9D9D9', borderRadius: 8, padding: 24, textAlign: 'center', cursor: 'pointer', backgroundColor: '#FAFAFA' }}>
                  <Upload size={28} style={{ color: 'rgba(0,0,0,0.25)', marginBottom: 6 }} />
                  <div style={{ fontSize: 13, color: 'rgba(0,0,0,0.45)' }}>点击或拖拽上传安装包</div>
                  {selectedPlatform && <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.25)', marginTop: 4 }}>支持格式：{selectedPlatform.file_types.join(' / ') || '任意'}</div>}
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 20 }}>
                {selectedPlatform && selectedPlatform.file_types.length > 0 && (
                  <div>
                    <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>文件类型</label>
                    <select value={verForm.file_type} onChange={e => setVerForm({ ...verForm, file_type: e.target.value })} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
                      <option value="">请选择</option>
                      {selectedPlatform.file_types.map(ft => <option key={ft} value={ft}>{ft}</option>)}
                    </select>
                  </div>
                )}
                {selectedPlatform && selectedPlatform.dist_types.length > 0 && (
                  <div>
                    <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>分发类型</label>
                    <select value={verForm.distribution_type} onChange={e => setVerForm({ ...verForm, distribution_type: e.target.value })} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
                      <option value="">请选择</option>
                      {selectedPlatform.dist_types.map(dt => <option key={dt.value} value={dt.value}>{dt.label}</option>)}
                    </select>
                  </div>
                )}
                <div>
                  <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>文件大小（字节）</label>
                  <input value={verForm.file_size} onChange={e => setVerForm({ ...verForm, file_size: e.target.value })} placeholder="如 47185920" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>最低系统版本</label>
                  <input value={verForm.os_min_version} onChange={e => setVerForm({ ...verForm, os_min_version: e.target.value })} placeholder="如 Android 10" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
                </div>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 14, cursor: 'pointer' }}>
                  <input type="checkbox" checked={verForm.is_force_update} onChange={e => setVerForm({ ...verForm, is_force_update: e.target.checked })} />强制更新
                </label>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}>版本描述</label>
                <textarea value={verForm.description} onChange={e => setVerForm({ ...verForm, description: e.target.value })} rows={2} placeholder="版本描述" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box', resize: 'vertical' }} />
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}>更新日志（每行一条）</label>
                <textarea value={verForm.changelog} onChange={e => setVerForm({ ...verForm, changelog: e.target.value })} rows={4} placeholder="新增XX功能&#10;修复XX问题" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box', resize: 'vertical' }} />
              </div>
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button onClick={() => setVersionDrawer(false)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
              <button onClick={handleAddVersion} disabled={!verForm.platform_id} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: verForm.platform_id ? '#4a7c59' : '#D9D9D9', color: '#fff', cursor: verForm.platform_id ? 'pointer' : 'not-allowed', fontSize: 14 }}>上传版本</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
