<template>
  <div class="p-2">
    <el-card shadow="hover">
      <!-- 存储设置提示信息 -->
      <div class="storage-notice">
        <div class="notice-content">
          <p>1. 上线后更换请慎重！存储在哪一方迁移都是很费时间的；2. 将public下面的static中的文件全部上传到存储空间；</p>
          <p>3. 本地存储需要将图片域名绑定到public/upload目录，否则无法上传</p>
        </div>
      </div>

      <!-- 配置表单内容 -->
      <div class="config-content">
        <el-form
          ref="configFormRef"
          :model="currentConfig"
          :rules="configRules"
          :validate-on-rule-change="false"
          label-width="180px"
          class="config-form"
        >
          <!-- 存储设置选择 -->
          <el-form-item label="存储设置:" prop="storageType">
            <el-radio-group v-model="currentConfig.storageType" @change="handleStorageTypeChange">
              <el-radio value="local">本地存储</el-radio>
              <el-radio value="qiniu">七牛云</el-radio>
              <el-radio value="aliyun">阿里云</el-radio>
              <el-radio value="tencent">腾讯云</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 存储域名配置 -->
          <el-form-item label="存储域名:" prop="domain">
            <el-input 
              v-model="currentConfig.domain" 
              :placeholder="getStoragePlaceholder()" 
            />
          </el-form-item>

          <!-- 云存储配置（根据存储类型显示不同字段） -->
          <template v-if="currentConfig.storageType !== 'local'">
            <!-- 七牛云：存储域名、accessKey、secretKey、桶名称 -->
            <template v-if="currentConfig.storageType === 'qiniu'">
              <el-form-item label="accessKey:" prop="accessKey">
                <el-input v-model="currentConfig.accessKey" placeholder="请输入accessKey" />
              </el-form-item>

              <el-form-item label="secretKey:" prop="secretKey">
                <el-input v-model="currentConfig.secretKey" type="password" placeholder="请输入secretKey" show-password />
              </el-form-item>

              <el-form-item label="桶名称:" prop="bucketName">
                <el-input v-model="currentConfig.bucketName" placeholder="请输入桶名称" />
              </el-form-item>
            </template>

            <!-- 阿里云：存储域名、accessKey、secretKey、桶名称、访问站点 -->
            <template v-else-if="currentConfig.storageType === 'aliyun'">
              <el-form-item label="accessKey:" prop="accessKey">
                <el-input v-model="currentConfig.accessKey" placeholder="请输入accessKey" />
              </el-form-item>

              <el-form-item label="secretKey:" prop="secretKey">
                <el-input v-model="currentConfig.secretKey" type="password" placeholder="请输入secretKey" show-password />
              </el-form-item>

              <el-form-item label="桶名称:" prop="bucketName">
                <el-input v-model="currentConfig.bucketName" placeholder="请输入桶名称" />
              </el-form-item>

              <el-form-item label="访问站点:" prop="endpoint">
                <el-input v-model="currentConfig.endpoint" placeholder="请输入访问站点" />
              </el-form-item>
            </template>

            <!-- 腾讯云：存储域名、accessKey、secretKey、桶名称、前缀、访问站点 -->
            <template v-else-if="currentConfig.storageType === 'tencent'">
              <el-form-item label="accessKey:" prop="accessKey">
                <el-input v-model="currentConfig.accessKey" placeholder="请输入accessKey" />
              </el-form-item>

              <el-form-item label="secretKey:" prop="secretKey">
                <el-input v-model="currentConfig.secretKey" type="password" placeholder="请输入secretKey" show-password />
              </el-form-item>

              <el-form-item label="桶名称:" prop="bucketName">
                <el-input v-model="currentConfig.bucketName" placeholder="请输入桶名称" />
              </el-form-item>

              <el-form-item label="前缀:" prop="prefix">
                <el-input v-model="currentConfig.prefix" placeholder="请输入前缀" />
              </el-form-item>

              <el-form-item label="访问站点:" prop="endpoint">
                <el-input v-model="currentConfig.endpoint" placeholder="请输入访问站点" />
              </el-form-item>
            </template>
          </template>

          <!-- 操作按钮 -->
          <el-form-item>
            <el-button type="primary" :loading="buttonLoading" @click="handleSave">
              保存
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup name="OssConfig" lang="ts">
import { listOssConfig, getOssConfig, updateOssConfig, addOssConfig } from '@/api/system/ossConfig';
import { OssConfigVO } from '@/api/system/ossConfig/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const buttonLoading = ref(false);
const configFormRef = ref<ElFormInstance>();

// 统一的配置数据
const currentConfig = ref({
  storageType: 'local',
  domain: 'https://img.tpidea.cn',
  configKey: '',
  accessKey: '',
  secretKey: '',
  bucketName: '',
  prefix: '',
  endpoint: '',
  isHttps: 'N',
  region: '',
  accessPolicy: '1',
  status: '1',
  remark: ''
});

// 表单验证规则
const configRules = computed(() => {
  const baseRules = {
    storageType: [{ required: true, message: '存储类型不能为空', trigger: 'change' }],
    domain: [{ required: true, message: '存储域名不能为空', trigger: 'blur' }]
  };

  // 根据存储类型添加不同的验证规则
  if (currentConfig.value.storageType !== 'local') {
    // 所有云存储都需要的基础字段
    Object.assign(baseRules, {
      accessKey: [{ required: true, message: 'accessKey不能为空', trigger: 'blur' }],
      secretKey: [{ required: true, message: 'secretKey不能为空', trigger: 'blur' }],
      bucketName: [{ required: true, message: '桶名称不能为空', trigger: 'blur' }]
    });

    // 阿里云和腾讯云需要访问站点
    if (currentConfig.value.storageType === 'aliyun' || currentConfig.value.storageType === 'tencent') {
      Object.assign(baseRules, {
        endpoint: [{ required: true, message: '访问站点不能为空', trigger: 'blur' }]
      });
    }
  }

  return baseRules;
});

