<template>
  <div class="p-4">
    <VbenForm
      ref="formRef"
      :schema="formSchema"
      :form-options="{
        layout: 'vertical',
        labelCol: { span: 24 },
        wrapperCol: { span: 24 },
      }"
      @submit="handleSave"
    >
      <template #submitButton>
        <div class="flex gap-2">
          <VbenButton type="primary" :loading="saveLoading" @click="handleSave">
            保存配置
          </VbenButton>
          <VbenButton @click="handleTest">
            测试上传
          </VbenButton>
          <VbenButton @click="handleReset">
            重置配置
          </VbenButton>
        </div>
      </template>
    </VbenForm>

    <!-- 测试上传对话框 -->
    <VbenModal
      v-model:open="testDialogVisible"
      title="测试文件上传"
      width="600px"
      @ok="handleUploadTest"
    >
      <div class="upload-test-container">
        <VbenUpload
          ref="uploadRef"
          v-model:file-list="testFileList"
          :max-count="1"
          :show-upload-list="false"
          @change="handleFileChange"
        >
          <div class="upload-area">
            <div class="upload-icon">
              <Icon icon="ep:upload-filled" size="40" />
            </div>
            <div class="upload-text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="upload-tip">
              选择一个文件进行上传测试
            </div>
          </div>
        </VbenUpload>
        
        <div v-if="testFile" class="test-file-info">
          <h4>文件信息：</h4>
          <p>文件名：{{ testFile.name }}</p>
          <p>文件大小：{{ formatFileSize(testFile.size) }}</p>
          <p>文件类型：{{ testFile.type }}</p>
        </div>
      </div>
    </VbenModal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { VbenForm, VbenButton, VbenModal, VbenUpload } from '@vben/components'
import { Icon } from '@iconify/vue'
import { message } from 'ant-design-vue'
import type { FormSchema } from '@vben/types'
import {
  getStorageConfigApi,
  updateStorageConfigApi,
  testStorageApi,
  resetStorageConfigApi,
  type StorageConfig,
} from '@/api/common/storage'

const formRef = ref()
const uploadRef = ref()
const saveLoading = ref(false)
const testDialogVisible = ref(false)
const testFileList = ref([])
const testFile = ref<File | null>(null)

