<script setup lang="ts">
import { Upload } from 'lucide-vue-next'
import { ref, reactive } from 'vue'
import { ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElCheckbox, ElMessage, ElUpload, ElButton } from 'element-plus'
import 'element-plus/dist/index.css'

// 固件列表接口 - 新增 firmwareType 字段
interface Firmware {
  version: string
  releaseDate: string
  status: '已发布' | '草稿'
  fileSize: string
  downloads: number
  md5?: string
  sha256?: string
  model?: string
  hardwareRange?: string
  upgradeType?: string
  signed?: boolean
  notes?: string[]
  expanded: boolean
  firmwareType: '主协板' | '采集板' | '发射板' | '主机固件' | '计算单元固件' // 新增固件类型
}

// 上传表单接口 - 新增 firmwareType 字段
interface FirmwareUploadForm {
  version: string
  hardwareRange: string
  upgradeType: '可选' | '强制'
  signed: boolean
  notes: string
  file: File | null
  firmwareType: '主协板' | '采集板' | '发射板' | '主机固件' | '计算单元固件' // 新增固件类型
}

const firmwares = ref<Firmware[]>([
  {
    version: 'v2.3.0',
    releaseDate: '2024-02-20',
    status: '已发布',
    fileSize: '12.5MB',
    downloads: 1234,
    md5: 'a1b2c3d4e5f6...',
    sha256: '...',
    model: 'GD30',
    hardwareRange: 'A1-A3',
    upgradeType: '可选',
    signed: true,
    notes: [
      '修复OTA升级流程中的断点续传Bug',
      '优化设备心跳上报频率',
      '新增配置文件远程下发功能',
      '增强安全性，升级前强制验证固件签名',
    ],
    expanded: true,
    firmwareType: '主机固件' // 为原有数据补充固件类型
  },
  {
    version: 'v2.2.0',
    releaseDate: '2024-01-15',
    status: '已发布',
    fileSize: '12.0MB',
    downloads: 2456,
    expanded: false,
    firmwareType: '主协板' // 为原有数据补充固件类型
  },
  {
    version: 'v2.1.0',
    releaseDate: '2023-12-01',
    status: '已发布',
    fileSize: '11.5MB',
    downloads: 3587,
    expanded: false,
    firmwareType: '采集板' // 为原有数据补充固件类型
  },
])

// ============== 上传弹窗相关 ==============
const uploadDialogVisible = ref(false)
// 升级类型选项
const upgradeTypes = ref<('可选' | '强制')[]>(['可选', '强制'])
// 新增：固件类型选项（5种）
const firmwareTypes = ref<('主协板' | '采集板' | '发射板' | '主机固件' | '计算单元固件')[]>(
  ['主协板', '采集板', '发射板', '主机固件', '计算单元固件']
)

// 初始化上传表单 - 新增 firmwareType 默认值
const uploadForm = ref<FirmwareUploadForm>({
  version: '',
  hardwareRange: '',
  upgradeType: '可选',
  signed: true,
  notes: '',
  file: null,
  firmwareType: '主机固件' // 固件类型默认值
})

// 表单校验规则 - 新增 firmwareType 必选校验
const uploadFormRules = reactive({
  version: [{ required: true, message: '请输入固件版本', trigger: 'blur' }],
  hardwareRange: [{ required: true, message: '请输入硬件版本范围', trigger: 'blur' }],
  upgradeType: [{ required: true, message: '请选择升级类型', trigger: 'change' }],
  firmwareType: [{ required: true, message: '请选择固件类型', trigger: 'change' }], // 新增
  file: [{ required: true, message: '请上传固件ZIP包', trigger: 'change' }]
})

// 文件上传前校验（仅允许ZIP）
const beforeUpload = (file: File) => {
  const isZip = file.type === 'application/zip' || file.name.endsWith('.zip')
  if (!isZip) {
    ElMessage.error('只能上传 ZIP 格式的固件包！')
    return false
  }
  uploadForm.value.file = file
  return false // 关闭自动上传，手动提交
}

// 重置表单
const resetUploadForm = () => {
  uploadForm.value = {
    version: '',
    hardwareRange: '',
    upgradeType: '可选',
    signed: true,
    notes: '',
    file: null,
    firmwareType: '主机固件' // 重置时恢复默认值
  }
}

// 表单ref（用于校验）
const uploadFormRef = ref<any>(null)

// 提交上传固件
const handleUploadSubmit = () => {
  if (!uploadFormRef.value) return
  
  uploadFormRef.value.validate((valid: boolean) => {
    if (!valid) return

    // 组装新固件数据 - 新增 firmwareType 字段
    const newFirmware: Firmware = {
      version: uploadForm.value.version,
      releaseDate: new Date().toISOString().split('T')[0],
      status: '草稿',
      fileSize: formatFileSize(uploadForm.value.file!.size),
      downloads: 0,
      model: 'GD30',
      hardwareRange: uploadForm.value.hardwareRange,
      upgradeType: uploadForm.value.upgradeType,
      signed: uploadForm.value.signed,
      notes: uploadForm.value.notes.split('\n').filter(item => item.trim()),
      expanded: false,
      firmwareType: uploadForm.value.firmwareType // 新增固件类型赋值
    }

    // 添加到列表
    firmwares.value.unshift(newFirmware)
    ElMessage.success('固件上传成功！')
    uploadDialogVisible.value = false
    resetUploadForm()
  })
}

// 文件大小格式化
const formatFileSize = (bytes: number): string => {
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB'
  return (bytes / (1024 * 1024)).toFixed(1) + 'MB'
}
</script>

