<template>
  <div class="page-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部" clearable>
            <el-option label="全部" value="" />
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="全部" clearable>
            <el-option label="全部" value="" />
            <el-option label="管理员" value="admin" />
            <el-option label="用户" value="user" />
            <el-option label="访客" value="guest" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="RefreshRight" @click="handleReset">重置</el-button>
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-wrapper">
      <m-table
        :options="tableOptions"
        :data="tableData"
        :isLoading="isLoading"
        pagination
        stripe
        border
        :total="total"
        :currentPage="queryForm.page"
        :pageSize="queryForm.size"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <!-- 自定义用户名列 -->
        <template #username="{ scope }">
          <el-link type="primary" @click="handleEdit(scope.row)">
            {{ scope.row.username }}
          </el-link>
        </template>

        <!-- 自定义状态列 -->
        <template #status="{ scope }">
          <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
            {{ scope.row.status === '1' ? '正常' : '禁用' }}
          </el-tag>
        </template>

        <!-- 自定义角色列 -->
        <template #role="{ scope }">
          <el-tag :type="getRoleTagType(scope.row.role)">
            {{ getRoleLabel(scope.row.role) }}
          </el-tag>
        </template>

        <!-- 操作列 -->
        <template #action="{ scope }">
          <el-button type="primary" link :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </m-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search, RefreshRight } from '@element-plus/icons-vue'
import MTable from '@/components/mTable/index.vue'
import type { TableOptions } from '@/components/mTable/types'

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  status: '',
  role: '',
  dateRange: null as [string, string] | null
})

// 分页参数
const queryForm = reactive({
  page: 1,
  size: 15
})

const isLoading = ref(false)
const total = ref(0)
const tableData = ref<any[]>([])

// 表格配置
const tableOptions: TableOptions[] = [
  {
    prop: 'id',
    label: 'ID',
    width: 80,
    align: 'center'
  },
  {
    prop: 'username',
    label: '用户名',
    minWidth: 120,
    slot: 'username'
  },
  {
    prop: 'email',
    label: '邮箱',
    minWidth: 180,
    showOmission: true
  },
  {
    prop: 'phone',
    label: '手机号',
    width: 130
  },
  {
    prop: 'role',
    label: '角色',
    width: 100,
    align: 'center',
    slot: 'role'
  },
  {
    prop: 'status',
    label: '状态',
    width: 80,
    align: 'center',
    slot: 'status'
  },
  {
    prop: 'createdAt',
    label: '创建时间',
    width: 180,
    align: 'center',
    dateName: 'createdAt',
    formatStr: 'yyyy-MM-dd HH:mm:ss'
  },
  {
    prop: 'remark',
    label: '备注',
    minWidth: 150,
    truncateText: true,
    truncateTextLength: 20
  },
  {
    label: '操作',
    width: 150,
    align: 'center',
    fixed: 'right',
    action: true
  }
]