/** 存储类型切换 */
const handleStorageTypeChange = (storageType: string) => {
  // 设置configKey
  currentConfig.value.configKey = storageType;
  
  // 加载对应的配置
  if (storageType !== 'local') {
    loadConfigByKey(storageType);
  }
};

/** 获取存储域名占位符 */
const getStoragePlaceholder = () => {
  const placeholders = {
    local: '格式:https://img.tpidea.cn',
    qiniu: '格式:https://img.tpidea.cn',
    aliyun: '格式:https://img.tpidea.cn',
    tencent: '格式:https://img.tpidea.cn'
  };
  return placeholders[currentConfig.value.storageType as keyof typeof placeholders] || '请输入存储域名';
};

/** 根据configKey加载配置数据 */
const loadConfigByKey = async (configKey: string) => {
  try {
    const res = await listOssConfig({ 
      configKey, 
      bucketName: '', 
      status: '', 
      pageNum: 1, 
      pageSize: 1 
    });
    if (res.rows && res.rows.length > 0) {
      const config = res.rows[0];
      // 将数据库中的配置回显到表单
      Object.assign(currentConfig.value, {
        configKey: config.configKey,
        accessKey: config.accessKey,
        secretKey: config.secretKey,
        bucketName: config.bucketName,
        prefix: config.prefix,
        endpoint: config.endpoint,
        domain: config.domain,
        isHttps: config.isHttps,
        region: config.region,
        accessPolicy: config.accessPolicy,
        status: config.status,
        remark: config.remark
      });
    }
  } catch (error) {
    console.error('加载配置失败:', error);
  }
};

/** 保存配置 */
const handleSave = async () => {
  try {
    await configFormRef.value?.validate();
    buttonLoading.value = true;

    const config = currentConfig.value;

    if (config.storageType === 'local') {
      // 本地存储只保存域名配置
      proxy?.$modal.msgSuccess('本地存储配置保存成功');
    } else {
      // 云存储配置
      // 检查是否已存在配置
      const existingRes = await listOssConfig({ 
        configKey: config.configKey, 
        bucketName: '', 
        status: '', 
        pageNum: 1, 
        pageSize: 1 
      });

      // 根据存储类型准备配置数据
      const configData = {
        ossConfigId: existingRes.rows && existingRes.rows.length > 0 ? existingRes.rows[0].ossConfigId : undefined,
        configKey: config.configKey,
        accessKey: config.accessKey,
        secretKey: config.secretKey,
        bucketName: config.bucketName,
        domain: config.domain
      };

      // 阿里云和腾讯云需要访问站点
      if (config.storageType === 'aliyun' || config.storageType === 'tencent') {
        Object.assign(configData, {
          endpoint: config.endpoint
        });
      }

      // 腾讯云需要前缀
      if (config.storageType === 'tencent') {
        Object.assign(configData, {
          prefix: config.prefix
        });
      }

      if (existingRes.rows && existingRes.rows.length > 0) {
        // 更新现有配置
        await updateOssConfig(configData);
        proxy?.$modal.msgSuccess('配置更新成功');
      } else {
        // 新增配置
        await addOssConfig(configData);
        proxy?.$modal.msgSuccess('配置保存成功');
      }
    }
  } catch (error) {
    console.error('保存配置失败:', error);
    proxy?.$modal.msgError('保存配置失败');
  } finally {
    buttonLoading.value = false;
  }
};

/** 重置配置 */
const handleReset = () => {
  configFormRef.value?.resetFields();
  // 重新加载配置
  if (currentConfig.value.storageType !== 'local') {
    loadConfigByKey(currentConfig.value.storageType);
  }
};

/** 初始化加载配置 */
const initConfig = async () => {
  // 可以根据需要加载默认配置或当前激活的配置
  if (currentConfig.value.storageType !== 'local') {
    await loadConfigByKey(currentConfig.value.storageType);
    // 填充完回显数据后，清除一次校验提示
    nextTick(() => {
      configFormRef.value?.clearValidate?.();
    });
  }
};

onMounted(() => {
  // 初始化时加载配置数据
  initConfig();
});
</script>

<style scoped>
.storage-notice {
  background-color: #ecf5ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 20px;
}

.notice-content p {
  margin: 0;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.notice-content p:last-child {
  margin-bottom: 0;
}

.config-content {
  padding: 20px 0;
}

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

.config-form .el-form-item {
  margin-bottom: 24px;
}

.config-form .el-form-item__label {
  font-weight: 500;
  color: #303133;
}

.config-form .el-input,
.config-form .el-select,
.config-form .el-input-number {
  width: 100%;
}

.config-form .el-textarea {
  width: 100%;
}

.config-form .el-radio-group {
  display: flex;
  align-items: center;
}

.config-form .el-radio {
  margin-right: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .config-form {
    max-width: 100%;
  }

  .config-form .el-form-item__label {
    width: 100% !important;
    text-align: left !important;
  }

  .config-form .el-radio {
    margin-right: 12px;
    margin-bottom: 8px;
  }
}
</style>
