<template>
  <div class="container">
    <section class="hero fade-up">
      <div class="hero-badge">USER ADMIN</div>
      <h1 class="hero-title">用户与权限管理</h1>
      <p class="hero-sub">支持账号查询、权限调整、批量导入，适用于企业商用场景。</p>
    </section>

    <section class="card fade-up fade-up-delay-1">
      <div class="card-title">搜索用户</div>
      <div class="field">
        <label class="field-label">关键词</label>
        <input class="input" v-model="keyword" placeholder="输入用户名或昵称" @keyup.enter="fetchUsers" />
      </div>
      <button class="btn btn-primary" :disabled="loading" @click="fetchUsers">
        {{ loading ? '查询中...' : '查询' }}
      </button>
    </section>

    <section class="card fade-up fade-up-delay-1">
      <div class="card-title">批量导入</div>
      <div class="card-desc">粘贴 JSON 数组，支持批量新增或更新用户信息。</div>
      <textarea class="textarea" v-model="importText" rows="4"></textarea>
      <button class="btn btn-accent" @click="importUsers">执行导入</button>
    </section>

    <section class="card fade-up fade-up-delay-2" v-if="users.length">
      <div class="card-title">用户列表</div>

      <div class="list-item" v-for="item in users" :key="item.id">
        <div class="item-title">{{ item.nickname }}（{{ item.username }}）</div>
        <div class="item-sub">{{ item.company || '未填写公司' }} · {{ item.title || '未填写岗位' }} · {{ item.is_admin ? '管理员' : '普通用户' }}</div>
        <div class="row">
          <span class="label">信誉分</span>
          <div class="credit-score-bar">
            <div class="credit-fill" :style="{ width: ((item.credit_score || 100) / 2) + '%' }"></div>
            <span class="credit-value">{{ item.credit_score || 100 }}</span>
          </div>
        </div>

        <div v-if="editUserId === item.id" style="margin-top: 10px;">
          <div class="grid-2">
            <div class="field">
              <label class="field-label">昵称</label>
              <input class="input" v-model="editForm.nickname" placeholder="昵称" />
            </div>
            <div class="field">
              <label class="field-label">手机号</label>
              <input class="input" v-model="editForm.phone" placeholder="手机号" />
            </div>
            <div class="field">
              <label class="field-label">公司</label>
              <input class="input" v-model="editForm.company" placeholder="公司" />
            </div>
            <div class="field">
              <label class="field-label">岗位</label>
              <input class="input" v-model="editForm.title" placeholder="岗位" />
            </div>
            <div class="field">
              <label class="field-label">新密码（可选）</label>
              <input class="input" type="password" v-model="editForm.password" placeholder="留空表示不修改" />
            </div>
            <div class="field">
              <label class="field-label">信誉分（0-200）</label>
              <input class="input" type="number" v-model.number="editForm.credit_score" />
            </div>
          </div>

          <div class="row">
            <span class="label">管理员权限</span>
            <label class="switch">
              <input type="checkbox" v-model="editForm.is_admin" />
              <span class="switch-slider"></span>
            </label>
          </div>

          <div class="btn-row">
            <button class="btn btn-primary" @click="saveEdit">保存</button>
            <button class="btn btn-ghost" @click="cancelEdit">取消</button>
          </div>
        </div>

        <div v-else class="btn-row">
          <button class="btn btn-ghost btn-sm" @click="startEdit(item)">编辑</button>
          <button class="btn btn-danger btn-sm" @click="removeUser(item.id)">删除</button>
        </div>
      </div>
    </section>

    <section class="card fade-up fade-up-delay-2" v-else-if="!loading">
      <div class="empty">暂无用户。</div>
    </section>
  </div>
</template>

<script>
import { request } from '@/utils/request'
import { toast, confirm } from '@/utils/feedback'

export default {
  name: 'AdminUsers',
  data() {
    return {
      keyword: '',
      loading: false,
      users: [],
      editUserId: null,
      editForm: {
        nickname: '',
        company: '',
        title: '',
        phone: '',
        is_admin: false,
        password: '',
        credit_score: 100
      },
      importText: '[{"username":"operator01","password":"123456","nickname":"运营同学","company":"示例科技公司"}]'
    }
  },
  mounted() {
    this.fetchUsers()
  },
  methods: {
    async fetchUsers() {
      this.loading = true
      try {
        const data = await request({
          url: '/admin/users',
          params: {
            keyword: this.keyword,
            page: 1,
            page_size: 80
          }
        })
        this.users = data.items || []
      } finally {
        this.loading = false
      }
    },
    startEdit(row) {
      this.editUserId = row.id
      this.editForm = {
        nickname: row.nickname || '',
        company: row.company || '',
        title: row.title || '',
        phone: row.phone || '',
        is_admin: !!row.is_admin,
        password: '',
        credit_score: row.credit_score || 100
      }
    },
    cancelEdit() {
      this.editUserId = null
    },
    async saveEdit() {
      const id = this.editUserId
      if (!id) return
      const payload = { ...this.editForm }
      if (!payload.password) delete payload.password
      await request({ url: `/admin/users/${id}`, method: 'PUT', data: payload })
      toast('用户已更新', 'success')
      this.editUserId = null
      this.fetchUsers()
    },
    async removeUser(id) {
      const { confirm: ok } = await confirm({
        title: '删除用户',
        content: `确认删除用户 ID ${id} 吗？`,
        confirmText: '删除',
        cancelText: '取消'
      })
      if (!ok) return
      await request({ url: `/admin/users/${id}`, method: 'DELETE' })
      toast('删除成功', 'success')
      this.fetchUsers()
    },
    async importUsers() {
      let items = []
      try {
        items = JSON.parse(this.importText)
      } catch (err) {
        toast('JSON 格式错误', 'error')
        return
      }
      await request({ url: '/admin/users/import', method: 'POST', data: { items } })
      toast('导入完成', 'success')
      this.fetchUsers()
    }
  }
}
</script>
