<template>
  <div class="oss-config-setting">
    <!-- 顶部业务提醒 -->
    <div class="setting-hint">
      <el-alert :closable="false" type="info" class="custom-alert">
        <template #title>
          <div class="alert-content">
            <p>1. 上线后更换请慎重！存储在哪一方迁移都是很费时间的；</p>
            <p>2. 将 public 下面的 static 中的文件全部上传到存储空间；</p>
            <p>3. 本地存储需要将图片域名绑定到 public/upload 目录，否则无法上传。</p>
          </div>
        </template>
      </el-alert>
    </div>

    <!-- 存储配置表单 -->
    <div class="setting-body">
      <el-form ref="ossFormRef" :model="form" :rules="rules" label-width="140px" class="premium-setting-form">
        
        <!-- 存储设置选择 -->
        <el-form-item label="存储设置：">
          <el-radio-group v-model="form.configKey" @change="handleTypeChange" class="custom-radio-group">
            <el-radio label="local" border>本地存储</el-radio>
            <el-radio label="qiniu" border>七牛云</el-radio>
            <el-radio label="aliyun" border>阿里云</el-radio>
            <el-radio label="tencent" border>腾讯云</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 通用字段：存储域名 -->
        <el-form-item label="存储域名：" prop="domain">
          <el-input v-model="form.domain" placeholder="格式 https://img.tpidea.cn" class="config-input">
            <template #prefix>
              <span class="protocol-prefix">{{ protocol }}</span>
            </template>
          </el-input>
          <div class="form-tip" v-if="form.configKey === 'local'">对应服务器 public/upload 目录绑定的域名</div>
        </el-form-item>

        <!-- 云端特有字段 -->
        <template v-if="form.configKey !== 'local'">
          <el-form-item label="AccessKey：" prop="accessKey">
            <el-input v-model="form.accessKey" placeholder="请输入云端存储 AccessKey" class="config-input" />
          </el-form-item>

          <el-form-item label="SecretKey：" prop="secretKey">
            <el-input v-model="form.secretKey" type="password" show-password placeholder="请输入云端存储 SecretKey" class="config-input" />
          </el-form-item>

          <el-form-item label="桶名称：" prop="bucketName">
            <el-input v-model="form.bucketName" placeholder="请输入存储桶（Bucket）名称" class="config-input" />
          </el-form-item>

          <el-form-item label="存储区域：" prop="region">
            <el-input v-model="form.region" placeholder="如：cn-hangzhou, oss-cn-beijing" class="config-input" />
          </el-form-item>

          <el-form-item label="访问站点：" prop="endpoint">
            <el-input v-model="form.endpoint" placeholder="请输入访问域名或站点 Endpoint" class="config-input" />
          </el-form-item>
        </template>

        <!-- 其他配置 -->
        <el-form-item label="前缀路径：" prop="prefix">
          <el-input v-model="form.prefix" placeholder="如：upload, static" class="config-input" />
          <div class="form-tip">选填，存储文件时的路径前缀</div>
        </el-form-item>

        <el-form-item label="HTTPS 访问：" v-if="form.configKey !== 'local'">
          <el-switch v-model="form.isHttps" active-value="Y" inactive-value="N" active-text="开启" inactive-text="关闭" />
        </el-form-item>

        <!-- 保存操作 -->
        <el-form-item class="action-item">
          <el-button type="primary" class="save-btn" :loading="buttonLoading" @click="submitForm">保存设置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

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

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

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

const form = ref<OssConfigForm>({
  ossConfigId: undefined,
  configKey: 'local',
  accessKey: '',
  secretKey: '',
  bucketName: '',
  prefix: '',
  endpoint: '',
  domain: '',
  isHttps: 'N',
  accessPolicy: '1',
  region: '',
  status: '0', // 默认设为启用/默认状态
  remark: ''
});

