<template>
  <ContentPage>
    <!-- <template #header>用户管理</template> -->

    <template #search>
      <div style="display: flex; gap: 8px">
        <el-input v-model="query.keyword" placeholder="用户名/昵称/手机号/邮箱" style="max-width: 260px" clearable />
        <el-button type="primary" @click="() => ((query.page = 1), loadUsers())">查询</el-button>
        <el-button @click="openCreate" style="border: 1px solid var(--ios-primary); color: var(--ios-primary);">新增用户</el-button>
        <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
      </div>
    </template>

    <el-table :data="users" v-loading="loading" style="width: 100%; height: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" :index="indexMethod" />
      <el-table-column label="用户" min-width="80">
        <template #default="{ row }">
          <div style="display: flex; align-items: center; gap: 10px">
            <el-avatar shape="square" :size="40" :src="apiBase + row.avatarPath" v-if="row.avatarPath" />
            <el-avatar shape="square" :size="40" v-else>{{ row.nickname?.charAt(0) }}</el-avatar>
            <div style="line-height: 1.2">
              <div style="font-weight: 600">{{ row.username }}</div>
              <div style="font-size: 12px; color: var(--el-text-color-secondary)">{{ row.email || '-' }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label="昵称" min-width="80" />
      <el-table-column label="角色">
        <template #default="{ row }">
          <el-tag v-for="r in row.roles" :key="r" size="small" style="margin-right: 4px">{{ r }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" />
      <el-table-column label="性别" width="100">
        <template #default="{ row }">
          <span v-if="row.gender === 1">男</span>
          <span v-else-if="row.gender === 2">女</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">{{ row.status === 1 ? '正常' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="{ row }">
          <div style="display: flex; align-items: center">
            <el-tooltip content="编辑" placement="top">
              <el-button type="primary" text bg :icon="EditPen" style="font-size: 15px; padding: 6px 8px" @click="openEdit(row)" />
            </el-tooltip>
            <el-tooltip content="分配角色" placement="top">
              <el-button type="primary" text bg :icon="UserFilled" style="font-size: 15px; padding: 6px 8px" @click="openAssignRoles(row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button type="danger" text bg :icon="Delete" style="font-size: 15px; padding: 6px 8px" @click="handleDelete(row)" />
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <template #pagination>
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        v-model:page-size="query.size"
        v-model:current-page="query.page"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="loadUsers"
        @current-change="loadUsers"
      />
    </template>
  </ContentPage>

  <el-dialog v-model="roleDialogOpen" title="分配角色" width="520px">
    <el-form v-loading="roleLoading" label-width="90px">
      <el-form-item label="用户：">
        <span>{{ currentUser?.username }}</span>
      </el-form-item>
      <el-form-item label="角色：">
        <el-checkbox-group v-model="selectedRoleIds">
          <el-checkbox v-for="r in allRoles" :key="r.id" :value="r.id">
            {{ r.roleName }}({{ r.roleKey }})
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="roleDialogOpen = false">取消</el-button>
      <el-button type="primary" :loading="roleLoading" @click="saveRoles">保存</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="formDialogOpen" :title="formData.id ? '编辑用户' : '新增用户'" width="520px">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px" v-loading="formLoading">
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :http-request="handleAvatarUpload"
          style="border: 1px dashed var(--el-border-color); border-radius: 6px; cursor: pointer; overflow: hidden; display: inline-block;"
        >
          <img v-if="formData.avatarPath" :src="apiBase + formData.avatarPath" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" :disabled="!!formData.id" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="formData.nickname" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" type="password" placeholder="不修改请留空" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="formData.gender">
          <el-radio :value="0">未知</el-radio>
          <el-radio :value="1">男</el-radio>
          <el-radio :value="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="formDialogOpen = false">取消</el-button>
      <el-button type="primary" :loading="formLoading" @click="saveUser">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import ContentPage from '@/components/ContentPage.vue'
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, EditPen, Plus, UserFilled } from '@element-plus/icons-vue'
import {
  createUser,
  deleteUser,
  deleteUsers,
  fetchRoles,
  fetchUserRoleIds,
  fetchUsers,
  updateUser,
  updateUserRoles,
} from '../../../api/system'
import { uploadFile } from '../../../api/common'

const apiBase = import.meta.env.VITE_API_BASE || 'http://localhost:8080'

const query = reactive({
  page: 1,
  size: 10,
  keyword: '',
})

const loading = ref(false)
const users = ref([])
const total = ref(0)

async function loadUsers() {
  loading.value = true
  try {
    const page = await fetchUsers(query)
    users.value = page.records
    total.value = page.total
  } finally {
    loading.value = false
  }
}

function indexMethod(index) {
  return (query.page - 1) * query.size + index + 1
}

const selectedIds = ref([])

function handleSelectionChange(selection) {
  selectedIds.value = selection.map((item) => item.id)
}

function handleBatchDelete() {
  if (selectedIds.value.length === 0) return
  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 个用户吗？`, '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await deleteUsers(selectedIds.value)
      ElMessage.success('删除成功')
      loadUsers()
    } catch (e) {
      ElMessage.error(e?.response?.data?.message || '删除失败')
    }
  })
}

const formDialogOpen = ref(false)
const formLoading = ref(false)
const formRef = ref(null)
const formData = reactive({
  id: undefined,
  username: '',
  password: '',
  nickname: '',
  avatarPath: '',
  phone: '',
  email: '',
  gender: 0,
  status: 1,
})
const rules = computed(() => {
  const r = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  }
  if (!formData.id) {
    r.password = [{ required: true, message: '请输入密码', trigger: 'blur' }]
  }
  return r
})

function openCreate() {
  formData.id = undefined
  formData.username = ''
  formData.password = ''
  formData.nickname = ''
  formData.avatarPath = ''
  formData.phone = ''
  formData.email = ''
  formData.gender = 0
  formData.status = 1
  formDialogOpen.value = true
}

function openEdit(row) {
  Object.assign(formData, row)
  formData.password = '' // Don't show password
  formDialogOpen.value = true
}

async function saveUser() {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
  } catch (e) {
    return
  }
  formLoading.value = true
  try {
    if (formData.id) {
      await updateUser(formData)
      ElMessage.success('更新成功')
    } else {
      await createUser(formData)
      ElMessage.success('创建成功')
    }
    formDialogOpen.value = false
    loadUsers()
  } catch (e) {
    ElMessage.error(e?.response?.data?.message || '保存失败')
  } finally {
    formLoading.value = false
  }
}

function handleDelete(row) {
  ElMessageBox.confirm(`确认删除用户 "${row.username}" 吗？`, '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await deleteUser(row.id)
      ElMessage.success('删除成功')
      loadUsers()
    } catch (e) {
      ElMessage.error(e?.response?.data?.message || '删除失败')
    }
  })
}

async function handleAvatarUpload(options) {
  try {
    const res = await uploadFile(options.file)
    // The backend returns { url: '...', thumbUrl: '...' }
    // We store the relative path or full URL depending on requirement.
    // Here we assume the backend returns a relative path like 'avatar/...'
    // and we prepend the base URL when displaying.
    // But for simplicity, let's just save what the backend returns.
    formData.avatarPath = res.url
  } catch (e) {
    ElMessage.error('上传失败')
  }
}

onMounted(loadUsers)

const roleDialogOpen = ref(false)
const roleLoading = ref(false)
const allRoles = ref([])
const selectedRoleIds = ref([])
const currentUser = ref(null)

async function openAssignRoles(u) {
  currentUser.value = u
  roleDialogOpen.value = true
  roleLoading.value = true
  try {
    const [roles, roleIds] = await Promise.all([fetchRoles(), fetchUserRoleIds(u.id)])
    allRoles.value = roles
    selectedRoleIds.value = roleIds
  } finally {
    roleLoading.value = false
  }
}

async function saveRoles() {
  if (!currentUser.value) return
  roleLoading.value = true
  try {
    await updateUserRoles(currentUser.value.id, selectedRoleIds.value)
    ElMessage.success('保存成功')
    roleDialogOpen.value = false
    loadUsers()
  } catch (e) {
    ElMessage.error(e?.response?.data?.message || '保存失败')
  } finally {
    roleLoading.value = false
  }
}

</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
