<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 部门树 -->
      <el-col :span="4">
        <el-card shadow="never">
          <template #header>
            <span>部门列表</span>
          </template>
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable style="margin-bottom: 10px" />
          <el-tree
            ref="deptTreeRef"
            :data="deptTree"
            :props="{ children: 'children', label: 'label' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      
      <!-- 用户列表 -->
      <el-col :span="20">
        <!-- 搜索栏 -->
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="用户状态" clearable>
              <el-option label="正常" value="0" />
              <el-option label="停用" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 操作栏 -->
        <el-row :gutter="10" class="mb10">
          <el-col :span="1.5">
            <el-button type="primary" plain @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain :disabled="!selectedIds.length" @click="handleDelete">删除</el-button>
          </el-col>
        </el-row>

        <!-- 表格 -->
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="用户编号" prop="user_id" width="100" />
          <el-table-column label="用户名称" prop="user_name" width="120" show-overflow-tooltip />
          <el-table-column label="用户昵称" prop="nick_name" width="120" show-overflow-tooltip />
          <el-table-column label="部门" prop="dept_name" width="150" show-overflow-tooltip />
          <el-table-column label="手机号码" prop="phonenumber" width="120" />
          <el-table-column label="状态" prop="status" width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="create_time" width="160" />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
              <el-button link type="primary" @click="handleResetPwd(row)">重置密码</el-button>
              <el-button link type="danger" @click="handleDelete(row)" v-if="row.user_id !== 1">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="getList"
          @current-change="getList"
          style="margin-top: 15px; justify-content: flex-end"
        />
      </el-col>
    </el-row>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <el-tree-select
                v-model="form.deptId"
                :data="deptTree"
                :props="{ children: 'children', label: 'label', value: 'id' }"
                placeholder="请选择归属部门"
                check-strictly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="!form.userId">
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option label="男" value="0" />
                <el-option label="女" value="1" />
                <el-option label="未知" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio value="0">正常</el-radio>
                <el-radio value="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="form.roleIds" multiple placeholder="请选择角色" style="width: 100%">
                <el-option
                  v-for="role in roleOptions"
                  :key="role.roleId"
                  :label="role.roleName"
                  :value="role.roleId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位" prop="postIds">
              <el-select v-model="form.postIds" multiple placeholder="请选择岗位" style="width: 100%">
                <el-option
                  v-for="post in postOptions"
                  :key="post.postId"
                  :label="post.postName"
                  :value="post.postId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/**
 * 用户管理页面
 * @author 湖北新华业务中台研发团队
 */
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'

// 部门树
const deptTreeRef = ref()
const deptName = ref('')
const deptTree = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  phonenumber: '',
  status: '',
  deptId: null
})

// 列表数据
const loading = ref(false)
const userList = ref([])
const total = ref(0)
const selectedIds = ref([])

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = ref({})
const roleOptions = ref([])
const postOptions = ref([])

const rules = {
  userName: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
  nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  phonenumber: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }]
}

// 监听部门名称过滤
watch(deptName, (val) => {
  deptTreeRef.value?.filter(val)
})

// 过滤节点
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.includes(value)
}

// 点击部门节点
const handleNodeClick = (data) => {
  queryParams.deptId = data.id
  handleQuery()
}

// 获取部门树
const getDeptTree = async () => {
  try {
    const res = await request.get('/api/system/user/deptTree')
    deptTree.value = res.data || []
  } catch (error) {
    console.error('获取部门树失败:', error)
  }
}

// 获取角色选项
const getRoleOptions = async () => {
  try {
    const res = await request.get('/api/system/user/roleOptions')
    roleOptions.value = res.data || []
  } catch (error) {
    console.error('获取角色选项失败:', error)
  }
}

// 获取岗位选项
const getPostOptions = async () => {
  try {
    const res = await request.get('/api/system/user/postOptions')
    postOptions.value = res.data || []
  } catch (error) {
    console.error('获取岗位选项失败:', error)
  }
}

// 获取用户列表
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/api/system/user/list', { params: queryParams })
    userList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.userName = ''
  queryParams.phonenumber = ''
  queryParams.status = ''
  queryParams.deptId = null
  handleQuery()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.user_id)
}

// 新增
const handleAdd = () => {
  form.value = { status: '0', sex: '0', roleIds: [], postIds: [] }
  dialogTitle.value = '新增用户'
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  try {
    const res = await request.get(`/api/system/user/${row.user_id}`)
    const data = res.data
    form.value = {
      userId: data.user_id,
      deptId: data.dept_id,
      userName: data.user_name,
      nickName: data.nick_name,
      email: data.email,
      phonenumber: data.phonenumber,
      sex: data.sex,
      status: data.status,
      roleIds: (data.roles || []).map(r => r.role_id),
      postIds: (data.posts || []).map(p => p.post_id)
    }
    dialogTitle.value = '编辑用户'
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

// 提交表单
const submitForm = async () => {
  await formRef.value?.validate()
  try {
    if (form.value.userId) {
      await request.put('/api/system/user', form.value)
      ElMessage.success('修改成功')
    } else {
      await request.post('/api/system/user', form.value)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 删除
const handleDelete = async (row) => {
  const ids = row?.user_id ? [row.user_id] : selectedIds.value
  if (!ids.length) return
  
  await ElMessageBox.confirm('确认删除选中的用户?', '提示', { type: 'warning' })
  try {
    await request.delete(`/api/system/user/${ids.join(',')}`)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    ElMessage.error(error.message || '删除失败')
  }
}

// 重置密码
const handleResetPwd = async (row) => {
  const { value } = await ElMessageBox.prompt('请输入新密码', '重置密码', {
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: '密码长度在5到20个字符'
  })
  try {
    await request.put('/api/system/user/resetPwd', { userId: row.user_id, password: value })
    ElMessage.success('密码重置成功')
  } catch (error) {
    ElMessage.error('密码重置失败')
  }
}

// 状态修改
const handleStatusChange = async (row) => {
  const text = row.status === '0' ? '启用' : '停用'
  try {
    await request.put('/api/system/user/changeStatus', { userId: row.user_id, status: row.status })
    ElMessage.success(`${text}成功`)
  } catch (error) {
    row.status = row.status === '0' ? '1' : '0'
    ElMessage.error(`${text}失败`)
  }
}

onMounted(() => {
  getDeptTree()
  getRoleOptions()
  getPostOptions()
  getList()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 15px;
}
.mb10 {
  margin-bottom: 10px;
}
</style>
