<template>
  <view class="rooms-page">
    <!-- 顶部栏 -->
    <view class="page-header">
      <view class="header-content">
        <text class="page-title">房源管理</text>
        <view class="header-stats">
          <view class="stat-item">
            <text class="stat-value">{{ stats.totalCount }}</text>
            <text class="stat-label">房源总数</text>
          </view>
          <view class="stat-divider"></view>
          <view class="stat-item">
            <text class="stat-value">{{ stats.onSaleCount }}</text>
            <text class="stat-label">在售中</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-section">
      <scroll-view scroll-x class="filter-scroll" :show-scrollbar="false">
        <view class="filter-wrapper">
          <view
            v-for="filter in filters"
            :key="filter.value"
            :class="['filter-chip', { active: currentStatus === filter.value }]"
            @tap="filterBy(filter.value)"
          >
            <text class="filter-label">{{ filter.label }}</text>
            <view v-if="filter.badge && filter.badge > 0" class="filter-badge">{{ filter.badge }}</view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 房源列表 -->
    <scroll-view scroll-y class="rooms-container" @scrolltolower="loadMore">
      <view class="rooms-list">
        <!-- 房源卡片 -->
        <view
          v-for="room in roomList"
          :key="room.id"
          class="room-card"
          @tap="goEdit(room.id)"
        >
          <!-- 房源图片 -->
          <view class="room-image-wrapper">
            <image
              v-if="room.coverImage"
              class="room-image"
              :src="room.coverImage"
              mode="aspectFill"
            />
            <view v-else class="room-placeholder">
              <u-icon name="image" size="80" color="#D1D5DB"></u-icon>
            </view>

            <!-- 状态标签 -->
            <view class="image-badges">
              <view :class="['sale-badge', room.status === 'on_sale' ? 'on-sale' : 'off-sale']">
                <text class="badge-text">{{ room.status === 'on_sale' ? '在售' : '已下架' }}</text>
              </view>
              <view v-if="room.auditStatus === 'pending'" class="audit-badge pending">
                <u-icon name="clock" size="24" color="#F59E0B"></u-icon>
                <text class="badge-text">审核中</text>
              </view>
              <view v-else-if="room.auditStatus === 'rejected'" class="audit-badge rejected">
                <u-icon name="close-circle" size="24" color="#EF4444"></u-icon>
                <text class="badge-text">已拒绝</text>
              </view>
            </view>
          </view>

          <!-- 房源信息 -->
          <view class="room-info">
            <view class="room-header">
              <text class="room-name">{{ room.name }}</text>
              <view class="room-type-tag">
                <text class="type-text">{{ typeLabels[room.type] }}</text>
              </view>
            </view>

            <view class="room-meta">
              <view class="price-section">
                <text class="price-symbol">¥</text>
                <text class="price-value">{{ room.price }}</text>
                <text class="price-unit">/晚</text>
              </view>
              <view v-if="room.rating > 0" class="rating-section">
                <u-icon name="star-fill" size="28" color="#FBBF24"></u-icon>
                <text class="rating-text">{{ room.rating.toFixed(1) }}</text>
              </view>
            </view>

            <!-- 拒绝原因 -->
            <view v-if="room.auditStatus === 'rejected' && room.auditRejectReason" class="reject-reason">
              <u-icon name="info-circle" size="28" color="#EF4444"></u-icon>
              <text class="reason-text">{{ room.auditRejectReason }}</text>
            </view>

            <!-- 操作按钮 -->
            <view v-if="room.auditStatus !== 'pending'" class="room-actions" @tap.stop>
              <view class="action-button calendar" @tap="goCalendar(room.id)">
                <u-icon name="calendar" size="28" color="#3B82F6"></u-icon>
                <text class="action-text">日历</text>
              </view>
              <view class="action-button edit" @tap="goEdit(room.id)">
                <u-icon name="edit-pen" size="28" color="#8B5CF6"></u-icon>
                <text class="action-text">编辑</text>
              </view>
              <view
                v-if="room.status === 'on_sale'"
                class="action-button off-sale"
                @tap="handleOffSale(room.id)"
              >
                <u-icon name="eye-off" size="28" color="#EF4444"></u-icon>
                <text class="action-text">下架</text>
              </view>
              <view
                v-else
                class="action-button on-sale"
                @tap="handleOnSale(room.id)"
              >
                <u-icon name="eye" size="28" color="#10B981"></u-icon>
                <text class="action-text">上架</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="roomList.length === 0 && !loading" class="empty-container">
          <view class="empty-icon">
            <u-icon name="home" size="140" color="#D1D5DB"></u-icon>
          </view>
          <text class="empty-title">暂无房源</text>
          <text class="empty-desc">{{ getEmptyText() }}</text>
          <view class="empty-action" @tap="goCreate">
            <u-icon name="plus-circle" size="32" color="#FFFFFF"></u-icon>
            <text class="empty-action-text">立即添加房源</text>
          </view>
        </view>

        <!-- 加载状态 -->
        <loading-state v-if="loading && roomList.length === 0" text="加载中..." color="#667eea" />

        <!-- 加载更多 -->
        <loading-state v-if="loading && roomList.length > 0" size="small" text="加载中..." color="#667eea" />

        <!-- 没有更多 -->
        <view v-if="!loading && roomList.length > 0 && !hasMore" class="no-more">
          <text class="no-more-text">没有更多房源了</text>
        </view>
      </view>
    </scroll-view>

    <!-- 悬浮添加按钮 -->
    <view class="fab-button" @tap="goCreate">
      <u-icon name="plus" size="48" color="#FFFFFF"></u-icon>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { getMerchantRooms, removeMerchantRoom, updateMerchantRoom } from '@/api/seller/room';