// 生成 Mock 数据
function generateMockData() {
  const roles = ['admin', 'user', 'guest']
  const statuses = ['0', '1']
  const remarks = [
    '这是一段很长的备注信息用于测试文本截断功能',
    '普通备注',
    '系统管理员账号',
    '测试用户',
    '',
    '需要审核的用户账号',
    'VIP用户'
  ]

  const data: any[] = []
  for (let i = 1; i <= 58; i++) {
    data.push({
      id: i,
      username: `user_${String(i).padStart(3, '0')}`,
      email: `user${i}@example.com`,
      phone: `138${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
      role: roles[Math.floor(Math.random() * roles.length)],
      status: statuses[Math.floor(Math.random() * statuses.length)],
      createdAt: Date.now() - Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000),
      remark: remarks[Math.floor(Math.random() * remarks.length)]
    })
  }
  return data
}

// 全部数据
const allData = ref<any[]>([])

// 加载数据
async function loadData() {
  isLoading.value = true

  // 模拟接口延迟
  await new Promise((resolve) => setTimeout(resolve, 500))

  // 过滤数据
  let filtered = [...allData.value]

  if (searchForm.username) {
    filtered = filtered.filter((item) => item.username.toLowerCase().includes(searchForm.username.toLowerCase()))
  }
  if (searchForm.email) {
    filtered = filtered.filter((item) => item.email.toLowerCase().includes(searchForm.email.toLowerCase()))
  }
  if (searchForm.status) {
    filtered = filtered.filter((item) => item.status === searchForm.status)
  }
  if (searchForm.role) {
    filtered = filtered.filter((item) => item.role === searchForm.role)
  }

  total.value = filtered.length

  // 分页
  const start = (queryForm.page - 1) * queryForm.size
  const end = start + queryForm.size
  tableData.value = filtered.slice(start, end)

  isLoading.value = false
}

// 角色标签类型
function getRoleTagType(role: string) {
  const map: Record<string, string> = {
    admin: 'danger',
    user: 'primary',
    guest: 'info'
  }
  return map[role] || 'info'
}

// 角色标签文本
function getRoleLabel(role: string) {
  const map: Record<string, string> = {
    admin: '管理员',
    user: '用户',
    guest: '访客'
  }
  return map[role] || role
}

// 查询
function handleSearch() {
  queryForm.page = 1
  loadData()
}

// 重置
function handleReset() {
  searchForm.username = ''
  searchForm.email = ''
  searchForm.status = ''
  searchForm.role = ''
  searchForm.dateRange = null
  queryForm.page = 1
  loadData()
}

// 新增
function handleAdd() {
  ElMessage.info('点击了新增按钮')
}

// 编辑
function handleEdit(row: any) {
  ElMessage.info(`编辑用户: ${row.username}`)
}

// 删除
async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm(`确定要删除用户 "${row.username}" 吗？`, '提示', {
      type: 'warning'
    })
    ElMessage.success(`删除用户 ${row.username} 成功`)
    loadData()
  } catch {
    // 取消删除
  }
}

// 分页大小改变
function handleSizeChange(val: number) {
  queryForm.size = val
  queryForm.page = 1
  loadData()
}

// 页码改变
function handleCurrentChange(val: number) {
  queryForm.page = val
  loadData()
}

onMounted(() => {
  allData.value = generateMockData()
  loadData()
})
</script>

<style lang="scss" scoped>
.page-container {
}

.search-form {
  flex-shrink: 0;
  margin-bottom: 16px;
  padding: 16px;
  background: #f5f7fa;

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

  :deep(.el-input),
  :deep(.el-select) {
    width: 160px;
  }

  :deep(.el-date-editor--daterange) {
    width: 280px;

    .el-range-input {
      width: 90px;
    }

    .el-range-separator {
      width: 30px;
    }
  }

  :deep(.el-button--primary) {
    background-color: #4f46e5;
    border-color: #4f46e5;

    &:hover,
    &:focus {
      background-color: #6366f1;
      border-color: #6366f1;
    }
  }
}

.table-wrapper {
  flex: 1;
  min-height: 0;
  overflow: hidden;

  :deep(.el-table) {
    --el-table-row-hover-bg-color: #f0f0ff;

    .el-table__row--striped td.el-table__cell {
      background-color: #f8f9fc;
    }

    .el-table__header th {
      background-color: #f5f7fa;
      color: #333;
      font-weight: 600;
    }

    .el-link--primary {
      color: #4f46e5;

      &:hover {
        color: #6366f1;
      }
    }

    .el-button--primary.is-link {
      color: #4f46e5;

      &:hover {
        color: #6366f1;
      }
    }
  }
}

:deep(.pagination) {
  padding-top: 16px;

  .el-pagination {
    .el-pager li.is-active {
      background-color: #4f46e5;
      color: #fff;
    }

    .el-pager li:not(.is-active):hover {
      color: #4f46e5;
    }
  }
}
</style>
