<template>
  <div class="sms-config">
    <el-card>
      <template #header>
        <span>短信平台配置</span>
      </template>
      <el-form
        v-if="isSuperUser"
        ref="formRef"
        :model="form"
        label-width="120px"
        style="max-width: 600px"
      >
        <el-form-item label="服务商">
          <el-select v-model="form.provider" placeholder="请选择">
            <el-option label="阿里云" value="aliyun" />
            <el-option label="腾讯云" value="tencent" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="AccessKey">
          <el-input v-model="form.access_key" placeholder="AccessKey" show-password />
        </el-form-item>
        <el-form-item label="SecretKey">
          <el-input v-model="form.secret_key" placeholder="SecretKey" show-password />
        </el-form-item>
        <el-form-item label="签名">
          <el-input v-model="form.sign_name" placeholder="短信签名" />
        </el-form-item>
        <el-form-item label="模板ID">
          <el-input v-model="form.template_id" placeholder="验证码模板ID" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="form.enabled" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSave">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getSMSConfig, updateSMSConfig } from '../../api/admin'
import { useAuthStore } from '../../stores/auth'

const authStore = useAuthStore()
const formRef = ref(null)
const loading = ref(false)

const form = reactive({
  provider: '',
  access_key: '',
  secret_key: '',
  sign_name: '',
  template_id: '',
  enabled: false
})

const isSuperUser = computed(() => {
  const user = authStore.getUser()
  if (!user) return false
  return user.role_id === 9527 && user.role === 'admin'
})

const fetchConfig = async () => {
  if (!isSuperUser.value) return
  try {
    const res = await getSMSConfig()
    Object.assign(form, res)
  } catch (e) {
    if (e.response?.status === 403) {
      ElMessage.warning('仅超级用户可配置')
    } else {
      ElMessage.error(e.message || '获取配置失败')
    }
  }
}

const handleSave = async () => {
  loading.value = true
  try {
    await updateSMSConfig(form)
    ElMessage.success('保存成功')
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message || '保存失败')
  } finally {
    loading.value = false
  }
}

onMounted(fetchConfig)
</script>

<style scoped>
.sms-config {
  padding: 0;
}
</style>
