<template>
  <div class="admin-group-container">
    <!-- 主容器 -->
    <el-card class="main-container" shadow="never">
      <!-- 操作栏 -->
      <div class="filter-section">
        <div class="filter-content">
          <div class="search-form">
            <el-input
              v-model="queryParams.key"
              placeholder="搜索关键词"
              clearable
              @clear="fetchGroupList"
              @keyup.enter="fetchGroupList"
              style="width: 200px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="action-bar">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>新增管理员组
            </el-button>
            <el-button type="success" @click="fetchGroupList">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>
        </div>
      </div>

      <!-- 管理员组列表 -->
      <div class="table-section">
        <!-- 骨架屏 -->
        <div v-if="loading" class="skeleton-container">
          <div v-for="i in 5" :key="i" class="skeleton-row">
            <div class="skeleton-cell skeleton-id"></div>
            <div class="skeleton-cell skeleton-name"></div>
            <div class="skeleton-cell skeleton-note"></div>
            <div class="skeleton-cell skeleton-time"></div>
            <div class="skeleton-cell skeleton-action"></div>
          </div>
        </div>

        <el-table
          v-else
          v-loading="loading"
          :data="groupList"
          style="width: 100%"
          :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
        >
          <el-table-column prop="id" label="组ID" width="100" />
          <el-table-column prop="name" label="组名称" min-width="200">
            <template #default="{ row }">
              <span class="group-name">{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="note" label="备注" min-width="250" show-overflow-tooltip />
          <el-table-column prop="CreatedAt" label="创建时间" width="180" />
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" link @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>编辑
                </el-button>
                <el-button type="success" link @click="handleViewMembers(row)">
                  <el-icon><User /></el-icon>成员
                </el-button>
                <el-button type="danger" link @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.count"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 管理员组表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增管理员组' : '编辑管理员组'"
      width="600px"
      append-to-body
    >
      <el-form
        ref="groupFormRef"
        :model="groupForm"
        :rules="groupRules"
        label-width="120px"
      >
        <el-form-item label="组名称" prop="name">
          <el-input v-model="groupForm.name" placeholder="请输入组名称" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="groupForm.note" type="textarea" :rows="4" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 成员列表对话框 -->
    <el-dialog
      v-model="memberDialogVisible"
      title="管理员组成员"
      width="900px"
      append-to-body
    >
      <div class="member-search">
        <el-input
          v-model="memberParams.key"
          placeholder="搜索成员"
          clearable
          @clear="fetchMemberList"
          @keyup.enter="fetchMemberList"
          style="width: 200px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <el-table
        v-loading="memberLoading"
        :data="memberList"
        style="width: 100%"
        :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
      >
        <el-table-column prop="UserId" label="用户ID" width="100" />
        <el-table-column prop="UserName" label="用户名" min-width="150">
          <template #default="{ row }">
            <div class="user-info">
              <span class="username">{{ row.UserName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="Email" label="邮箱" min-width="200" />
        <el-table-column prop="Phone" label="手机号" width="130" />
        <el-table-column label="性别" width="80">
          <template #default="{ row }">
            {{ row.Sex ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="Age" label="年龄" width="80" />
        <el-table-column prop="UserGroupId" label="用户组" width="120" />
        <el-table-column label="加入时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.CreatedAt) }}
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="memberParams.page"
        v-model:page-size="memberParams.count"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        :total="memberTotal"
        @size-change="handleMemberSizeChange"
        @current-change="handleMemberCurrentChange"
        background
        class="pagination"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search, Edit, User, Delete } from '@element-plus/icons-vue'
import { 
  getAdminGroupList, 
  getAdminGroupMemberList, 
  addAdminGroup, 
  updateAdminGroupInfo, 
  deleteAdminGroup 
} from '@/api/admin/group'
import { formatTime } from '@/utils/tool'

// 查询参数
const queryParams = reactive({
  key: '',
  page: 1,
  count: 10
})

// 成员查询参数
const memberParams = reactive({
  key: '',
  group_id: '',
  page: 1,
  count: 10
})

// 管理员组表单
const groupForm = reactive({
  group_id: undefined,
  name: '',
  note: ''
})

const groupRules = {
  name: [
    { required: true, message: '请输入组名称', trigger: 'blur' }
  ]
}

// 状态数据
const loading = ref(false)
const memberLoading = ref(false)
const groupList = ref([])
const memberList = ref([])
const total = ref(0)
const memberTotal = ref(0)
const dialogVisible = ref(false)
const memberDialogVisible = ref(false)
const dialogType = ref('add')
const groupFormRef = ref(null)

// 获取管理员组列表
const fetchGroupList = async () => {
  loading.value = true
  try {
    const res = await getAdminGroupList(queryParams)
    if (res.data.code === 200) {
      let responseData = res.data.data.data || []
      responseData.forEach(item => {
        item.CreatedAt = formatTime(item.CreatedAt)
      })
      groupList.value = responseData
      total.value = res.data.data.total || 0
    }
  } catch (error) {
    ElMessage.error('获取管理员组列表失败')
  } finally {
    loading.value = false
  }
}

// 获取成员列表
const fetchMemberList = async () => {
  memberLoading.value = true
  try {
    const res = await getAdminGroupMemberList(memberParams)
    if (res.data.code === 200) {
      let responseData = res.data.data.data || []
      // 数据已经包含所有需要的字段，不需要额外处理
      memberList.value = responseData
      memberTotal.value = res.data.data.total || 0
    }
  } catch (error) {
    ElMessage.error('获取成员列表失败')
  } finally {
    memberLoading.value = false
  }
}

// 分页
const handleSizeChange = (size) => {
  queryParams.count = size
  fetchGroupList()
}

const handleCurrentChange = (page) => {
  queryParams.page = page
  fetchGroupList()
}

const handleMemberSizeChange = (size) => {
  memberParams.count = size
  fetchMemberList()
}

const handleMemberCurrentChange = (page) => {
  memberParams.page = page
  fetchMemberList()
}

// 新增管理员组
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.assign(groupForm, {
    group_id: undefined,
    name: '',
    note: ''
  })
  groupFormRef.value?.resetFields()
}

// 编辑管理员组
const handleEdit = (row) => {
  console.log("编辑管理员组",row)
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(groupForm, {
    group_id: row.id,
    name: row.name,
    note: row.note
  })
}

// 查看成员
const handleViewMembers = (row) => {
  memberParams.group_id = row.id
  memberParams.key = ''
  memberParams.page = 1
  memberDialogVisible.value = true
  fetchMemberList()
}

// 删除管理员组
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除管理员组 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteAdminGroup({ group_id: row.id })
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchGroupList()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  groupFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (dialogType.value === 'add') {
          res = await addAdminGroup(groupForm)
        } else {
          res = await updateAdminGroupInfo(groupForm)
        }
        if (res.data.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
          dialogVisible.value = false
          fetchGroupList()
        }
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
  })
}