<template>
  <div class="p-6">
    <!-- Page Header -->
    <div class="mb-6">
      <div class="flex items-center justify-between mb-2">
        <h2 class="text-2xl font-semibold">固件库</h2>
        <div class="flex items-center gap-3">
          <button class="px-4 py-2 rounded text-white flex items-center gap-2" style="background-color: #4a7c59" @click="uploadDialogVisible = true">
            <Upload :size="16" />
            上传固件
          </button>
        </div>
      </div>
    </div>

    <!-- Firmware Version List -->
    <div class="bg-white rounded-lg" style="box-shadow: 0 1px 2px rgba(0,0,0,0.05)">
      <div class="p-6 border-b" style="border-color: #F0F0F0">
        <h3 class="text-base font-medium">固件版本库</h3>
      </div>

      <div class="divide-y" style="border-color: #F0F0F0">
        <div v-for="fw in firmwares" :key="fw.version" class="p-6">
          <!-- Header row - 新增固件类型展示 -->
          <div class="flex items-center gap-4 mb-2 flex-wrap">
            <span class="text-lg font-semibold">版本: {{ fw.version }}</span>
            <span class="text-sm" style="color: rgba(0,0,0,0.45)">发布日期: {{ fw.releaseDate }}</span>
            <span class="text-sm" style="color: #52C41A">{{ fw.status }}</span>
          </div>

          <!-- Basic info -->
          <div class="text-sm mb-1" style="color: rgba(0,0,0,0.65)">
            文件大小: {{ fw.fileSize }}&emsp;下载次数: {{ fw.downloads.toLocaleString() }}次
          </div>

          <!-- Expanded detail -->
          <template v-if="fw.expanded && fw.md5">
            <div class="text-sm mb-1" style="color: rgba(0,0,0,0.65)">
              MD5: {{ fw.md5 }}&emsp;SHA256: {{ fw.sha256 }}
            </div>
            <div class="text-sm mb-3" style="color: rgba(0,0,0,0.65)">
              升级类型: {{ fw.upgradeType }}
            </div>

            <!-- Signature -->
            <div v-if="fw.signed" class="mb-3">
              <span class="text-sm" style="color: #52C41A">数字签名: 已签名</span>
            </div>

            <!-- Release notes -->
            <div v-if="fw.notes && fw.notes.length" class="mb-4">
              <div class="text-sm font-medium mb-1" style="color: rgba(0,0,0,0.85)">发布说明:</div>
              <ul class="text-sm list-disc pl-5" style="color: rgba(0,0,0,0.65)">
                <li v-for="(note, i) in fw.notes" :key="i">{{ note }}</li>
              </ul>
            </div>

            <!-- Actions (expanded) -->
            <div class="flex items-center gap-6 pt-2">
              <button class="text-sm" style="color: #4a7c59">下载</button>
              <button class="text-sm" style="color: #4a7c59">编辑</button>
              <button class="text-sm" style="color: #4a7c59">撤回发布</button>
            </div>
          </template>

          <!-- Collapsed actions -->
          <template v-else>
            <div class="flex items-center gap-6 pt-3">
              <button class="text-sm" style="color: #4a7c59">下载</button>
              <button class="text-sm" style="color: #4a7c59" @click="fw.expanded = true">查看详情</button>
            </div>
          </template>
        </div>
      </div>
    </div>

    <!-- ============== 上传固件弹窗 ============== -->
    <ElDialog v-model="uploadDialogVisible" title="上传固件" width="550px" append-to-body>
      <ElForm :model="uploadForm" :rules="uploadFormRules" ref="uploadFormRef" label-width="110px" class="mt-4">
        <!-- 固件版本 -->
        <ElFormItem label="固件版本" prop="version">
          <ElInput v-model="uploadForm.version" placeholder="例如：v2.4.0" />
        </ElFormItem>

        <!-- 硬件版本范围 -->
        <ElFormItem label="硬件版本范围" prop="hardwareRange">
          <ElInput v-model="uploadForm.hardwareRange" placeholder="例如：A1-A3" />
        </ElFormItem>

        <!-- 升级类型 -->
        <ElFormItem label="升级类型" prop="upgradeType">
          <ElSelect v-model="uploadForm.upgradeType" placeholder="请选择升级类型">
            <ElOption v-for="type in upgradeTypes" :key="type" :label="type" :value="type" />
          </ElSelect>
        </ElFormItem>

        <!-- 数字签名 -->
        <ElFormItem label="数字签名">
          <ElCheckbox v-model="uploadForm.signed">已签名</ElCheckbox>
        </ElFormItem>

        <!-- 固件上传 -->
        <ElFormItem label="固件包" prop="file">
          <ElUpload
            :before-upload="beforeUpload"
            :file-list="[]"
            accept=".zip"
            drag
          >
            <div class="el-upload__text">点击或拖拽 ZIP 文件到此处</div>
          </ElUpload>
        </ElFormItem>

        <!-- 发布说明 -->
        <ElFormItem label="发布说明">
          <el-input
            v-model="uploadForm.notes"
            style="width: 100%"
            :rows="4"
            type="textarea"
            placeholder="每行一条发布说明，自动换行分割"
          />
        </ElFormItem>
      </ElForm>

      <!-- 弹窗底部按钮 -->
      <template #footer>
        <div class="flex justify-end gap-2">
          <ElButton @click="uploadDialogVisible = false; resetUploadForm()">取消</ElButton>
          <ElButton type="primary" style="background-color: #4a7c59; border-color: #4a7c59" @click="handleUploadSubmit">确认上传</ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>