// 表单配置
const formSchema: FormSchema[] = [
  {
    field: 'driver',
    label: '存储驱动',
    component: 'Select',
    required: true,
    componentProps: {
      options: [
        { label: '本地存储', value: 'local' },
        { label: '阿里云OSS', value: 'oss' },
        { label: '腾讯云COS', value: 'cos' },
        { label: '七牛云', value: 'qiniu' },
        { label: '又拍云', value: 'upyun' },
        { label: 'AWS S3', value: 's3' },
      ],
    },
  },
  // 本地存储配置
  {
    field: 'local_path',
    label: '存储路径',
    component: 'Input',
    required: true,
    show: ({ values }) => values.driver === 'local',
    helpMessage: '相对于项目根目录的路径',
  },
  {
    field: 'local_domain',
    label: '访问域名',
    component: 'Input',
    required: true,
    show: ({ values }) => values.driver === 'local',
    helpMessage: '文件访问的完整域名',
  },
  // 阿里云OSS配置
  {
    field: 'oss_access_key_id',
    label: 'AccessKey ID',
    component: 'Input',
    required: true,
    show: ({ values }) => values.driver === 'oss',
  },
  {
    field: 'oss_access_key_secret',
    label: 'AccessKey Secret',
    component: 'InputPassword',
    required: true,
    show: ({ values }) => values.driver === 'oss',
  },
  {
    field: 'oss_bucket',
    label: 'Bucket名称',
    component: 'Input',
    required: true,
    show: ({ values }) => values.driver === 'oss',
  },
  {
    field: 'oss_region',
    label: '地域节点',
    component: 'Select',
    required: true,
    show: ({ values }) => values.driver === 'oss',
    componentProps: {
      options: [
        { label: '华东1（杭州）', value: 'oss-cn-hangzhou' },
        { label: '华东2（上海）', value: 'oss-cn-shanghai' },
        { label: '华北1（青岛）', value: 'oss-cn-qingdao' },
        { label: '华北2（北京）', value: 'oss-cn-beijing' },
        { label: '华南1（深圳）', value: 'oss-cn-shenzhen' },
      ],
    },
  },
  {
    field: 'oss_domain',
    label: '自定义域名',
    component: 'Input',
    show: ({ values }) => values.driver === 'oss',
    helpMessage: '不填写则使用默认域名',
  },
  {
    field: 'oss_is_private',
    label: '是否私有',
    component: 'Switch',
    show: ({ values }) => values.driver === 'oss',
    defaultValue: false,
  },
  // 腾讯云COS配置
  {
    field: 'cos_secret_id',
    label: 'SecretId',
    component: 'Input',
    required: true,
    show: ({ values }) => values.driver === 'cos',
  },
  {
    field: 'cos_secret_key',
    label: 'SecretKey',
    component: 'InputPassword',
    required: true,
    show: ({ values }) => values.driver === 'cos',
  },
  {
    field: 'cos_bucket',
    label: 'Bucket名称',
    component: 'Input',
    required: true,
    show: ({ values }) => values.driver === 'cos',
  },
  {
    field: 'cos_region',
    label: '地域',
    component: 'Select',
    required: true,
    show: ({ values }) => values.driver === 'cos',
    componentProps: {
      options: [
        { label: '北京', value: 'ap-beijing' },
        { label: '上海', value: 'ap-shanghai' },
        { label: '广州', value: 'ap-guangzhou' },
        { label: '成都', value: 'ap-chengdu' },
        { label: '重庆', value: 'ap-chongqing' },
      ],
    },
  },
  // 七牛云配置
  {
    field: 'qiniu_access_key',
    label: 'AccessKey',
    component: 'Input',
    required: true,
    show: ({ values }) => values.driver === 'qiniu',
  },
  {
    field: 'qiniu_secret_key',
    label: 'SecretKey',
    component: 'InputPassword',
    required: true,
    show: ({ values }) => values.driver === 'qiniu',
  },
  {
    field: 'qiniu_bucket',
    label: '存储空间',
    component: 'Input',
    required: true,
    show: ({ values }) => values.driver === 'qiniu',
  },
  {
    field: 'qiniu_domain',
    label: '访问域名',
    component: 'Input',
    required: true,
    show: ({ values }) => values.driver === 'qiniu',
  },
  // 上传限制
  {
    field: 'max_size',
    label: '最大文件大小（MB）',
    component: 'InputNumber',
    required: true,
    defaultValue: 10,
    componentProps: {
      min: 1,
      max: 1024,
    },
  },
  {
    field: 'allowed_types',
    label: '允许的文件类型',
    component: 'Select',
    required: true,
    componentProps: {
      mode: 'multiple',
      options: [
        { label: '图片 (jpg, jpeg, png, gif, webp)', value: 'image' },
        { label: '文档 (pdf, doc, docx, xls, xlsx, ppt, pptx)', value: 'document' },
        { label: '视频 (mp4, avi, mov, wmv, flv)', value: 'video' },
        { label: '音频 (mp3, wav, flac, aac)', value: 'audio' },
        { label: '压缩包 (zip, rar, 7z, tar, gz)', value: 'archive' },
      ],
    },
  },
  // 图片处理
  {
    field: 'thumbnail_enabled',
    label: '自动生成缩略图',
    component: 'Switch',
    defaultValue: true,
  },
  {
    field: 'thumbnail_width',
    label: '缩略图宽度',
    component: 'InputNumber',
    show: ({ values }) => values.thumbnail_enabled,
    defaultValue: 200,
    componentProps: {
      min: 50,
      max: 1000,
    },
  },
  {
    field: 'thumbnail_height',
    label: '缩略图高度',
    component: 'InputNumber',
    show: ({ values }) => values.thumbnail_enabled,
    defaultValue: 200,
    componentProps: {
      min: 50,
      max: 1000,
    },
  },
  // 其他设置
  {
    field: 'enabled',
    label: '启用状态',
    component: 'Switch',
    defaultValue: true,
  },
  {
    field: 'is_default',
    label: '默认存储',
    component: 'Switch',
    defaultValue: false,
    helpMessage: '设为默认存储驱动',
  },
]

// 工具函数
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(2) + ' MB'
  }
}

// 加载配置
const loadConfig = async () => {
  try {
    const data = await getStorageConfigApi()
    formRef.value?.setFieldsValue(data)
  } catch (error) {
    message.error('加载配置失败')
  }
}

// 保存配置
const handleSave = async () => {
  try {
    const values = await formRef.value?.validate()
    if (!values) return

    saveLoading.value = true
    await updateStorageConfigApi(values as StorageConfig)
    message.success('保存成功')
  } catch (error) {
    message.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 测试上传
const handleTest = () => {
  testFile.value = null
  testFileList.value = []
  testDialogVisible.value = true
}

// 文件变化处理
const handleFileChange = (fileList: any[]) => {
  if (fileList.length > 0) {
    testFile.value = fileList[0].originFileObj || fileList[0]
  } else {
    testFile.value = null
  }
}

// 上传测试
const handleUploadTest = async () => {
  if (!testFile.value) {
    message.warning('请选择要上传的文件')
    return
  }

  try {
    const formData = new FormData()
    formData.append('file', testFile.value)

    const result = await testStorageApi(formData)
    message.success(`上传测试成功！文件URL: ${result.url}`)
    testDialogVisible.value = false
  } catch (error) {
    message.error('上传测试失败')
  }
}

// 重置配置
const handleReset = async () => {
  try {
    await resetStorageConfigApi()
    message.success('重置成功')
    await loadConfig()
  } catch (error) {
    message.error('重置失败')
  }
}

onMounted(() => {
  loadConfig()
})
</script>

<style scoped>
.p-4 {
  padding: 16px;
}

.flex {
  display: flex;
}

.gap-2 {
  gap: 8px;
}

.upload-test-container {
  padding: 16px;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background: #fafafa;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #1890ff;
}

.upload-icon {
  margin-bottom: 16px;
  color: #999;
}

.upload-text {
  margin-bottom: 8px;
  color: #666;
}

.upload-text em {
  color: #1890ff;
  font-style: normal;
}

.upload-tip {
  color: #999;
  font-size: 12px;
}

.test-file-info {
  margin-top: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.test-file-info h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.test-file-info p {
  margin: 5px 0;
  color: #606266;
}
</style>