<template>
	<view class="user-list-page">
		<NavBar title="用户列表" bgColor="#fff" color="#000"></NavBar>
		<!-- 顶部操作栏 -->
		<view class="action-bar">
			<view class="search-box">
				<uni-icons type="search" size="14" color="#999"></uni-icons>
				<input type="text" v-model="searchValue" placeholder="搜索姓名/手机号" class="search-input" confirm-type="search" @confirm="onSearch" />
			</view>
			<picker :range="statusOptions" range-key="label" @change="onStatusFilterChange">
				<view class="filter-btn">
					<text>{{ statusOptions[currentStatusOption].label }}</text>
					<uni-icons type="bottom" size="12" color="#666"></uni-icons>
				</view>
			</picker>
			<button size="mini" class="add-btn" @click="goToAdd">+ 新增</button>
		</view>

		<!-- 用户列表 -->
		<view class="list-container">
			<view class="user-card" v-for="user in users" :key="user.id">
				<view class="user-header">
					<image :src="user.avatarUrl || '/static/default-avatar.png'" class="user-avatar" mode="aspectFill"></image>
					<view class="user-info-main">
						<text class="user-name">{{ user.name }}</text>
						<text class="phone-row">{{ user.phone }}</text>
					</view>
					<view class="user-status">
						<switch :checked="user.status === 0" color="#ff9800" style="transform: scale(0.6);"
							@change="(e) => onStatusChange(e, user)" />
						<text class="status-text">{{ user.status === 0 ? '正常' : '禁用' }}</text>
					</view>
				</view>

				<view class="user-body">
					<view class="info-row">
						<text class="label">住址:</text>
						<text class="value">{{ user.address || '-' }}</text>
					</view>
					<view class="info-grid">
						<view class="grid-cell" @click="goToPetList(user)">
							<text class="label">关联宠物</text>
							<text class="value text-warning">{{ user.petCount || 0 }}只</text>
						</view>
						<view class="grid-cell" @click="goToOrderList(user)">
							<text class="label">订单数量</text>
							<text class="value">{{ user.orderCount || 0 }}单</text>
						</view>
					</view>
					<view class="source-box" v-if="user.source || user.createTime">
						<text class="source-tag" v-if="user.source">{{ user.source }}</text>
						<text class="create-time" v-if="user.createTime">创建时间: {{ user.createTime }}</text>
					</view>
				</view>

				<view class="card-actions">
					<button size="mini" class="action-btn" @click.stop="goToDetail(user)">详情</button>
					<button size="mini" class="action-btn" @click.stop="goToEdit(user)">编辑</button>
				</view>
			</view>

			<view v-if="users.length === 0" style="text-align: center; color: #999; padding: 50rpx 0; font-size: 28rpx;">
				暂无用户数据
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { onShow, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import NavBar from '@/components/nav-bar/index.vue'
import { listCustomer, changeCustomerStatus } from '@/api/archieves/customer'

const searchValue = ref('')
const users = ref([])

const statusOptions = [{ label: '状态', value: undefined }, { label: '正常', value: 0 }, { label: '停用', value: 1 }]
const currentStatusOption = ref(0) // Default to 全部状态

const onStatusFilterChange = (e) => {
    currentStatusOption.value = e.detail.value
    onSearch()
}

const pageNum = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)

const loadUsers = async (isLoadMore = false) => {
	try {
        uni.showNavigationBarLoading()
        const res = await listCustomer({
            pageNum: pageNum.value,
            pageSize: pageSize.value,
            keyword: searchValue.value,
            status: statusOptions[currentStatusOption.value].value
        })
        const rows = res?.rows || []
        if (isLoadMore) {
            users.value = [...users.value, ...rows]
        } else {
            users.value = rows
        }
        hasMore.value = users.value.length < (res?.total || 0)
	} catch (error) {
		console.error('获取用户列表失败', error)
		uni.showToast({ title: typeof error === 'string' ? error : '获取用户列表失败', icon: 'none' })
	} finally {
        uni.hideNavigationBarLoading()
        uni.stopPullDownRefresh()
    }
}

onShow(() => {
    pageNum.value = 1
    loadUsers()
})

onPullDownRefresh(() => {
    pageNum.value = 1
    loadUsers()
})

onReachBottom(() => {
    if (hasMore.value) {
        pageNum.value++
        loadUsers(true)
    }
})

const onSearch = () => {
    pageNum.value = 1
    loadUsers()
}

const goToAdd = () => uni.navigateTo({ url: '/pages/my/user/add/index' })
const goToDetail = (user) => uni.navigateTo({ url: `/pages/my/user/detail/index?id=${user.id}` })
const goToEdit = (user) => uni.navigateTo({ url: `/pages/my/user/edit/index?id=${user.id}` })
const goToPetList = (user) => uni.navigateTo({ url: `/pages/my/pet/list/index?userId=${user.id}` })
const goToOrderList = (user) => uni.reLaunch({ url: '/pages/order/list/index' })

