<template>
  <view class="page-review-create">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-content">
        <view class="navbar-left" @tap="goBack">
          <u-icon name="arrow-left" :size="20" color="#ffffff" />
        </view>
        <text class="navbar-title">评价订单</text>
        <view class="navbar-right"></view>
      </view>
    </view>

    <scroll-view scroll-y class="review-content">
      <!-- 订单信息卡片 -->
      <view class="section-card order-info-card">
        <view class="room-info">
          <image
            class="room-image"
            :src="orderInfo.roomCover || '/static/default-room.png'"
            mode="aspectFill"
          />
          <view class="room-detail">
            <text class="room-name">{{ orderInfo.roomName }}</text>
            <text class="merchant-name">{{ orderInfo.merchantName }}</text>
          </view>
        </view>
      </view>

      <!-- 评分卡片 -->
      <view class="section-card rating-card">
        <view class="card-header">
          <text class="card-title">整体评分</text>
          <text class="required-mark">*</text>
        </view>
        <view class="rating-stars">
          <view
            v-for="star in 5"
            :key="star"
            class="star-item"
            @tap="handleRating(star)"
          >
            <u-icon
              :name="star <= form.rating ? 'star-fill' : 'star'"
              :size="20"
              :color="star <= form.rating ? '#FFB800' : '#E5E5E5'"
            />
          </view>
        </view>
        <view class="rating-desc">
          <text class="desc-text">{{ getRatingDesc(form.rating) }}</text>
        </view>
      </view>

      <!-- 评价内容卡片 -->
      <view class="section-card content-card">
        <view class="card-header">
          <text class="card-title">评价内容</text>
          <text class="required-mark">*</text>
        </view>
        <textarea
          v-model="form.content"
          class="content-textarea"
          placeholder="分享您的入住体验，帮助其他用户做出更好的选择"
          placeholder-style="color: #CCCCCC"
          maxlength="500"
          :auto-height="false"
        />
        <view class="content-counter">
          <text class="counter-text">{{ form.content.length }}/500</text>
        </view>
      </view>

      <!-- 上传图片卡片 -->
      <view class="section-card images-card">
        <view class="card-header">
          <text class="card-title">上传图片</text>
          <text class="optional-mark">（选填，最多9张）</text>
        </view>
        <view class="images-grid">
          <view
            v-for="(img, index) in form.images"
            :key="index"
            class="image-item"
          >
            <image class="preview-image" :src="img" mode="aspectFill" />
            <view class="delete-btn" @tap.stop="deleteImage(index)">
              <u-icon name="close-circle-fill" :size="20" color="#FF4D4F" />
            </view>
          </view>
          <view
            v-if="form.images.length < 9"
            class="upload-btn"
            @tap="chooseImage"
          >
            <view class="upload-content">
              <u-icon name="camera-fill" :size="32" color="#CCCCCC" />
              <text class="upload-text">上传图片</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 匿名选项卡片 -->
      <view class="section-card anonymous-card">
        <view class="anonymous-row" @tap="toggleAnonymous">
          <view class="anonymous-left">
            <u-icon name="account" :size="18" color="#666" />
            <text class="anonymous-label">匿名评价</text>
          </view>
          <view class="anonymous-right">
            <view :class="['switch-btn', form.isAnonymous ? 'active' : '']">
              <view class="switch-dot"></view>
            </view>
          </view>
        </view>
        <view class="anonymous-tip">
          <u-icon name="info-circle" :size="14" color="#999" />
          <text class="tip-text">开启后，您的评价将不显示用户名和头像</text>
        </view>
      </view>

      <!-- 底部占位 -->
      <view class="bottom-placeholder"></view>
    </scroll-view>

    <!-- 底部提交按钮 -->
    <view class="submit-bar">
      <view class="submit-btn" :class="{ disabled: !canSubmit }" @tap="handleSubmit">
        <text class="submit-text">提交评价</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { createReview } from '@/api/user/review';
import { getOrderDetail } from '@/api/user/order';

const orderNo = ref('');
const orderInfo = ref({
  roomName: '',
  roomCover: '',
  merchantName: '',
});

const form = ref({
  rating: 0,
  content: '',
  images: [] as string[],
  isAnonymous: false,
});

