<template>
  <view class="page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>
    </view>

    <!-- 搜索和筛选区域 -->
    <view class="search-filter-section">
      <view class="search-box">
        <uni-icons color="#7F7F7F" size="20" type="search"></uni-icons>
        <input
          v-model="searchKeyword"
          class="search-input"
          placeholder="搜索用户昵称"
          @input="onSearch"
        />
      </view>
      <view class="filter-btn" @click="showFilter">
        <text class="filter-text">筛选</text>
        <text class="filter-arrow">▼</text>
      </view>
    </view>

    <!-- 筛选面板 -->
    <view v-if="showFilterPanel" class="filter-panel">
      <view class="filter-item">
        <text class="filter-label">开始时间</text>
        <picker :value="filterParams.beginTime" mode="date" @change="onBeginTimeChange">
          <view class="picker-input">{{ filterParams.beginTime || '请选择' }}</view>
        </picker>
      </view>
      <view class="filter-item">
        <text class="filter-label">结束时间</text>
        <picker :value="filterParams.endTime" mode="date" @change="onEndTimeChange">
          <view class="picker-input">{{ filterParams.endTime || '请选择' }}</view>
        </picker>
      </view>
      <view class="filter-actions">
        <button class="filter-reset" @click="resetFilter">重置</button>
        <button class="filter-confirm" @click="applyFilter">确定</button>
      </view>
    </view>

    <!-- 用户列表 -->
    <view class="user-list">
      <view v-for="(user, index) in filteredUsers" :key="user.userId" class="user-card">
        <!-- 用户基本信息 -->
        <view class="user-info">
          <view class="avatar-placeholder"></view>
          <view class="user-details">
            <text class="username">{{ user.nickName }}</text>
            <view class="user-stats">
              <text class="amount">¥ {{ user.totalAmount }}</text>
              <text class="device-count">{{ user.deviceNum }}台</text>
            </view>
          </view>
        </view>

        <!-- 设备信息表格 -->
        <view class="device-table">
          <view class="table-header">
            <text class="header-cell">类型</text>
            <text class="header-cell">金额</text>
            <text class="header-cell">租赁</text>
            <text class="header-cell">周期</text>
            <text class="header-cell">到期</text>
          </view>

          <view
            v-for="(device, deviceIndex) in user.devices.slice(
              0,
              user.isExpanded ? user.devices.length : 1
            )"
            :key="deviceIndex"
            class="table-row"
          >
            <text class="table-cell">{{ device.type }}</text>
            <text class="table-cell amount-cell">¥ {{ device.amount }}</text>
            <text class="table-cell">{{ device.rentDate }}</text>
            <text class="table-cell period-cell">{{ device.period }}</text>
            <text class="table-cell expiry-cell">{{ device.expiryDate }}</text>
          </view>
        </view>

        <!-- 展开/收起按钮 -->
        <view class="expand-btn" @click="toggleExpand(index)">
          <text class="expand-text">
            {{ user.isExpanded ? '点击收起' : '点击展开' }}
          </text>
          <text class="expand-arrow">
            {{ user.isExpanded ? '▲' : '▼' }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { commonEnum } from '@/enum/commonEnum.js'
import { getUserList } from '@/api/user/user.js'
import UniIcons from '../../uni_modules/uni-icons/components/uni-icons/uni-icons.vue'

export default {
  components: { UniIcons },
  data() {
    return {
      searchKeyword: '',
      users: [],
      loading: false,
      showFilterPanel: false,
      filterParams: {
        beginTime: '',
        endTime: '',
        name: '',
      },
    }
  },
  onLoad() {
    this.fetchUserList()
  },
  onShow() {
    // 页面显示时刷新数据
    this.fetchUserList()
  },
  computed: {
    filteredUsers() {
      if (!this.searchKeyword) {
        return this.users
      }
      return this.users.filter(user =>
        user.nickName.toLowerCase().includes(this.searchKeyword.toLowerCase())
      )
    },
  },
  methods: {
    // 获取用户列表
    async fetchUserList() {
      this.loading = true
      try {
        // 构建查询参数
        const params = {}
        if (this.filterParams.beginTime) {
          params.beginTime = this.filterParams.beginTime + ' 00:00:00'
        }
        if (this.filterParams.endTime) {
          params.endTime = this.filterParams.endTime + ' 23:59:59'
        }
        if (this.filterParams.name) {
          params.name = this.filterParams.name
        }

        const response = await getUserList(params)
        if (response.code === 200 && response.data && Array.isArray(response.data)) {
          // 转换API数据格式为页面需要的格式
          this.users = response.data.map(user => ({
            ...user,
            isExpanded: false, // 默认收起
            // 将orders转换为devices格式
            devices: user.orders
              ? user.orders.map(order => ({
                  type: order.typeName || '未知设备',
                  amount: order.amount || 0,
                  rentDate: this.formatDate(order.leaseTime),
                  period: order.suitName || '未知周期',
                  expiryDate: this.formatDate(order.expirationTime),
                }))
              : [],
          }))
          console.log('用户列表获取成功:', this.users)
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        uni.showToast({
          title: '数据加载失败',
          icon: 'none',
        })
      } finally {
        this.loading = false
      }
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '未知'
      const date = new Date(dateString)
      return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`
    },

    onSearch() {
      // 搜索逻辑已在computed中处理
    },

    showFilter() {
      this.showFilterPanel = !this.showFilterPanel
    },

    onBeginTimeChange(e) {
      this.filterParams.beginTime = e.detail.value
    },

    onEndTimeChange(e) {
      this.filterParams.endTime = e.detail.value
    },

    resetFilter() {
      this.filterParams = {
        beginTime: '',
        endTime: '',
        name: '',
      }
      this.searchKeyword = ''
    },

    applyFilter() {
      this.filterParams.name = this.searchKeyword
      this.showFilterPanel = false
      this.fetchUserList()
    },

    toggleExpand(index) {
      this.users[index].isExpanded = !this.users[index].isExpanded
    },
  },
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 90vh;
  background: #f7f7f7;
  padding-bottom: 40rpx;
  position: relative;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20rpx;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.search-filter-section {
  display: flex;
  align-items: center;
  padding: 20rpx 20rpx 20rpx 20rpx;
  gap: 20rpx;
  background: white;
  margin-bottom: 20rpx;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background: #f3f5f6;
  border-radius: 999px;
  padding: 20rpx 50rpx;

  .search-input {
    padding: 0 20rpx;
    flex: 1;
    font-size: 28rpx;
  }
}

.filter-btn {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 10rpx;
  padding: 20rpx;

  .filter-text {
    font-size: 28rpx;
    margin-right: 10rpx;
  }

  .filter-arrow {
    font-size: 24rpx;
  }
}

.filter-panel {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.filter-label {
  font-size: 28rpx;
  color: #333;
  margin-right: 20rpx;
}

.picker-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  padding: 10rpx 20rpx;
  background: #f8f8f8;
}

.filter-actions {
  display: flex;
  justify-content: space-around;
  margin-top: 20rpx;
}

.filter-reset,
.filter-confirm {
  flex: 1;
  margin: 0 10rpx;
  padding: 15rpx 20rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  background: #ff6b35;
  color: white;
  font-weight: 500;
}

.filter-reset {
  background: #f0f0f0;
  color: #333;
}

.filter-confirm {
  background: #ff6b35;
}

.filter-panel {
  background: white;
  padding: 20rpx;
  border-top: 1rpx solid #eee;
  margin-bottom: 20rpx;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.filter-label {
  width: 120rpx;
  font-size: 28rpx;
  color: #333;
}

.picker-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 15rpx 20rpx;
  background: #f8f8f8;
}

.filter-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
}

.filter-reset,
.filter-confirm {
  flex: 1;
  padding: 20rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  text-align: center;
}

.filter-reset {
  background: #f0f0f0;
  color: #333;
}

.filter-confirm {
  background: #ff6b35;
  color: white;
}

.user-list {
  padding: 0 20rpx;
}

.user-card {
  background: white;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.avatar-placeholder {
  width: 80rpx;
  height: 80rpx;
  background: #e0e0e0;
  border-radius: 50%;
  margin-right: 20rpx;
}

.user-details {
  display: flex;
  justify-content: space-between;
  flex: 1;
}

.username {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.user-stats {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.amount {
  font-size: 32rpx;
  font-weight: 500;
  padding-right: 78rpx;
}

.device-count {
  font-size: 32rpx;
  font-weight: 500;
  color: #666;
}

.device-table {
  margin-bottom: 20rpx;
}

.table-header {
  display: flex;
  background: #f8f8f8;
  border-radius: 10rpx;
  padding: 20rpx 0;
  margin-bottom: 10rpx;
}

.header-cell {
  flex: 1;
  text-align: center;
  font-size: 24rpx;
  color: #666;
  font-weight: 500;
}

.table-row {
  display: flex;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.table-cell {
  flex: 1;
  text-align: center;
  font-size: 24rpx;
  color: #333;

  &.amount-cell {
    color: #ff6b35;
  }

  &.period-cell {
    color: #ff6b35;
  }

  &.expiry-cell {
    color: #ff4757;
  }
}

.expand-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;
  //color: #007aff;
  font-size: 28rpx;

  .expand-text {
    margin-right: 10rpx;
  }

  .expand-arrow {
    font-size: 24rpx;
  }
}

view {
  //border: red solid 1px;
}
</style>
