<template>
  <el-dialog
    v-model="visible"
    title="下级用户"
    width="1000px"
    :close-on-click-modal="false"
    @close="handleClose"
    @open="handleOpen"
  >
    <div class="user-info" v-if="user">
      <el-avatar :src="user.avatar" :size="40">
        <el-icon><User /></el-icon>
      </el-avatar>
      <div class="user-detail">
        <div class="nickname">{{ user.nickname || '-' }}</div>
        <div class="uid">UID: {{ user.uid || '-' }} (ID: {{ user.id }})</div>
      </div>
      <div class="team-stats">
        <el-statistic title="下级总数" :value="total" />
      </div>
    </div>

    <!-- 操作栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleExport" :loading="exportLoading">
        <el-icon><Download /></el-icon>导出Excel
      </el-button>
    </div>

    <!-- 下级用户列表 -->
    <el-table :data="teamList" v-loading="loading" border stripe max-height="400">
      <el-table-column label="用户信息" min-width="200">
        <template #default="{ row }">
          <div class="member-info">
            <el-avatar :src="row.avatar" :size="40">
              <el-icon><User /></el-icon>
            </el-avatar>
            <div class="member-detail">
              <div class="member-nickname">{{ row.nickname || '-' }}</div>
              <div class="member-uid">UID: {{ row.uid || '-' }} (ID: {{ row.id }})</div>
              <div class="member-mobile" v-if="row.mobile">{{ row.mobile }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="balance" label="余额" width="100" align="right">
        <template #default="{ row }">
          <span class="money">¥{{ row.balance?.toFixed(2) || '0.00' }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="integral" label="积分" width="80" align="right">
        <template #default="{ row }">
          {{ row.integral || 0 }}
        </template>
      </el-table-column>

      <el-table-column prop="diamond" label="钻石" width="80" align="right">
        <template #default="{ row }">
          {{ row.diamond || 0 }}
        </template>
      </el-table-column>

      <el-table-column prop="totalConsumption" label="总消费" width="120" align="right">
        <template #default="{ row }">
          <span class="money">¥{{ row.totalConsumption?.toFixed(2) || '0.00' }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="vipLevel" label="VIP" width="80" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.vipLevel > 0" type="warning" size="small">VIP{{ row.vipLevel }}</el-tag>
          <span v-else class="text-muted">-</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
            {{ row.status === 1 ? '正常' : '封禁' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="createdAt" label="注册时间" width="170" />
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="currentPageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      class="pagination"
    />

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { User, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getSubordinateUsers, type UserListItem } from '@/api/business/user'

interface Props {
  modelValue: boolean
  user: UserListItem | null
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const loading = ref(false)
const exportLoading = ref(false)
const teamList = ref<UserListItem[]>([])
const total = ref(0)
const currentPage = ref(1)
const currentPageSize = ref(20)

// 获取数据
const fetchData = async () => {
  if (!props.user) return

  loading.value = true
  try {
    const res = await getSubordinateUsers(props.user.id, currentPage.value, currentPageSize.value)
    teamList.value = res.data?.list || []
    total.value = res.data?.total || 0
  } catch (error) {
    console.error('获取下级用户失败', error)
    teamList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchData()
}

const handleSizeChange = (size: number) => {
  currentPageSize.value = size
  currentPage.value = 1
  fetchData()
}

// 导出Excel
const handleExport = async () => {
  if (!props.user) return

  exportLoading.value = true
  try {
    // 获取所有数据用于导出
    const res = await getSubordinateUsers(props.user.id, 1, 10000)
    const data = res.data?.list || []

    if (data.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }

    // 构建CSV内容
    const headers = ['UID', 'ID', '昵称', '手机号', '余额', '积分', '钻石', '总消费', 'VIP等级', '状态', '注册时间']
    const rows = data.map(item => [
      item.uid || '-',
      item.id,
      item.nickname || '-',
      item.mobile || '-',
      item.balance?.toFixed(2) || '0.00',
      item.integral || 0,
      item.diamond || 0,
      item.totalConsumption?.toFixed(2) || '0.00',
      item.vipLevel > 0 ? `VIP${item.vipLevel}` : '-',
      item.status === 1 ? '正常' : '封禁',
      item.createdAt || '-'
    ])

    // 添加BOM以支持中文
    const BOM = '\uFEFF'
    const csvContent = BOM + [headers.join(','), ...rows.map(row => row.join(','))].join('\n')

    // 创建下载链接
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `下级用户_${props.user.id}_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    URL.revokeObjectURL(link.href)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败', error)
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 对话框打开时
const handleOpen = () => {
  currentPage.value = 1
  currentPageSize.value = 20
  fetchData()
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 16px;
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
}

.nickname {
  font-weight: 500;
  font-size: 14px;
}

.uid {
  font-size: 12px;
  color: #909399;
}

.team-stats {
  padding: 0 20px;
}

.toolbar {
  margin-bottom: 16px;
}

.member-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.member-detail {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.member-nickname {
  font-weight: 500;
}

.member-uid {
  font-size: 12px;
  color: #909399;
}

.member-mobile {
  font-size: 12px;
  color: #606266;
}

.money {
  color: #e6a23c;
  font-weight: 500;
}

.text-muted {
  color: #909399;
}

.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}
</style>