import LoadingState from '@/components/base/LoadingState.vue';

const typeLabels: Record<string, string> = {
  hotel: '酒店',
  homestay: '民宿',
  apartment: '公寓',
  hostel: '青旅',
};

const filters = ref([
  { label: '全部', value: '', badge: 0 },
  { label: '在售中', value: 'on_sale', badge: 0 },
  { label: '已下架', value: 'off_sale', badge: 0 },
  { label: '审核中', value: 'pending', badge: 0 },
]);

const roomList = ref<any[]>([]);
const currentStatus = ref('');
const page = ref(1);
const loading = ref(false);
const hasMore = ref(true);

const stats = ref({
  totalCount: 0,
  onSaleCount: 0,
});

onShow(() => {
  fetchRooms(true);
  fetchStats();
});

async function fetchRooms(reset = false) {
  if (loading.value) return;
  if (!reset && !hasMore.value) return;

  loading.value = true;
  if (reset) {
    page.value = 1;
    hasMore.value = true;
    roomList.value = []; // 立即清空列表，避免显示旧数据
  }

  try {
    const params: any = {
      page: page.value,
      pageSize: 10,
    };

    if (currentStatus.value === 'pending') {
      params.auditStatus = 'pending';
    } else if (currentStatus.value) {
      params.status = currentStatus.value;
    }

    const res = await getMerchantRooms(params);
    const list = res.data?.list || [];
    roomList.value = reset ? list : [...roomList.value, ...list];
    hasMore.value = list.length >= 10;
    if (list.length > 0) {
      page.value++;
    }
  } catch (e) {
    console.error(e);
    uni.showToast({ title: '加载失败，请重试', icon: 'none' });
  } finally {
    loading.value = false;
  }
}

async function fetchStats() {
  try {
    const [allRes, onSaleRes] = await Promise.all([
      getMerchantRooms({ page: 1, pageSize: 1 }),
      getMerchantRooms({ page: 1, pageSize: 1, status: 'on_sale' }),
    ]);
    stats.value.totalCount = allRes.data?.total || 0;
    stats.value.onSaleCount = onSaleRes.data?.total || 0;

    // 更新筛选器徽章
    filters.value[0].badge = allRes.data?.total || 0;
    filters.value[1].badge = onSaleRes.data?.total || 0;
  } catch (e) {
    console.error(e);
  }
}

function filterBy(status: string) {
  if (currentStatus.value === status) return;
  currentStatus.value = status;
  fetchRooms(true);
}

function loadMore() {
  if (!hasMore.value || loading.value) return;
  fetchRooms();
}

function getEmptyText(): string {
  if (currentStatus.value === 'on_sale') return '暂无在售房源';
  if (currentStatus.value === 'off_sale') return '暂无已下架房源';
  if (currentStatus.value === 'pending') return '暂无审核中房源';
  return '还没有房源，点击下方按钮添加吧';
}