const canSubmit = computed(() => {
  return form.value.rating > 0 && form.value.content.trim().length >= 10;
});

onMounted(() => {
  const pages = getCurrentPages();
  const page = pages[pages.length - 1] as any;
  orderNo.value = page.options?.orderNo || page.$page?.options?.orderNo;
  if (orderNo.value) fetchOrderInfo();
});

async function fetchOrderInfo() {
  try {
    const res = await getOrderDetail(orderNo.value);
    const order = res.data;
    orderInfo.value = {
      roomName: order.room?.name || '',
      roomCover: order.room?.coverImage || '',
      merchantName: order.merchant?.shopName || '',
    };
  } catch (e) {
    console.error('获取订单信息失败:', e);
    uni.showToast({ title: '加载失败', icon: 'none' });
  }
}

function handleRating(star: number) {
  form.value.rating = star;
}

function getRatingDesc(rating: number): string {
  const descMap: Record<number, string> = {
    1: '非常不满意',
    2: '不满意',
    3: '一般',
    4: '满意',
    5: '非常满意',
  };
  return rating > 0 ? descMap[rating] : '请选择评分';
}

function chooseImage() {
  const remainCount = 9 - form.value.images.length;
  uni.chooseImage({
    count: remainCount,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      // 实际项目中需要上传到服务器，这里模拟使用本地路径
      form.value.images.push(...res.tempFilePaths);
      uni.showToast({ title: '图片已添加', icon: 'success' });
    },
  });
}

function deleteImage(index: number) {
  uni.showModal({
    title: '提示',
    content: '确定删除这张图片？',
    success: (res) => {
      if (res.confirm) {
        form.value.images.splice(index, 1);
      }
    },
  });
}

function toggleAnonymous() {
  form.value.isAnonymous = !form.value.isAnonymous;
}

function goBack() {
  uni.navigateBack();
}

async function handleSubmit() {
  if (!canSubmit.value) {
    if (form.value.rating === 0) {
      uni.showToast({ title: '请选择评分', icon: 'none' });
      return;
    }
    if (form.value.content.trim().length < 10) {
      uni.showToast({ title: '评价内容至少10个字', icon: 'none' });
      return;
    }
    return;
  }

  uni.showLoading({ title: '提交中...' });
  try {
    await createReview(orderNo.value, {
      rating: form.value.rating,
      content: form.value.content.trim(),
      images: form.value.images,
      isAnonymous: form.value.isAnonymous,
    });
    uni.hideLoading();
    uni.showToast({
      title: '评价成功',
      icon: 'success',
      duration: 1500,
    });
    setTimeout(() => {
      // 通过事件通知订单详情页刷新
      uni.$emit('reviewSubmitted', { orderNo: orderNo.value });
      uni.navigateBack();
    }, 1500);
  } catch (e: any) {
    uni.hideLoading();
    uni.showToast({
      title: e.message || '提交失败',
      icon: 'none',
    });
  }
}
</script>

