<template>
  <div class="page-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>上传配置</span>
          <el-button type="primary" :loading="saving" @click="handleSave">
            <el-icon><Check /></el-icon>保存配置
          </el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="140px"
        class="config-form"
      >
        <!-- 存储类型选择 -->
        <el-divider content-position="left">存储类型</el-divider>
        
        <el-form-item label="存储方式" prop="type">
          <el-radio-group v-model="formData.type" @change="handleTypeChange">
            <el-radio :value="StorageType.Local">
              <el-icon><FolderOpened /></el-icon>
              本地存储
            </el-radio>
            <el-radio :value="StorageType.Aliyun">
              <el-icon><Cloudy /></el-icon>
              阿里云OSS
            </el-radio>
            <el-radio :value="StorageType.Tencent">
              <el-icon><Cloudy /></el-icon>
              腾讯云COS
            </el-radio>
          </el-radio-group>
          <div class="form-tip">
            <template v-if="formData.type === StorageType.Local">
              文件将存储在服务器本地目录
            </template>
            <template v-else-if="formData.type === StorageType.Aliyun">
              文件将上传至阿里云对象存储服务(OSS)
            </template>
            <template v-else-if="formData.type === StorageType.Tencent">
              文件将上传至腾讯云对象存储服务(COS)
            </template>
          </div>
        </el-form-item>

        <!-- 云存储配置（仅在选择云存储时显示） -->
        <template v-if="isCloudStorage">
          <el-divider content-position="left">
            {{ formData.type === StorageType.Aliyun ? '阿里云OSS配置' : '腾讯云COS配置' }}
          </el-divider>

          <!-- 腾讯云COS需要AppId -->
          <el-row v-if="formData.type === StorageType.Tencent" :gutter="24">
            <el-col :span="12">
              <el-form-item label="AppId" prop="AppId">
                <el-input 
                  v-model="formData.AppId" 
                  placeholder="请输入腾讯云AppId"
                  clearable
                />
                <div class="form-tip">
                  腾讯云账号的AppId，可在控制台账号信息中查看
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="空间名称(Bucket)" prop="Bucket">
                <el-input 
                  v-model="formData.Bucket" 
                  placeholder="请输入Bucket名称"
                  clearable
                />
                <div class="form-tip">
                  {{ formData.type === StorageType.Aliyun ? '阿里云OSS的Bucket名称' : '腾讯云COS的Bucket名称' }}
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地域(Region)" prop="Region">
                <el-input 
                  v-model="formData.Region" 
                  placeholder="请输入地域"
                  clearable
                />
                <div class="form-tip">
                  <template v-if="formData.type === StorageType.Aliyun">
                    例如: oss-cn-hangzhou、oss-cn-shanghai
                  </template>
                  <template v-else>
                    例如: ap-guangzhou、ap-shanghai
                  </template>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="AccessKeyId" prop="AccessKeyId">
                <el-input 
                  v-model="formData.AccessKeyId" 
                  placeholder="请输入AccessKeyId"
                  clearable
                />
                <div class="form-tip">
                  {{ formData.type === StorageType.Aliyun ? '阿里云AccessKey ID' : '腾讯云SecretId' }}
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="AccessKeySecret" prop="AccessKeySecret">
                <el-input 
                  v-model="formData.AccessKeySecret" 
                  placeholder="请输入AccessKeySecret"
                  type="password"
                  show-password
                  clearable
                />
                <div class="form-tip">
                  {{ formData.type === StorageType.Aliyun ? '阿里云AccessKey Secret' : '腾讯云SecretKey' }}
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="请求域名" prop="Domain">
                <el-input 
                  v-model="formData.Domain" 
                  placeholder="请输入请求域名"
                  clearable
                />
                <div class="form-tip">
                  用于访问文件的域名，例如: https://your-bucket.oss-cn-hangzhou.aliyuncs.com
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <!-- 本地存储提示 -->
        <template v-else>
          <el-divider content-position="left">本地存储说明</el-divider>
          
          <el-alert
            title="本地存储模式"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <p>使用本地存储时，文件将保存在服务器的本地目录中。</p>
              <p>优点：配置简单，无需额外费用</p>
              <p>缺点：不支持CDN加速，服务器迁移时需要同步文件</p>
            </template>
          </el-alert>
        </template>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Check, FolderOpened, Cloudy } from '@element-plus/icons-vue'