const onStatusChange = (e, user) => {
    const originalStatus = user.status
    const targetStatus = e.detail.value ? 0 : 1
    const text = targetStatus === 0 ? '启用' : '停用'

    uni.showModal({
        title: '提示',
        content: `确认要${text}该用户吗？`,
        success: async (res) => {
            if (res.confirm) {
                try {
                    uni.showLoading({ title: '处理中...' })
                    await changeCustomerStatus(user.id, targetStatus)
                    uni.hideLoading()
                    user.status = targetStatus
                    uni.showToast({ title: `已${text}`, icon: 'success' })
                } catch(err) {
                    uni.hideLoading()
                    uni.showToast({ title: typeof err === 'string' ? err : '操作失败', icon: 'none' })
                    // 恢复源数据渲染，利用 setTimeout 强制触发 vue 的重算
                    user.status = targetStatus
                    setTimeout(() => { user.status = originalStatus }, 50)
                }
            } else {
                // 用户取消，恢复 switch
                user.status = targetStatus
                setTimeout(() => { user.status = originalStatus }, 50)
            }
        }
    })
}
</script>

<style lang="scss" scoped>
.user-list-page {
	min-height: 100vh;
	background: #f2f2f2;
	padding-bottom: 40rpx;
}

.action-bar {
	display: flex;
	align-items: center;
	padding: 20rpx 24rpx;
	background: #fff;
	gap: 16rpx;
}

.search-box {
	flex: 1;
	height: 64rpx;
	display: flex;
	align-items: center;
	background: #f5f5f5;
	border-radius: 32rpx;
	padding: 0 24rpx;
	gap: 12rpx;
}

.search-input {
	flex: 1;
	font-size: 26rpx;
	background: transparent;
	height: 100%;
}

.filter-btn {
	height: 64rpx;
	display: flex;
	align-items: center;
	gap: 8rpx;
	background: #f5f5f5;
	border-radius: 32rpx;
	padding: 0 24rpx;
	font-size: 24rpx;
	color: #666;
}

.add-btn {
	height: 64rpx;
	line-height: 64rpx;
	font-size: 24rpx;
	font-weight: bold;
	background: linear-gradient(90deg, #ffd53f, #ff9500);
	color: #fff;
	border: none;
	border-radius: 32rpx;
	padding: 0 28rpx;
	margin: 0;
	white-space: nowrap;
	display: flex;
	align-items: center;
	justify-content: center;

	&::after {
		border: none;
	}
}

.list-container {
	padding: 24rpx;
}

.user-card {
	background: #fff;
	border-radius: 24rpx;
	padding: 28rpx;
	margin-bottom: 24rpx;
}

.user-header {
	display: flex;
	align-items: center;
	margin-bottom: 24rpx;
	padding-bottom: 24rpx;
	border-bottom: 2rpx solid #EEEEEE;
}

.user-avatar {
	width: 88rpx;
	height: 88rpx;
	border-radius: 50%;
	background: #f0f0f0;
	margin-right: 24rpx;
}

.user-info-main {
	flex: 1;
}

.user-name {
	display: block;
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 8rpx;
}

.phone-row {
	display: block;
	font-size: 26rpx;
	color: #666;
}

.user-status {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 4rpx;
}

.status-text {
	font-size: 20rpx;
	color: #ff9800;
}

.user-body {
	font-size: 26rpx;
}

.info-row {
	display: flex;
	margin-bottom: 16rpx;
}

.label {
	color: #999;
	width: 100rpx;
	flex-shrink: 0;
}

.value {
	color: #333;
	flex: 1;
}

.info-grid {
	display: flex;
	background: transparent;
	border: 2rpx solid #EEEEEE;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.grid-cell {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8rpx;
}

.grid-cell .label {
	width: auto;
	font-size: 24rpx;
}

.grid-cell .value {
	font-size: 30rpx;
	font-weight: bold;
}

.text-warning {
	color: #ff9800;
}

.source-box {
	background: transparent;
	padding: 16rpx;
	border-radius: 12rpx;
	border: 1rpx solid #f9e8d4;
}

.source-tag {
	display: block;
	color: #ff9800;
	font-weight: bold;
	font-size: 24rpx;
	margin-bottom: 8rpx;
}

.create-time {
	font-size: 22rpx;
	color: #a1887f;
}

.card-actions {
	display: flex;
	justify-content: center;
	gap: 40rpx;
	margin-top: 24rpx;
	padding-top: 24rpx;
	border-top: 2rpx dashed #EEEEEE;
}

.action-btn {
	width: 160rpx;
	height: 64rpx;
	line-height: 60rpx;
	border: 1rpx solid #e0e0e0;
	color: #666;
	font-size: 24rpx;
	background: transparent;
	border-radius: 12rpx;
	padding: 0;
	margin: 0;
	display: flex;
	align-items: center;
	justify-content: center;

	&::after {
		border: none;
	}
}
</style>