<style lang="scss" scoped>
.page-review-create {
  min-height: 100vh;
  background: linear-gradient(180deg, #FFF5F0 0%, #F5F7FA 100%);
  display: flex;
  flex-direction: column;
}

/* ========== 自定义导航栏 ========== */
.custom-navbar {
  background: linear-gradient(135deg, #FF8C5A 0%, #FF6B35 100%);
  padding: 0 24rpx;
}

.navbar-content {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar-left,
.navbar-right {
  width: 80rpx;
  display: flex;
  align-items: center;
}

.navbar-left {
  justify-content: flex-start;
  padding: 12rpx;
  margin-left: -12rpx;
  transition: opacity 0.3s ease;

  &:active {
    opacity: 0.6;
  }
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
}

/* ========== 评价内容 ========== */
.review-content {
  flex: 1;
  overflow-y: auto;
  padding: 24rpx 0;
}

/* ========== 卡片通用样式 ========== */
.section-card {
  margin: 0 24rpx 16rpx;
  background: #ffffff;
  border-radius: 20rpx;
  padding: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-bottom: 24rpx;
}

.card-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.required-mark {
  font-size: 28rpx;
  color: #FF4D4F;
}

.optional-mark {
  font-size: 24rpx;
  color: #999;
}

/* ========== 订单信息卡片 ========== */
.order-info-card {
  padding: 20rpx;
}

.room-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.room-image {
  width: 120rpx;
  height: 90rpx;
  border-radius: 12rpx;
  background: #F5F7FA;
  flex-shrink: 0;
}

.room-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  min-width: 0;
}

.room-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #1A1A1A;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.merchant-name {
  font-size: 24rpx;
  color: #999;
}

/* ========== 评分卡片 ========== */
.rating-card {
  text-align: center;
}

.rating-stars {
  display: flex;
  justify-content: center;
  gap: 16rpx;
  margin-bottom: 16rpx;
}

.star-item {
  padding: 8rpx;
  transition: transform 0.2s ease;

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

.rating-desc {
  padding: 12rpx 0;
}

.desc-text {
  font-size: 26rpx;
  color: #666;
}

/* ========== 评价内容卡片 ========== */
.content-card {
  .card-header {
    margin-bottom: 16rpx;
  }
}

.content-textarea {
  width: 100%;
  min-height: 240rpx;
  padding: 20rpx;
  background: #F5F7FA;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #1A1A1A;
  line-height: 1.6;
  box-sizing: border-box;
}

.content-counter {
  display: flex;
  justify-content: flex-end;
  margin-top: 12rpx;
}

.counter-text {
  font-size: 24rpx;
  color: #999;
}

/* ========== 上传图片卡片 ========== */
.images-card {
  .card-header {
    margin-bottom: 16rpx;
  }
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.image-item {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  border-radius: 16rpx;
  overflow: hidden;
  background: #F5F7FA;
}

.preview-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 44rpx;
  height: 44rpx;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(4rpx);
  transition: all 0.2s ease;

  &:active {
    transform: scale(0.9);
    background: rgba(0, 0, 0, 0.8);
  }
}

.upload-btn {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  background: #F5F7FA;
  border: 2rpx dashed #D9D9D9;
  border-radius: 16rpx;
  transition: all 0.3s ease;
  overflow: hidden;

  &:active {
    background: #E8E8E8;
    border-color: #BFBFBF;
  }
}

.upload-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
}

.upload-text {
  font-size: 22rpx;
  color: #999;
  white-space: nowrap;
}

/* ========== 匿名选项卡片 ========== */
.anonymous-card {
  padding: 20rpx 24rpx;
}

.anonymous-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12rpx 0;
}

.anonymous-left {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.anonymous-label {
  font-size: 28rpx;
  color: #1A1A1A;
  font-weight: 500;
}

.switch-btn {
  width: 88rpx;
  height: 48rpx;
  background: #E5E5E5;
  border-radius: 24rpx;
  position: relative;
  transition: background 0.3s ease;

  &.active {
    background: #52C41A;

    .switch-dot {
      transform: translateX(40rpx);
    }
  }
}

.switch-dot {
  position: absolute;
  top: 4rpx;
  left: 4rpx;
  width: 40rpx;
  height: 40rpx;
  background: #ffffff;
  border-radius: 50%;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.anonymous-tip {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-top: 12rpx;
  padding: 12rpx 16rpx;
  background: #F5F7FA;
  border-radius: 8rpx;
}

.tip-text {
  font-size: 24rpx;
  color: #999;
  line-height: 1.5;
}

/* ========== 底部占位 ========== */
.bottom-placeholder {
  height: 160rpx;
}

/* ========== 底部提交按钮 ========== */
.submit-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  padding: 24rpx 32rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -8rpx 24rpx rgba(0, 0, 0, 0.08);
  z-index: 100;
}

.submit-btn {
  width: 100%;
  height: 96rpx;
  background: linear-gradient(135deg, #FF8C5A 0%, #FF6B35 100%);
  border-radius: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 16rpx rgba(255, 107, 53, 0.3);
  transition: all 0.3s ease;

  &:active:not(.disabled) {
    transform: scale(0.98);
    box-shadow: 0 4rpx 12rpx rgba(255, 107, 53, 0.35);
  }

  &.disabled {
    background: linear-gradient(135deg, #D9D9D9 0%, #BFBFBF 100%);
    box-shadow: none;
    opacity: 0.7;
  }
}

.submit-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
  letter-spacing: 2rpx;
}
</style>
