<template>
  <el-dialog
    v-model="visible"
    :title="adminGroup ? '选择管理员组' : '选择用户组'"
    width="900px"
    append-to-body
    @close="handleClose"
  >
    <div class="user-group-selector">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <!-- 选择用户组 -->
        <el-tab-pane :label="adminGroup ? '选择管理员组' : '选择用户组'" name="selectGroup">
          <div class="group-list-container">
            <!-- 搜索筛选区域 -->
            <div class="filter-section">
              <el-form :inline="true" :model="searchParams" class="search-form">
                <el-form-item label="关键词">
                  <el-input
                    v-model="searchParams.key"
                    :placeholder="adminGroup ? '搜索管理员组名称' : '搜索用户组名称'"
                    clearable
                    @keyup.enter="handleSearch"
                    style="width: 200px"
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSearch" :icon="Search">
                    搜索
                  </el-button>
                  <el-button @click="handleReset" :icon="Refresh">
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 管理员组列表表格 -->
            <el-table
              v-if="adminGroup"
              v-loading="loading"
              :data="groupList"
              highlight-current-row
              @current-change="handleCurrentChange"
              style="width: 100%"
              :height="350"
              :row-class-name="tableRowClassName"
            >
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column prop="id" label="ID" width="80" align="center" />
              <el-table-column prop="name" label="组名称" min-width="150" show-overflow-tooltip>
                <template #default="{ row }">
                  <span class="group-name">{{ row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="auth" label="权限标识" min-width="120" show-overflow-tooltip />
              <el-table-column prop="note" label="备注" min-width="150" show-overflow-tooltip>
                <template #default="{ row }">
                  {{ row.note || '-' }}
                </template>
              </el-table-column>
            </el-table>

            <!-- 用户组列表表格 -->
            <el-table
              v-else
              v-loading="loading"
              :data="groupList"
              highlight-current-row
              @current-change="handleCurrentChange"
              style="width: 100%"
              :height="350"
              :row-class-name="tableRowClassName"
            >
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column label="组ID" width="100" align="center">
                <template #default="{ row }">
                  {{ row.group_id || row.GroupId || row.id || row.Id }}
                </template>
              </el-table-column>
              <el-table-column label="组名称" min-width="150" show-overflow-tooltip>
                <template #default="{ row }">
                  <span class="group-name">{{ row.group_name || row.name || row.Name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="升级金额" width="120" align="right">
                <template #default="{ row }">
                  <span v-if="row.floor_price || row.FloorPrice" class="price-text">
                    ¥{{ row.floor_price || row.FloorPrice }}
                  </span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column label="下一级组ID" width="100" align="center">
                <template #default="{ row }">
                  {{ row.higher_level_id || row.HigherLevelId || '-' }}
                </template>
              </el-table-column>
              <el-table-column label="类型" width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="(row.fixed || row.Fixed) ? 'warning' : 'success'" size="small">
                    {{ (row.fixed || row.Fixed) ? '固定' : '可升级' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="成员数量" width="100" align="center">
                <template #default="{ row }">
                  <el-tag type="info" size="small" effect="plain">
                    {{ row.member_count || row.MemberCount || 0 }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container" v-if="total > 0">
              <el-pagination
                v-model:current-page="searchParams.page"
                v-model:page-size="searchParams.count"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                background
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
              />
            </div>
            
            <el-empty v-if="groupList.length === 0 && !loading" :description="adminGroup ? '暂无管理员组数据' : '暂无用户组数据'" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleConfirm"
          :disabled="!selectedGroup"
        >
          确定选择
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getUserGroupList } from '@/api/admin/user'
import { getAdminGroupList } from '@/api/admin/group'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  // 当前已选中的用户组ID（用于回显）
  currentGroupId: {
    type: [String, Number],
    default: ''
  },
  // 排除的用户组ID（避免选择自己作为下一级）
  excludeGroupId: {
    type: [String, Number],
    default: ''
  },
  // 是否请求管理员组接口
  adminGroup: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'confirm'])

// 响应式数据
const visible = ref(false)
const activeTab = ref('selectGroup')
const loading = ref(false)
const groupList = ref([])
const total = ref(0)
const selectedGroup = ref(null)

// 搜索参数
const searchParams = reactive({
  key: '',
  page: 1,
  count: 10
})

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    // 重置状态
    activeTab.value = 'selectGroup'
    selectedGroup.value = null
    searchParams.page = 1
    fetchGroupList()
  }
})

// 监听 visible 变化
watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 获取用户组列表
const fetchGroupList = async () => {
  loading.value = true
  groupList.value = []
  
  try {
    const params = {
      page: searchParams.page,
      count: searchParams.count
    }
    
    const res = props.adminGroup ? await getAdminGroupList(params) : await getUserGroupList(params)
    
    if (res.data.code === 200) {
      let responseData = res.data?.data || res.data
      
      if (props.adminGroup) {
        groupList.value = responseData?.data || []
        total.value = responseData?.total || groupList.value.length
      } else if (Array.isArray(responseData)) {
        groupList.value = responseData
        total.value = responseData.length
      } else if (responseData.list) {
        groupList.value = responseData.list || []
        total.value = responseData.total || responseData.all_count || 0
      } else if (responseData.data && Array.isArray(responseData.data)) {
        groupList.value = responseData.data
        total.value = responseData.all_count || responseData.data.length
      } else {
        groupList.value = []
        total.value = 0
      }
      
      // 过滤掉排除的用户组
      if (props.excludeGroupId) {
        groupList.value = groupList.value.filter(item => {
          const itemId = item.group_id || item.GroupId || item.id || item.Id
          return itemId !== props.excludeGroupId
        })
      }
      
      // 关键词过滤
      if (searchParams.key) {
        const keyword = searchParams.key.toLowerCase()
        groupList.value = groupList.value.filter(item => {
          const name = (item.group_name || item.name || item.Name || '').toLowerCase()
          const id = String(item.group_id || item.GroupId || item.id || item.Id)
          return name.includes(keyword) || id.includes(keyword)
        })
      }
      
      // 如果有当前选中的用户组ID，自动选中
      if (props.currentGroupId) {
        const currentGroup = groupList.value.find(item => {
          const itemId = item.group_id || item.GroupId || item.id || item.Id
          return itemId === props.currentGroupId
        })
        if (currentGroup) {
          selectedGroup.value = currentGroup
        }
      }
    } else {
      ElMessage.error(res.data.msg || '获取用户组列表失败')
    }
  } catch (error) {
    console.error('获取用户组列表失败:', error)
    ElMessage.error('获取用户组列表失败')
  } finally {
    loading.value = false
  }
}

// 处理标签页切换
const handleTabClick = (tab) => {
  if (tab.paneName === 'selectGroup') {
    fetchGroupList()
  }
}

// 搜索
const handleSearch = () => {
  searchParams.page = 1
  fetchGroupList()
}

// 重置搜索
const handleReset = () => {
  searchParams.key = ''
  searchParams.page = 1
  fetchGroupList()
}

// 分页处理
const handleSizeChange = (size) => {
  searchParams.count = size
  searchParams.page = 1
  fetchGroupList()
}

const handlePageChange = (page) => {
  searchParams.page = page
  fetchGroupList()
}

// 选择用户组
const handleCurrentChange = (row) => {
  selectedGroup.value = row
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (selectedGroup.value) {
    const selectedId = selectedGroup.value.group_id || selectedGroup.value.GroupId || selectedGroup.value.id || selectedGroup.value.Id
    const rowId = row.group_id || row.GroupId || row.id || row.Id
    if (rowId === selectedId) {
      return 'selected-row'
    }
  }
  return ''
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  selectedGroup.value = null
  groupList.value = []
  searchParams.key = ''
  searchParams.page = 1
  total.value = 0
}

// 确认选择
const handleConfirm = () => {
  if (selectedGroup.value) {
    emit('confirm', selectedGroup.value)
    handleClose()
  } else {
    ElMessage.warning('请选择一个用户组')
  }
}
</script>

<style scoped>
.user-group-selector {
  min-height: 450px;
}

.group-list-container {
  padding: 10px 0;
}

.filter-section {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 12px;
}

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

.price-text {
  color: #f56c6c;
  font-weight: 500;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 表格样式 */
:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.selected-row) {
  background-color: var(--el-color-primary-light-9) !important;
}

:deep(.selected-row td) {
  background-color: var(--el-color-primary-light-9) !important;
}

:deep(.el-table__body tr.current-row > td) {
  background-color: var(--el-color-primary-light-8) !important;
}

/* 标签页样式 */
:deep(.el-tabs__header) {
  margin-bottom: 16px;
}

:deep(.el-tabs__item) {
  font-size: 15px;
  padding: 0 24px;
}

:deep(.el-tabs__item.is-active) {
  font-weight: 600;
}
</style>