// 初始化
onMounted(() => {
  fetchGroupList()
})
</script>

<style scoped>
.admin-group-container {
  padding: 0;
}

.main-container {
  border: 1px solid #e1e8ed;
  background: #ffffff;
}

.filter-section {
  padding: 0;
  border-bottom: 1px solid #e1e8ed;
  background: #fafbfc;
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form {
  margin: 0;
  flex: 1;
  display: flex;
  align-items: center;
}

.action-bar {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.table-section {
  padding: 0;
}

.group-name {
  font-weight: 500;
  color: #2c3e50;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  padding: 16px 20px;
  border-top: 1px solid #e1e8ed;
  background: #fafbfc;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0;
}

.member-search {
  margin-bottom: 16px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border: none;
  color: #2c3e50;
}

:deep(.el-table__header) {
  background: #f8f9fa;
}

:deep(.el-table th) {
  background: #f8f9fa !important;
  border-bottom: 2px solid #e1e8ed;
  color: #2c3e50;
  font-weight: 600;
  font-size: 13px;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f2f5;
  color: #34495e;
}

:deep(.el-table tr:hover > td) {
  background-color: #f8f9fa !important;
}

:deep(.el-card__body) {
  padding: 0;
}

/* 骨架屏样式 */
.skeleton-container {
  padding: 20px;
}

.skeleton-row {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  gap: 16px;
}

.skeleton-row:last-child {
  border-bottom: none;
}

.skeleton-cell {
  height: 20px;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s ease-in-out infinite;
  border-radius: 4px;
}

.skeleton-id { width: 100px; }
.skeleton-name { width: 200px; }
.skeleton-note { flex: 1; min-width: 250px; }
.skeleton-time { width: 180px; }
.skeleton-action { width: 250px; height: 32px; }

@keyframes skeleton-loading {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}
</style>
