<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showLoadingToast, closeToast, showFailToast, showToast, showImagePreview } from 'vant'
import { getGoodsInfo, type ShopGoodsDTO } from '@/common/apis/manage/goods'
import type { BorrowReturnDynamicDTO, SearchBorrowReturnDynamicQuery } from '@/common/apis/manage/order'
import { getBorrowReturnDynamicApi } from '@/common/apis/manage/order'

const route = useRoute()
const router = useRouter()

const goodsId = ref<number | null>(null)
const goods = ref<ShopGoodsDTO>({})
const loading = ref(false);
const activeTab = ref(0);

// 商品动态相关状态
const dynamicList = ref<BorrowReturnDynamicDTO[]>([])
const dynamicLoading = ref(false)
const dynamicFinished = ref(false)
const dynamicQueryParams = ref<SearchBorrowReturnDynamicQuery>({
  pageNum: 1,
  pageSize: 10
})
const dynamicTotal = ref(0)
const hasMoreDynamic = computed(() => dynamicList.value.length < dynamicTotal.value)

// 获取商品详情
const fetchGoodsDetail = async (id: number) => {
  try {
    loading.value = true
    const toast = showLoadingToast({ message: '加载中...', duration: 0 })
    const res = await getGoodsInfo(id)
    goods.value = res.data
    closeToast()
    // 加载商品动态
    resetDynamicQuery()
    fetchDynamicList()
  } catch (error) {
    console.error('加载商品详情失败:', error)
    showFailToast('加载失败')
    router.back()
  } finally {
    loading.value = false
  }
}

// 跳转到编辑页面
const navigateToEdit = () => {
  if (goods.value.goodsId) {
    router.push(`/manage/goods/edit/${goods.value.goodsId}`)
  }
}

// 重置动态查询参数
function resetDynamicQuery() {
  dynamicQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    goodsId: goodsId.value ? Number(goodsId.value) : undefined
  }
  dynamicList.value = []
  dynamicTotal.value = 0
  dynamicFinished.value = false
}

// 获取商品动态列表
async function fetchDynamicList(isLoadMore = false) {
  if (!goodsId.value) return
  if (!isLoadMore) {
    dynamicLoading.value = true
  }
  try {
    // 确保商品ID筛选
    dynamicQueryParams.value.goodsId = goodsId.value
    const res = await getBorrowReturnDynamicApi(dynamicQueryParams.value)
    if (res.code === 0) {
      if (isLoadMore) {
        // 加载更多：追加数据
        dynamicList.value = [...dynamicList.value, ...(res.data?.rows || [])]
      } else {
        // 首次加载：替换数据
        dynamicList.value = res.data?.rows || []
      }
      dynamicTotal.value = res.data?.total || 0
      dynamicFinished.value = dynamicList.value.length >= dynamicTotal.value
    } else {
      showToast(res.msg || "获取数据失败")
    }
  } catch (_error) {
    showToast("网络错误，请重试")
  } finally {
    dynamicLoading.value = false
  }
}

// 加载更多商品动态
function loadMoreDynamic() {
  if (dynamicLoading.value || dynamicFinished.value) return
  dynamicQueryParams.value.pageNum!++
  fetchDynamicList(true)
}

// 安全获取图片数组
function getImageArray(imagesStr?: string): string[] {
  if (!imagesStr || imagesStr.trim() === "") return []
  return imagesStr.split(",").filter(img => img.trim() !== "")
}

// 预览归还图片组
function previewReturnImages(images: string[], startIndex = 0) {
  if (!images || images.length === 0) return
  showImagePreview([images[startIndex]])
}

// 预览审批图片组
function previewAuditImages(images: string[], startIndex = 0) {
  if (!images || images.length === 0) return
  showImagePreview([images[startIndex]])
}

// 初始化
onMounted(() => {
  const id = route.params.id
  if (id) {
    const idStr = Array.isArray(id) ? id[0] : id
    if (idStr) {
      goodsId.value = parseInt(idStr, 10)
      if (!isNaN(goodsId.value)) {
        fetchGoodsDetail(goodsId.value)
      } else {
        showFailToast('商品ID无效')
        router.back()
      }
    }
  }
})
</script>

