<template>
  <view class="user-management">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @click="navigateBack">
        <u-icon name="arrow-left" size="24" color="#606266"></u-icon>
      </view>
      <view class="nav-title">用户管理</view>
      <view class="nav-right">
        <u-button type="text" @click="addUser">添加</u-button>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-box">
      <u-search placeholder="搜索用户名/手机号" v-model="searchKeyword"></u-search>
    </view>

    <!-- 用户列表 -->
    <view class="user-list">
      <u-cell-group v-if="filteredUsers.length > 0">
        <u-cell 
          v-for="(user, index) in filteredUsers" 
          :key="user.id"
          :title="user.name"
          :label="`手机号：${user.phone} | 角色：${getRoleName(user.role)}`"
          :right-icon="'arrow-right'"
          is-link
          @click="editUser(user)"
        >
          <template #right>
            <u-tag :type="getRoleType(user.role)">{{ getRoleName(user.role) }}</u-tag>
          </template>
        </u-cell>
      </u-cell-group>
      <u-empty v-else text="暂无用户数据"></u-empty>
    </view>

    <!-- 分页 -->
    <u-pagination 
      v-if="filteredUsers.length > 0" 
      :current="currentPage"
      :pageSize="pageSize"
      :total="filteredUsers.length"
      @change="changePage"
    ></u-pagination>

    <!-- 添加/编辑用户弹窗 -->
    <u-popup v-model="showUserModal" mode="bottom" :round="true" :closeable="true">
      <view class="modal-content">
        <view class="modal-title">{{ isEditing ? '编辑用户' : '添加用户' }}</view>
        <u-form :model="formData" ref="uForm">
          <u-form-item label="姓名">
            <u-input v-model="formData.name" placeholder="请输入姓名"></u-input>
          </u-form-item>
          <u-form-item label="手机号">
            <u-input v-model="formData.phone" type="number" placeholder="请输入手机号"></u-input>
          </u-form-item>
          <u-form-item label="角色">
            <u-picker 
              mode="selector" 
              :range="roles" 
              :rangeKey="'name'"
              v-model="formData.roleIndex"
              placeholder="请选择角色"
            ></u-picker>
          </u-form-item>
          <u-form-item label="部门">
            <u-picker 
              mode="selector" 
              :range="departments" 
              :rangeKey="'name'"
              v-model="formData.deptIndex"
              placeholder="请选择部门"
            ></u-picker>
          </u-form-item>
        </u-form>
        <view class="modal-buttons">
          <u-button @click="showUserModal = false" style="flex: 1; margin-right: 20rpx;">取消</u-button>
          <u-button type="primary" @click="submitForm" style="flex: 1;">确定</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        searchKeyword: '',
        currentPage: 1,
        pageSize: 10,
        showUserModal: false,
        isEditing: false,
        editUserId: '',
        formData: {
          name: '',
          phone: '',
          roleIndex: 0,
          deptIndex: 0
        },
        roles: [
          { id: 1, name: '管理员' },
          { id: 2, name: '信息员' },
          { id: 3, name: '部门负责人' },
          { id: 4, name: '普通用户' }
        ],
        departments: [
          { id: 1, name: '技术部' },
          { id: 2, name: '市场部' },
          { id: 3, name: '财务部' },
          { id: 4, name: '人力资源部' },
          { id: 5, name: '行政部' }
        ],
        users: [
          { id: 1, name: '张三', phone: '13800138001', role: 1, deptId: 1 },
          { id: 2, name: '李四', phone: '13800138002', role: 2, deptId: 2 },
          { id: 3, name: '王五', phone: '13800138003', role: 3, deptId: 3 },
          { id: 4, name: '赵六', phone: '13800138004', role: 4, deptId: 4 },
          { id: 5, name: '钱七', phone: '13800138005', role: 4, deptId: 5 },
          { id: 6, name: '孙八', phone: '13800138006', role: 3, deptId: 1 },
          { id: 7, name: '周九', phone: '13800138007', role: 2, deptId: 3 },
          { id: 8, name: '吴十', phone: '13800138008', role: 4, deptId: 2 }
        ]
      }
    },
    computed: {
      filteredUsers() {
        if (!this.searchKeyword) {
          return this.users
        }
        return this.users.filter(user => 
          user.name.includes(this.searchKeyword) || 
          user.phone.includes(this.searchKeyword)
        )
      },
      paginatedUsers() {
        const start = (this.currentPage - 1) * this.pageSize
        const end = start + this.pageSize
        return this.filteredUsers.slice(start, end)
      }
    },
    methods: {
      navigateBack() {
        uni.navigateBack()
      },
      getRoleName(roleId) {
        const role = this.roles.find(r => r.id === roleId)
        return role ? role.name : '未知'
      },
      getRoleType(roleId) {
        switch (roleId) {
          case 1: return 'error'
          case 2: return 'success'
          case 3: return 'warning'
          case 4: return 'info'
          default: return 'info'
        }
      },
      addUser() {
        this.isEditing = false
        this.formData = {
          name: '',
          phone: '',
          roleIndex: 0,
          deptIndex: 0
        }
        this.showUserModal = true
      },
      editUser(user) {
        this.isEditing = true
        this.editUserId = user.id
        const roleIndex = this.roles.findIndex(r => r.id === user.role)
        const deptIndex = this.departments.findIndex(d => d.id === user.deptId)
        this.formData = {
          name: user.name,
          phone: user.phone,
          roleIndex: roleIndex !== -1 ? roleIndex : 0,
          deptIndex: deptIndex !== -1 ? deptIndex : 0
        }
        this.showUserModal = true
      },
      submitForm() {
        if (!this.formData.name || !this.formData.phone) {
          uni.showToast({ title: '请填写完整信息', icon: 'none' })
          return
        }

        const userData = {
          name: this.formData.name,
          phone: this.formData.phone,
          role: this.roles[this.formData.roleIndex].id,
          deptId: this.departments[this.formData.deptIndex].id
        }

        if (this.isEditing) {
          // 编辑用户
          const index = this.users.findIndex(u => u.id === this.editUserId)
          if (index !== -1) {
            this.users[index] = { ...this.users[index], ...userData }
            uni.showToast({ title: '编辑成功', icon: 'success' })
          }
        } else {
          // 添加用户
          const newId = Math.max(...this.users.map(u => u.id), 0) + 1
          this.users.push({ id: newId, ...userData })
          uni.showToast({ title: '添加成功', icon: 'success' })
        }

        this.showUserModal = false
      },
      changePage(page) {
        this.currentPage = page
      }
    }
  }
</script>

<style lang="scss">
  .user-management {
    padding-bottom: 20rpx;
    background-color: #f5f5f5;

    .nav-bar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 88rpx;
      padding: 0 30rpx;
      background-color: #fff;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

      .nav-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
      }
    }

    .search-box {
      padding: 20rpx;
      background-color: #fff;
    }

    .user-list {
      margin-top: 20rpx;
      padding: 0 20rpx;
    }

    .modal-content {
      padding: 30rpx;

      .modal-title {
        font-size: 36rpx;
        font-weight: bold;
        text-align: center;
        margin-bottom: 30rpx;
        color: #333;
      }

      .modal-buttons {
        display: flex;
        margin-top: 30rpx;
      }
    }
  }
</style>