async function handleOffSale(id: number) {
  uni.showModal({
    title: '下架房源',
    content: '确认下架此房源？下架后客户将无法预订。',
    confirmText: '确认下架',
    cancelText: '取消',
    success: async (res) => {
      if (res.confirm) {
        try {
          await removeMerchantRoom(id);
          uni.showToast({ title: '已下架', icon: 'success' });
          fetchRooms(true);
          fetchStats();
        } catch (e: any) {
          uni.showToast({ title: e.message || '操作失败，请重试', icon: 'none' });
        }
      }
    },
  });
}

async function handleOnSale(id: number) {
  uni.showModal({
    title: '上架房源',
    content: '确认上架此房源？上架后客户可以预订。',
    confirmText: '确认上架',
    cancelText: '取消',
    success: async (res) => {
      if (res.confirm) {
        try {
          await updateMerchantRoom(id, { status: 'on_sale' });
          uni.showToast({ title: '已上架', icon: 'success' });
          fetchRooms(true);
          fetchStats();
        } catch (e: any) {
          uni.showToast({ title: e.message || '操作失败，请重试', icon: 'none' });
        }
      }
    },
  });
}

function goEdit(id: number) {
  uni.navigateTo({ url: `/pages/seller/room-form?id=${id}` });
}

function goCreate() {
  uni.navigateTo({ url: '/pages/seller/room-form' });
}

function goCalendar(id: number) {
  uni.navigateTo({ url: `/pages/seller/room-calendar?roomId=${id}` });
}
</script>

<style lang="scss" scoped>
@import '@/static/styles/common.scss';

.rooms-page {
  min-height: 100vh;
  background: #F9FAFB;
  display: flex;
  flex-direction: column;
  padding-bottom: 120rpx;
}

/* 顶部栏 */
.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 48rpx 32rpx 32rpx;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 40rpx;
  font-weight: 700;
  color: #FFFFFF;
  letter-spacing: 0.5rpx;
}

.header-stats {
  display: flex;
  align-items: center;
  gap: 24rpx;
  background: rgba(255, 255, 255, 0.15);
  padding: 16rpx 24rpx;
  border-radius: 40rpx;
  backdrop-filter: blur(10rpx);
}

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

.stat-value {
  font-size: 32rpx;
  font-weight: 700;
  color: #FFFFFF;
  line-height: 1;
}

.stat-label {
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.85);
}

.stat-divider {
  width: 2rpx;
  height: 32rpx;
  background: rgba(255, 255, 255, 0.3);
}

/* 筛选栏 */
.filter-section {
  background: #FFFFFF;
  border-bottom: 2rpx solid #F3F4F6;
}

.filter-scroll {
  white-space: nowrap;
}

.filter-wrapper {
  display: inline-flex;
  gap: 16rpx;
  padding: 24rpx 32rpx;
}

.filter-chip {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 8rpx;
  padding: 16rpx 32rpx;
  background: #F3F4F6;
  border-radius: 40rpx;
  transition: all 0.3s ease;

  &.active {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);

    .filter-label {
      color: #FFFFFF;
      font-weight: 600;
    }

    .filter-badge {
      background: #FFFFFF;
      color: #667eea;
    }
  }
}

.filter-label {
  font-size: 26rpx;
  color: #6B7280;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.filter-badge {
  min-width: 32rpx;
  height: 32rpx;
  padding: 0 8rpx;
  background: #EF4444;
  color: #FFFFFF;
  font-size: 20rpx;
  font-weight: 600;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}

/* 房源容器 */
.rooms-container {
  flex: 1;
  height: 0;
}

.rooms-list {
  padding: 24rpx 32rpx;
}

/* 房源卡片 */
.room-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  overflow: hidden;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  }
}

/* 房源图片 */
.room-image-wrapper {
  position: relative;
  width: 100%;
  height: 400rpx;
}

.room-image {
  width: 100%;
  height: 100%;
  background: #F3F4F6;
}

.room-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #F3F4F6 0%, #E5E7EB 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-badges {
  position: absolute;
  top: 20rpx;
  left: 20rpx;
  right: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.sale-badge {
  padding: 12rpx 24rpx;
  border-radius: 40rpx;
  backdrop-filter: blur(10rpx);
  display: flex;
  align-items: center;
  gap: 8rpx;

  &.on-sale {
    background: rgba(16, 185, 129, 0.9);
  }

  &.off-sale {
    background: rgba(107, 114, 128, 0.9);
  }
}

