<template>
  <div class="yh-cloud-accounts">
    <el-card>
      <template #header>
        <span>宇恒云账号管理</span>
      </template>
      <p class="hint">
        调用云端
        <code>POST /register</code>（默认
        <code>http://www.cloud.yuxindazhineng.com:3001/register</code>，可通过环境变量
        <code>YH_CLOUD_REGISTER_URL</code> 覆盖）。成功后在 Mongo 集合
        <code>yuheng_cloud_register_records</code> 写入一条记录，<strong>仅保存账号与密码</strong>；邮箱仅用于提交云端。
      </p>

      <el-form v-if="canEdit" :model="form" :rules="rules" ref="formRef" label-width="88px" class="add-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="云端 username" clearable style="max-width: 360px" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="云端 password" show-password clearable style="max-width: 360px" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="云端必填 email，不入库" clearable style="max-width: 360px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="submitting" @click="submit">提交注册</el-button>
        </el-form-item>
      </el-form>
      <el-alert v-else type="warning" title="无权限" description="需要「宇恒云账号管理」权限，请在角色权限中为当前角色勾选。" :closable="false" />

      <el-divider v-if="canEdit" />

      <el-table v-if="canEdit" :data="list" v-loading="loading" stripe>
        <el-table-column prop="username" label="账号" min-width="140" />
        <el-table-column label="密码" min-width="160">
          <template #default="{ row }">
            <span class="pwd-mask">{{ row._showPwd ? row.password : '••••••••' }}</span>
            <el-button link type="primary" size="small" @click="row._showPwd = !row._showPwd">
              {{ row._showPwd ? '隐藏' : '显示' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="记录时间" width="200" />
      </el-table>
      <el-pagination
        v-if="canEdit"
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        style="margin-top: 16px"
        @current-change="fetchList"
        @size-change="fetchList"
      />
    </el-card>
  </div>
</template>

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

const authStore = useAuthStore()
const canEdit = computed(() => authStore.hasPermission('yuheng_cloud:manage'))

const formRef = ref(null)
const submitting = ref(false)
const loading = ref(false)
const list = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)

const form = reactive({
  username: '',
  password: '',
  email: ''
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱（提交云端）', trigger: 'blur' }]
}

const fetchList = async () => {
  if (!canEdit.value) return
  loading.value = true
  try {
    const res = await listYuhengCloudAccounts({ page: page.value, page_size: pageSize.value })
    const rows = (res.list || []).map((r) => ({ ...r, _showPwd: false }))
    list.value = rows
    total.value = res.total ?? 0
  } catch (e) {
    ElMessage.error(e.message || '加载失败')
  } finally {
    loading.value = false
  }
}

const submit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
  } catch {
    return
  }
  submitting.value = true
  try {
    await createYuhengCloudAccount({
      username: form.username.trim(),
      password: form.password,
      email: form.email.trim()
    })
    ElMessage.success('云端注册成功，已写入本地记录')
    form.username = ''
    form.password = ''
    form.email = ''
    formRef.value?.resetFields()
    fetchList()
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  if (canEdit.value) fetchList()
})
</script>

<style scoped>
.yh-cloud-accounts {
  padding: 0;
}
.hint {
  margin: 0 0 16px;
  font-size: 13px;
  color: #606266;
  line-height: 1.65;
  max-width: 900px;
}
.add-form {
  max-width: 520px;
}
.pwd-mask {
  margin-right: 8px;
  font-family: monospace;
}
</style>
