<template>
  <div class="store-page">
    <Breadcrumb />

    <a-card title="账号管理">
      <div class="buttonGroup">
        <a-button type="primary" @click="openModal()">
          <template #icon><icon-plus /></template>
          添加账号
        </a-button>
        <a-button @click="loadList">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>
      </div>

      <a-table row-key="id" :data="data" :loading="loading" :pagination="false" :scroll="{ x: 900 }">
        <template #columns>
          <a-table-column title="登录名" data-index="username" :width="140" />
          <a-table-column title="姓名" :width="100">
            <template #cell="{ record }">{{ record.realname || '未知' }}</template>
          </a-table-column>
          <a-table-column title="学院" :width="140">
            <template #cell="{ record }">{{ record.deptName || '未知' }}</template>
          </a-table-column>
          <a-table-column title="班级" :width="140">
            <template #cell="{ record }">{{ record.className || '未知' }}</template>
          </a-table-column>
          <a-table-column title="创建时间" :width="170">
            <template #cell="{ record }">{{ formatTimestamp(record.create_time) }}</template>
          </a-table-column>
          <a-table-column title="更新时间" :width="170">
            <template #cell="{ record }">{{ formatTimestamp(record.update_time) }}</template>
          </a-table-column>
          <a-table-column title="状态" :width="100">
            <template #cell="{ record }">
              <a-tag v-if="record.state === 0" color="orangered">待验证</a-tag>
              <a-tag v-else-if="record.state === 1" color="green">已验证</a-tag>
              <a-tag v-else-if="record.state === 2" color="red">已失效</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="200" fixed="right">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="handleActive(record)">验证</a-button>
                <a-button type="text" size="small" @click="openModal(record)">编辑</a-button>
                <a-popconfirm content="删除后无法恢复，确认删除？" @ok="handleDelete(record)">
                  <a-button type="text" status="danger" size="small">删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="visible"
      :title="form.id ? '编辑账号' : '添加账号'"
      @before-ok="handleSave"
      :ok-loading="saving"
      draggable
      esc-to-close
    >
      <a-form :model="form" layout="vertical">
        <a-form-item label="用户名" required>
          <a-input v-model="form.username" placeholder="统一身份认证用户名" allow-clear />
        </a-form-item>
        <a-form-item label="密码" required>
          <a-input-password v-model="form.password" placeholder="统一身份认证密码" allow-clear />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Notification, Modal } from '@arco-design/web-vue'
import { getJwAccount, saveJwAccount, deleteJwAccount, activeJwAccount } from '@/api/jwAccount'
import { formatTimestamp } from '@/utils/icTime'

const loading = ref(false)
const saving = ref(false)
const visible = ref(false)
const data = ref([])
const form = reactive({ id: undefined, username: '', password: '' })

const loadList = async () => {
  loading.value = true
  try {
    const res = await getJwAccount()
    if (res?.code !== 0) {
      Notification.error({ title: '获取账号列表失败', content: res?.msg || '请稍后再试' })
      return
    }
    data.value = res.data || []
  } catch (error) {
    Notification.error({ title: '请求失败', content: error.message || '网络错误' })
  } finally {
    loading.value = false
  }
}

const openModal = (record) => {
  form.id = record?.id
  form.username = record?.username || ''
  form.password = ''
  visible.value = true
}

const handleSave = async () => {
  if (!form.username?.trim()) {
    Notification.error({ title: '请填写用户名' })
    return false
  }
  if (!form.password?.trim()) {
    Notification.error({ title: '请填写密码' })
    return false
  }
  saving.value = true
  try {
    const res = await saveJwAccount({
      id: form.id,
      username: form.username.trim(),
      password: btoa(form.password)
    })
    if (res?.code !== 0) {
      Notification.error({ title: '保存失败', content: res?.msg || '请稍后再试' })
      return false
    }
    Notification.success({ title: '保存成功', content: '请及时验证账号' })
    await loadList()
    return true
  } catch (error) {
    Notification.error({ title: '保存失败', content: error.message || '请稍后再试' })
    return false
  } finally {
    saving.value = false
  }
}

const handleActive = (record) => {
  Modal.confirm({
    title: '验证账号',
    content: `您正在验证统一身份认证账号 ${record.username}，请确保用户名和密码无误。`,
    onOk: async () => {
      const res = await activeJwAccount({ username: record.username })
      if (res?.code !== 0) {
        Notification.error({ title: '验证失败', content: res?.msg || '请稍后再试' })
        return
      }
      Notification.success({ title: '验证成功', content: '该账号现在已可正常使用' })
      loadList()
    }
  })
}

const handleDelete = async (record) => {
  const res = await deleteJwAccount({ id: record.id })
  if (res?.code !== 0) {
    Notification.error({ title: '删除失败', content: res?.msg || '请稍后再试' })
    return
  }
  Notification.success({ title: '删除成功' })
  loadList()
}

onMounted(loadList)
</script>

<style scoped>
.buttonGroup {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}
</style>