<template>
  <div class="goods-detail-page">
    <!-- 加载中 -->
    <van-loading v-if="loading" size="24px" vertical>加载中...</van-loading>

    <!-- 商品详情内容 -->
    <div v-else class="goods-content">
      <!-- 商品图片 -->
      <div class="goods-image-section">
        <van-image
          v-if="goods.coverImg"
          :src="goods.coverImg"
          class="goods-main-image"
          fit="cover"
        >
          <template #error>
            <div class="image-error">
              <van-icon name="photo-fail" size="40" />
              <div>图片加载失败</div>
            </div>
          </template>
        </van-image>
        <div v-else class="no-image">
          <van-icon name="photo" size="60" />
          <div>暂无图片</div>
        </div>
      </div>

      <!-- Tabs 切换 -->
      <van-tabs class="goods-tabs" v-model:active="activeTab" offset-top="50" sticky>
        <!-- 商品详情 Tab -->
        <van-tab title="商品详情">
          <div class="tab-content">
            <!-- 商品基本信息 -->
            <div class="goods-basic-info">
              <h2 class="goods-name">{{ goods.goodsName || '未知商品' }}</h2>
              <div class="goods-price">¥{{ goods.price?.toFixed(2) || '0.00' }}</div>

              <div class="goods-meta">
                <van-tag v-if="goods.status === 1" type="success">上架</van-tag>
                <van-tag v-else-if="goods.status === 2" type="danger">下架</van-tag>
                <van-tag v-if="goods.stock! > 0" type="primary">库存: {{ goods.stock }}</van-tag>
                <van-tag v-else type="warning">已售罄</van-tag>
                <van-tag v-if="goods.autoApproval === 1" type="success">免审批</van-tag>
              </div>
            </div>

            <!-- 商品详情 -->
            <div class="goods-detail-section">
              <h3 class="section-title">商品详情</h3>
              <div class="detail-content" v-html="goods.goodsDetail || '暂无商品详情'"></div>
            </div>

            <!-- 使用说明 -->
            <div v-if="goods.usageInstruction" class="usage-section">
              <h3 class="section-title">使用说明</h3>
              <div class="usage-content">{{ goods.usageInstruction }}</div>
            </div>

            <!-- 备注 -->
            <div v-if="goods.remark" class="remark-section">
              <h3 class="section-title">备注</h3>
              <div class="remark-content">{{ goods.remark }}</div>
            </div>
          </div>
        </van-tab>

        <!-- 商品动态 Tab -->
        <van-tab title="商品动态">
          <div class="tab-content">
            <!-- 商品动态列表 -->
            <van-list
              v-if="dynamicList.length > 0"
              :loading="dynamicLoading"
              :finished="dynamicFinished"
              finished-text="没有更多了"
              @load="loadMoreDynamic"
            >
              <!-- 时间线容器 -->
              <div class="timeline-container">
                <!-- 时间线线条 -->
                <div class="timeline-line" />

                <!-- 动态条目 -->
                <div
                  v-for="item in dynamicList"
                  :key="item.orderGoodsId"
                  class="timeline-item"
                >
                  <!-- 时间点 -->
                  <div class="timeline-dot">
                    <div class="dot" :class="`dot-type-${item.dynamicType}`" />
                  </div>

                  <!-- 内容卡片 -->
                  <div class="dynamic-card">
                    <!-- 时间显示 -->
                    <div class="dynamic-time">
                      {{ item.dynamicType === 0 ? item.orderTime : item.operateTime }}
                    </div>

                    <!-- 卡片头部：类型和状态 -->
                    <div class="card-header">
                      <span class="dynamic-type" :class="`type-${item.dynamicType}`">
                        {{ item.dynamicTypeStr }}
                      </span>
                      <span v-if="item.dynamicType === 1" class="audit-status" :class="`status-${item.status}`">
                        {{ item.statusStr }}
                      </span>
                    </div>

                    <!-- 分隔线 -->
                    <van-divider />

                    <!-- 商品信息（简化展示，因为已经在商品详情页） -->
                    <div class="goods-info">
                      <div class="goods-details">
                        <div class="order-info">
                          <div class="order-name">
                            {{ item.orderName }}
                          </div>
                          <div class="order-mobile">
                            {{ item.orderMobile }}
                          </div>
                        </div>
                        <div class="cabinet-info">
                          <span class="cabinet-name">{{ item.cabinetName }}</span>
                          <span class="cell-no">格口号: {{ item.cellNo }}</span>
                        </div>
                      </div>
                    </div>

                    <!-- 归还图片和审核图片 -->
                    <div v-if="item.dynamicType === 1" class="image-section">
                      <!-- 归还图片 -->
                      <div v-if="getImageArray(item.images).length > 0" class="image-group">
                        <div class="image-label">
                          归还图片
                        </div>
                        <div class="image-list">
                          <van-image
                            v-for="(img, imgIndex) in getImageArray(item.images)"
                            :key="imgIndex"
                            :src="img"
                            width="50"
                            height="50"
                            fit="cover"
                            class="return-image"
                            @click="previewReturnImages(getImageArray(item.images), imgIndex)"
                          />
                        </div>
                      </div>

                      <!-- 审核图片 -->
                      <div v-if="getImageArray(item.auditImages).length > 0" class="image-group">
                        <div class="image-label">
                          审核图片
                        </div>
                        <div class="image-list">
                          <van-image
                            v-for="(img, imgIndex) in getImageArray(item.auditImages)"
                            :key="imgIndex"
                            :src="img"
                            width="50"
                            height="50"
                            fit="cover"
                            class="audit-image"
                            @click="previewAuditImages(getImageArray(item.auditImages), imgIndex)"
                          />
                        </div>
                      </div>
                    </div>

                    <!-- 审批人和审核说明 -->
                    <div v-if="item.dynamicType === 1 && (item.auditName || item.auditRemark)" class="audit-info">
                      <div v-if="item.auditName" class="audit-person">
                        <span class="label">审批人:</span>
                        <span class="value">{{ item.auditName }}</span>
                      </div>
                      <div v-if="item.auditRemark && item.auditRemark != '自动审批'" class="audit-remark">
                        <span class="label">审核说明:</span>
                        <span class="value">{{ item.auditRemark }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </van-list>

            <!-- 空状态 -->
            <div v-if="!dynamicLoading && dynamicList.length === 0" class="empty-state">
              <van-empty description="暂无商品动态" />
            </div>
          </div>
        </van-tab>
      </van-tabs>
    </div>

    <!-- 固定在右下角的圆形编辑按钮 -->
    <div v-if="activeTab === 0" class="floating-edit-button">
      <van-button
        round
        type="primary"
        size="large"
        icon="edit"
        @click="navigateToEdit"
      />
    </div>
  </div>
</template>

<style scoped>
.goods-detail-page {
  height: 100%;
  background-color: #f7f8fa;
}

.goods-content {
  padding: 12px;
}

/* 商品图片区域 */
.goods-image-section {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* Tabs 样式 */
.goods-tabs {
  /* margin-bottom: 16px; */
}

.tab-content {
  padding: 0;
  background: white;
  overflow: hidden;
}

.goods-dynamics-placeholder {
  text-align: center;
  padding: 40px 0;
  color: #969799;
  font-size: 14px;
}

.goods-main-image {
  width: 100%;
  height: 300px;
  display: block;
}

.image-error {
  width: 100%;
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #969799;
  background-color: #f7f8fa;
}

.no-image {
  width: 100%;
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #969799;
  background-color: #f7f8fa;
}

/* 商品基本信息 */
.goods-basic-info {
  padding: 16px;
  margin-bottom: 16px;
}

.goods-name {
  font-size: 18px;
  color: #333;
  font-weight: 600;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.goods-price {
  font-size: 24px;
  color: #ff4444;
  font-weight: 700;
  margin: 8px 0 12px 0;
}

.goods-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 12px;
}

/* 详情区域 */
.goods-detail-section,
.usage-section,
.remark-section {
  padding: 16px;
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  color: #333;
  font-weight: 600;
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-content {
  font-size: 14px;
  color: #555;
  line-height: 1.6;
}

.detail-content :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 8px 0;
}

.usage-content,
.remark-content {
  font-size: 14px;
  color: #555;
  line-height: 1.6;
  white-space: pre-wrap;
}

/* 浮动编辑按钮 */
.floating-edit-button {
  position: fixed;
  right: 20px;
  bottom: 30px;
  z-index: 1000;
}

.floating-edit-button .van-button {
  width: 56px;
  height: 56px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.floating-edit-button .van-button .van-icon {
  font-size: 20px;
}

/* 商品动态样式 */
.dynamic-time {
  padding: 10px 16px;
  font-size: 13px;
  color: #666;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 6px 6px 0 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  font-weight: 500;
  letter-spacing: 0.3px;
}

.timeline-container {
  position: relative;
  margin-top: 8px;
  min-height: 90vh;
  padding-left: 32px;
}

.timeline-line {
  position: absolute;
  left: 16px;
  top: 0;
  bottom: 0;
  width: 3px;
  background: linear-gradient(
    to bottom,
    rgba(25, 137, 250, 0.2) 0%,
    rgba(25, 137, 250, 0.6) 30%,
    rgba(25, 137, 250, 0.8) 50%,
    rgba(25, 137, 250, 0.6) 70%,
    rgba(25, 137, 250, 0.2) 100%
  );
  border-radius: 2px;
  box-shadow: 0 0 10px rgba(25, 137, 250, 0.15);
}

.timeline-item {
  position: relative;
  margin-bottom: 20px;
  transition:
    transform 0.3s ease,
    opacity 0.3s ease;
}

.timeline-item:hover {
  transform: translateY(-2px);
}

.timeline-dot {
  position: absolute;
  left: -30px;
  top: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 32px;
  z-index: 2;
}

.dot {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background-color: #1989fa;
  border: 3px solid white;
  box-shadow:
    0 0 0 3px #1989fa,
    0 0 15px rgba(25, 137, 250, 0.4);
  transition: all 0.3s ease;
  position: relative;
}

.dot::after {
  content: "";
  position: absolute;
  top: -3px;
  left: -3px;
  right: -3px;
  bottom: -3px;
  border-radius: 50%;
  background: inherit;
  filter: blur(5px);
  opacity: 0.4;
  z-index: -1;
}

.dot-type-0 {
  background-color: #1989fa;
  box-shadow:
    0 0 0 3px #1989fa,
    0 0 15px rgba(25, 137, 250, 0.4);
}

.dot-type-1 {
  background-color: #07c160;
  box-shadow:
    0 0 0 3px #07c160,
    0 0 15px rgba(7, 193, 96, 0.4);
}

.dynamic-card {
  border-radius: 10px;
  overflow: hidden;
  box-shadow:
    0 4px 20px rgba(0, 0, 0, 0.08),
    0 2px 6px rgba(0, 0, 0, 0.04),
    inset 0 1px 0 rgba(255, 255, 255, 0.8);
  background-color: white;
  border: 1px solid rgba(0, 0, 0, 0.05);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.dynamic-card:hover {
  box-shadow:
    0 8px 30px rgba(0, 0, 0, 0.12),
    0 4px 12px rgba(0, 0, 0, 0.06),
    inset 0 1px 0 rgba(255, 255, 255, 0.9);
  transform: translateY(-4px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: linear-gradient(to right, rgba(25, 137, 250, 0.03), rgba(7, 193, 96, 0.03));
  border-bottom: 1px solid rgba(0, 0, 0, 0.04);
}

.dynamic-type {
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 0.5px;
  position: relative;
}

.type-0 {
  color: #1989fa;
}

.type-1 {
  color: #07c160;
}

.audit-status {
  font-size: 12px;
  padding: 3px 10px;
  border-radius: 16px;
  font-weight: 600;
  letter-spacing: 0.3px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.audit-status:hover {
  transform: scale(1.05);
}

.status-1 {
  background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%);
  color: #f57c00;
  border: 1px solid rgba(245, 124, 0, 0.2);
}

.status-2 {
  background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
  color: #07c160;
  border: 1px solid rgba(7, 193, 96, 0.2);
}

.status-3 {
  background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
  color: #ee0a24;
  border: 1px solid rgba(238, 10, 36, 0.2);
}

.goods-info {
  display: flex;
  padding: 16px;
  gap: 12px;
  align-items: center;
}

.goods-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.order-info {
  display: flex;
  gap: 12px;
  font-size: 13px;
  color: #666;
  background: rgba(0, 0, 0, 0.02);
  padding: 8px 10px;
  border-radius: 6px;
  margin-top: 4px;
}

.order-info .order-name,
.order-info .order-mobile {
  display: flex;
  align-items: center;
  gap: 6px;
}

.cabinet-info {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #666;
  background: rgba(25, 137, 250, 0.04);
  padding: 8px 10px;
  border-radius: 6px;
  margin-top: 4px;
}

.cabinet-name {
  font-weight: 500;
  color: #333;
}

.cell-no {
  color: #1989fa;
  font-weight: 600;
  background: rgba(25, 137, 250, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 13px;
}

.image-section {
  padding: 0 16px 16px;
  display: flex;
  gap: 16px;
}

.image-group {
  flex: 1;
}

.image-label {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
  padding-left: 8px;
  border-left: 3px solid #1989fa;
}

.image-list {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.return-image,
.audit-image {
  border-radius: 6px;
  overflow: hidden;
  border: 2px solid white;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.return-image:hover,
.audit-image:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
}

.audit-info {
  padding: 0 16px 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  font-size: 13px;
}

.audit-person,
.audit-remark {
  display: flex;
  gap: 8px;
  align-items: flex-start;
  background: rgba(0, 0, 0, 0.02);
  padding: 10px;
  border-radius: 8px;
}

.label {
  color: #666;
  min-width: 70px;
  font-weight: 500;
}

.value {
  color: #333;
  flex: 1;
  line-height: 1.5;
}

.empty-state {
  padding: 80px 0;
}

/* 美化分隔线 */
.van-divider {
  margin: 0 16px;
  border-color: rgba(0, 0, 0, 0.06);
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(15px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.timeline-item {
  animation: fadeIn 0.4s cubic-bezier(0.4, 0, 0.2, 1) forwards;
}
</style>