import { 
  getUploadSetting, 
  updateUploadSetting, 
  StorageType,
  type UploadSetting 
} from '@/api/business/config'

// 加载状态
const loading = ref(false)
const saving = ref(false)

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
interface FormDataType {
  type: string
  AppId: string
  Bucket: string
  Region: string
  AccessKeyId: string
  AccessKeySecret: string
  Domain: string
}

const formData = reactive<FormDataType>({
  type: StorageType.Local,
  AppId: '',
  Bucket: '',
  Region: '',
  AccessKeyId: '',
  AccessKeySecret: '',
  Domain: ''
})

// 是否为云存储
const isCloudStorage = computed(() => {
  return formData.type === StorageType.Aliyun || formData.type === StorageType.Tencent
})

// 云存储字段验证器
const cloudFieldValidator = (rule: any, value: string, callback: any) => {
  if (isCloudStorage.value && !value) {
    callback(new Error(rule.message))
  } else {
    callback()
  }
}

// 表单验证规则
const formRules: FormRules = {
  type: [
    { required: true, message: '请选择存储方式', trigger: 'change' }
  ],
  Bucket: [
    { validator: cloudFieldValidator, message: '请输入空间名称', trigger: 'blur' }
  ],
  Region: [
    { validator: cloudFieldValidator, message: '请输入地域', trigger: 'blur' }
  ],
  AccessKeyId: [
    { validator: cloudFieldValidator, message: '请输入AccessKeyId', trigger: 'blur' }
  ],
  AccessKeySecret: [
    { validator: cloudFieldValidator, message: '请输入AccessKeySecret', trigger: 'blur' }
  ],
  Domain: [
    { validator: cloudFieldValidator, message: '请输入请求域名', trigger: 'blur' }
  ]
}

// 存储类型变更处理
const handleTypeChange = () => {
  // 切换到本地存储时，清空云存储配置
  if (formData.type === StorageType.Local) {
    formData.AppId = ''
    formData.Bucket = ''
    formData.Region = ''
    formData.AccessKeyId = ''
    formData.AccessKeySecret = ''
    formData.Domain = ''
  }
  // 清除验证状态
  formRef.value?.clearValidate()
}

// 加载配置数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getUploadSetting()
    if (res.data?.value) {
      const data = res.data.value
      Object.assign(formData, {
        type: data.type || StorageType.Local,
        AppId: data.AppId || '',
        Bucket: data.Bucket || '',
        Region: data.Region || '',
        AccessKeyId: data.AccessKeyId || '',
        AccessKeySecret: data.AccessKeySecret || '',
        Domain: data.Domain || ''
      })
    }
  } catch (error) {
    ElMessage.error('加载配置失败')
    console.error('加载配置失败:', error)
  } finally {
    loading.value = false
  }
}

// 保存配置
const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
  } catch {
    ElMessage.warning('请检查表单填写是否正确')
    return
  }

  saving.value = true
  try {
    const submitData: UploadSetting = {
      type: formData.type
    }

    // 仅在云存储模式下提交云存储配置
    if (isCloudStorage.value) {
      if (formData.type === StorageType.Tencent) {
        submitData.AppId = formData.AppId
      }
      submitData.Bucket = formData.Bucket
      submitData.Region = formData.Region
      submitData.AccessKeyId = formData.AccessKeyId
      submitData.AccessKeySecret = formData.AccessKeySecret
      submitData.Domain = formData.Domain
    }

    await updateUploadSetting(submitData)
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
    console.error('保存配置失败:', error)
  } finally {
    saving.value = false
  }
}

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

<style scoped>
.page-container {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.config-form {
  max-width: 1000px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
}

:deep(.el-divider__text) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-radio) {
  margin-right: 30px;
}

:deep(.el-radio .el-icon) {
  margin-right: 4px;
  vertical-align: middle;
}

:deep(.el-alert) {
  margin-bottom: 20px;
}

:deep(.el-alert p) {
  margin: 4px 0;
  line-height: 1.6;
}
</style>