const rules = {
  domain: [{ required: true, message: "存储域名不能为空", trigger: "blur" }],
  accessKey: [{ required: true, message: "AccessKey 不能为空", trigger: "blur" }],
  secretKey: [{ required: true, message: "SecretKey 不能为空", trigger: "blur" }],
  bucketName: [{ required: true, message: "桶名称不能为空", trigger: "blur" }],
  endpoint: [{ required: true, message: "访问站点不能为空", trigger: "blur" }],
};

const protocol = computed(() => (form.value.isHttps === 'Y' ? 'https://' : 'http://'));

/** 加载对应类型的配置 */
const loadTypeConfig = async (configKey: string) => {
  const res = await listOssConfig({ configKey } as any);
  if (res.rows && res.rows.length > 0) {
    Object.assign(form.value, res.rows[0]);
  } else {
    // 重置表单（保留当前 key）
    const currentKey = form.value.configKey;
    form.value = {
      ossConfigId: undefined,
      configKey: currentKey,
      accessKey: '',
      secretKey: '',
      bucketName: '',
      prefix: '',
      endpoint: '',
      domain: '',
      isHttps: 'N',
      accessPolicy: '1',
      region: '',
      status: '0',
      remark: ''
    };
  }
};

/** 切换存储类型 */
const handleTypeChange = (val: any) => {
  loadTypeConfig(val);
};

/** 提交表单 */
const submitForm = () => {
  ossFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 保存并强制设为默认状态
        form.value.status = '0';
        if (form.value.ossConfigId) {
          await updateOssConfig(form.value);
        } else {
          await addOssConfig(form.value);
        }
        proxy?.$modal.msgSuccess("存储配置已保存并激活");
        await loadTypeConfig(form.value.configKey);
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 初始化：加载已激活的配置项 */
const initOssConfig = async () => {
  const res = await listOssConfig({} as any);
  if (res.rows && res.rows.length > 0) {
    const activeItem = res.rows.find((item: any) => item.status === '0');
    if (activeItem) {
      form.value.configKey = activeItem.configKey;
      Object.assign(form.value, activeItem);
    } else {
      loadTypeConfig('local');
    }
  } else {
    loadTypeConfig('local');
  }
};

onMounted(() => {
  initOssConfig();
});
</script>

<style scoped lang="scss">
.oss-config-setting {
  padding: 8px 0;
}

.setting-hint {
  margin-bottom: 32px;
  
  .custom-alert {
    background-color: #f0faff;
    border: 1px solid #c2eaff;
    border-radius: 8px;
    padding: 12px 16px;

    .alert-content {
      color: #0089ff;
      font-size: 14px;
      line-height: 1.8;
      
      p {
        margin: 0;
      }
    }
  }
}

.setting-body {
  padding-left: 20px;
}

.premium-setting-form {
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #4e5969;
    padding-right: 24px;
  }

  .config-input {
    max-width: 520px;
    
    .protocol-prefix {
      color: #909399;
      font-size: 13px;
    }

    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px #e5e6eb inset;
      padding: 4px 12px;
      border-radius: 6px;
      
      &:hover {
        box-shadow: 0 0 0 1px #409eff inset;
      }
      
      &.is-focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
  }

  .form-tip {
    font-size: 13px;
    color: #86909c;
    margin-top: 8px;
    line-height: 1.4;
  }

  .custom-radio-group {
    :deep(.el-radio) {
      margin-right: 16px;
      border-radius: 6px;
      padding: 0 20px;
      height: 36px;
      
      &.is-bordered.is-checked {
        border-color: #409eff;
        background-color: rgba(64, 158, 255, 0.04);
      }
      
      .el-radio__label {
        font-size: 14px;
      }
    }
  }

  .action-item {
    margin-top: 40px;
  }

  .save-btn {
    padding: 12px 32px;
    height: auto;
    font-size: 15px;
    font-weight: 500;
    border-radius: 6px;
    box-shadow: 0 4px 10px rgba(64, 158, 255, 0.2);
  }
}
</style>