.audit-badge {
  padding: 12rpx 20rpx;
  border-radius: 40rpx;
  backdrop-filter: blur(10rpx);
  display: flex;
  align-items: center;
  gap: 8rpx;

  &.pending {
    background: rgba(245, 158, 11, 0.9);
  }

  &.rejected {
    background: rgba(239, 68, 68, 0.9);
  }
}

.badge-text {
  font-size: 24rpx;
  color: #FFFFFF;
  font-weight: 600;
  line-height: 1;
}

/* 房源信息 */
.room-info {
  padding: 32rpx;
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.room-name {
  flex: 1;
  font-size: 32rpx;
  font-weight: 600;
  color: #111827;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.room-type-tag {
  flex-shrink: 0;
  padding: 8rpx 20rpx;
  background: linear-gradient(135deg, #EFF6FF 0%, #DBEAFE 100%);
  border-radius: 20rpx;
}

.type-text {
  font-size: 24rpx;
  color: #3B82F6;
  font-weight: 600;
  line-height: 1;
}

.room-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.price-section {
  display: flex;
  align-items: baseline;
  gap: 4rpx;
}

.price-symbol {
  font-size: 28rpx;
  color: #EF4444;
  font-weight: 600;
}

.price-value {
  font-size: 44rpx;
  color: #EF4444;
  font-weight: 700;
  line-height: 1;
}

.price-unit {
  font-size: 24rpx;
  color: #9CA3AF;
  margin-left: 4rpx;
}

.rating-section {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 8rpx 16rpx;
  background: #FFFBEB;
  border-radius: 20rpx;
}

.rating-text {
  font-size: 26rpx;
  color: #D97706;
  font-weight: 600;
}

/* 拒绝原因 */
.reject-reason {
  display: flex;
  align-items: flex-start;
  gap: 12rpx;
  padding: 20rpx;
  background: #FEF2F2;
  border-radius: 16rpx;
  border-left: 6rpx solid #EF4444;
  margin-bottom: 24rpx;
}

.reason-text {
  flex: 1;
  font-size: 24rpx;
  color: #DC2626;
  line-height: 1.6;
}

/* 操作按钮 */
.room-actions {
  display: flex;
  gap: 16rpx;
}

.action-button {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  padding: 20rpx 16rpx;
  border-radius: 16rpx;
  transition: all 0.3s ease;

  &.calendar {
    background: #EFF6FF;
    border: 2rpx solid #DBEAFE;

    &:active {
      background: #DBEAFE;
    }
  }

  &.edit {
    background: #F5F3FF;
    border: 2rpx solid #EDE9FE;

    &:active {
      background: #EDE9FE;
    }
  }

  &.off-sale {
    background: #FEF2F2;
    border: 2rpx solid #FEE2E2;

    &:active {
      background: #FEE2E2;
    }
  }

  &.on-sale {
    background: #D1FAE5;
    border: 2rpx solid #A7F3D0;

    &:active {
      background: #A7F3D0;
    }
  }
}

.action-text {
  font-size: 24rpx;
  font-weight: 500;
  line-height: 1;

  .calendar & {
    color: #3B82F6;
  }

  .edit & {
    color: #8B5CF6;
  }

  .off-sale & {
    color: #EF4444;
  }

  .on-sale & {
    color: #10B981;
  }
}

/* 空状态 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 48rpx;
}

.empty-icon {
  margin-bottom: 32rpx;
  opacity: 0.5;
}

.empty-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #6B7280;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #9CA3AF;
  text-align: center;
  margin-bottom: 48rpx;
}

.empty-action {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 24rpx 48rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 48rpx;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.96);
  }
}

.empty-action-text {
  font-size: 28rpx;
  color: #FFFFFF;
  font-weight: 600;
}

.no-more {
  text-align: center;
  padding: 32rpx 0;
}

.no-more-text {
  font-size: 24rpx;
  color: #D1D5DB;
}

/* 悬浮添加按钮 */
.fab-button {
  position: fixed;
  right: 32rpx;
  bottom: 32rpx;
  width: 112rpx;
  height: 112rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
  z-index: 100;

  &:active {
    transform: scale(0.92);
    box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4);
  }
}
</style>
