<template>
  <div class="oss-config-page">
    <div class="setting-hint">
      <el-alert :closable="false" type="info" class="custom-alert">
        <template #title>
          <div class="alert-content">
            <span>上线后更换请慎重，迁移存储耗时较长；本地存储需将图片域名绑定到 public/upload 目录。</span>
          </div>
        </template>
      </el-alert>
    </div>

    <div class="setting-body">
      <el-card shadow="never" class="setting-card">
        <template #header>
          <div class="setting-card-header">
            <span class="setting-card-title">存储配置</span>
          </div>
        </template>

        <el-form ref="ossFormRef" :model="form" :rules="rules" label-width="110px" class="premium-form">
          <el-form-item label="存储服务">
            <el-radio-group v-model="form.configKey" @change="handleTypeChange" class="storage-radio-group">
              <el-radio value="local" border>本地存储</el-radio>
              <el-radio value="minio" border>Minio</el-radio>
              <el-radio value="qiniu" border>七牛云</el-radio>
              <el-radio value="aliyun" border>阿里云</el-radio>
              <el-radio value="qcloud" border>腾讯云</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="访问站点" prop="endpoint">
                <el-input v-model="form.endpoint" placeholder="请输入访问站点" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="自定义域名" prop="domain">
                <el-input v-model="form.domain" placeholder="请输入自定义域名">
                  <template #prefix>
                    <span class="protocol-prefix">{{ protocol }}</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="AccessKey" prop="accessKey">
                <el-input v-model="form.accessKey" placeholder="请输入 AccessKey" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="SecretKey" prop="secretKey">
                <el-input v-model="form.secretKey" placeholder="请输入 SecretKey" show-password />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="桶名称" prop="bucketName">
                <el-input v-model="form.bucketName" placeholder="请输入存储桶名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="前缀路径" prop="prefix">
                <el-input v-model="form.prefix" placeholder="选填，如 upload、static" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="存储区域" prop="region">
                <el-input v-model="form.region" placeholder="如 cn-hangzhou" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="HTTPS 访问">
                <el-switch v-model="form.isHttps" active-value="Y" inactive-value="N" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="桶权限">
                <el-radio-group v-model="form.accessPolicy">
                  <el-radio value="0">private</el-radio>
                  <el-radio value="1">public</el-radio>
                  <el-radio value="2">custom</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注内容" :rows="2" />
          </el-form-item>

          <el-form-item class="action-item">
            <el-button type="primary" class="save-btn" icon="Check" :loading="buttonLoading"
              @click="submitForm">保存配置</el-button>
            <el-button icon="Refresh" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </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 initFormData: OssConfigForm = {
  ossConfigId: undefined,
  configKey: 'local',
  accessKey: '',
  secretKey: '',
  bucketName: '',
  prefix: '',
  endpoint: '',
  domain: '',
  isHttps: 'N',
  accessPolicy: '1',
  region: '',
  status: '0',
  remark: ''
};

const form = ref<OssConfigForm>({ ...initFormData });

const rules = {
  endpoint: [{ required: true, message: '访问站点不能为空', trigger: 'blur' }],
  domain: [{ required: true, message: '自定义域名不能为空', trigger: 'blur' }],
  accessKey: [
    { required: true, message: 'AccessKey 不能为空', trigger: 'blur' },
    { min: 2, max: 200, message: '长度必须介于 2 和 200 之间', trigger: 'blur' }
  ],
  secretKey: [
    { required: true, message: 'SecretKey 不能为空', trigger: 'blur' },
    { min: 2, max: 100, message: '长度必须介于 2 和 100 之间', trigger: 'blur' }
  ],
  bucketName: [
    { required: true, message: '桶名称不能为空', trigger: 'blur' },
    { min: 2, max: 100, message: '长度必须介于 2 和 100 之间', trigger: 'blur' }
  ]
};

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

function loadTypeConfig(configKey: string) {
  listOssConfig({ configKey } as any).then(res => {
    if (res.rows && res.rows.length > 0) {
      Object.assign(form.value, res.rows[0]);
      form.value.status = '0';
    } else {
      form.value = { ...initFormData, configKey };
    }
  });
}

function handleTypeChange(val: string) {
  loadTypeConfig(val);
}

function resetForm() {
  form.value = { ...initFormData };
  ossFormRef.value?.resetFields();
  loadTypeConfig('local');
}

function 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;
      }
    }
  });
}

function initOssConfig() {
  listOssConfig({} as any).then(res => {
    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 lang="scss" scoped>
.oss-config-page {
  padding: 16px;
  min-height: calc(100vh - 100px);
  background: #f5f7fa;
}

.setting-hint {
  margin-bottom: 16px;

  .custom-alert {
    background: #f0faff;
    border: 1px solid #c2eaff;
    border-radius: 8px;

    .alert-content {
      color: #0089ff;
      font-size: 13px;
      line-height: 1.6;
    }
  }
}

.setting-body {
  .setting-card {
    border-radius: 8px;
    border: 1px solid #edf0f5;
    background: #fff;

    .setting-card-header {
      .setting-card-title {
        font-size: 15px;
        font-weight: 600;
        color: #1a1a2e;
      }
    }
  }
}

.premium-form {
  max-width: 920px;

  .storage-radio-group {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    :deep(.el-radio) {
      margin-right: 0;
      border-radius: 6px;
      padding: 7px 18px;
      height: auto;
      border-color: #e5e6eb;
      transition: all 0.2s ease;

      &:hover {
        border-color: #409eff;
      }

      &.is-checked {
        border-color: #409eff;
        background: rgba(64, 158, 255, 0.04);
      }

      .el-radio__label {
        font-size: 13px;
      }
    }
  }

  .protocol-prefix {
    color: #bfc0c4;
    font-size: 13px;
  }

  .action-item {
    margin-top: 4px;
    padding-top: 16px;
    border-top: 1px solid #f0f2f5;
  }

  .save-btn {
    padding: 8px 28px;
    border-radius: 6px;
  }
}
</style>