<template>
  <view class="page">
    <NavBar title="申请详情" :showBack="true" />

    <scroll-view class="detail-scroll" scroll-y v-if="detail">
      <view class="status-banner" :class="getStatusClass(detail.status)">
        <view class="status-dot"></view>
        <text class="status-text">{{ getStatusText(detail.status) }}</text>
      </view>

      <view class="detail-section">
        <view class="section-title">
          <text class="section-title-text">基本信息</text>
        </view>

        <view class="detail-row">
          <text class="detail-label">申请编号</text>
          <text class="detail-value">#{{ detail.id }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">商品名称</text>
          <text class="detail-value">{{ detail.productName || '-' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">条形码</text>
          <text class="detail-value">{{ detail.barcode || '-' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">分类</text>
          <text class="detail-value">{{ detail.category || '-' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">品牌</text>
          <text class="detail-value">{{ detail.brand || '-' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">规格</text>
          <text class="detail-value">{{ detail.specification || '-' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">单位</text>
          <text class="detail-value">{{ detail.unit || '-' }}</text>
        </view>
      </view>

      <view class="detail-section">
        <view class="section-title">
          <text class="section-title-text">价格信息</text>
        </view>

        <view class="detail-row">
          <text class="detail-label">售价</text>
          <text class="detail-value price">¥{{ formatMoney(detail.price || 0) }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">成本价</text>
          <text class="detail-value">¥{{ formatMoney(detail.costPrice || 0) }}</text>
        </view>
      </view>

      <view class="detail-section" v-if="imageUrls.length > 0">
        <view class="section-title">
          <text class="section-title-text">商品图片</text>
        </view>
        <view class="image-gallery">
          <image
            class="gallery-image"
            v-for="(img, index) in imageUrls"
            :key="index"
            :src="img"
            mode="aspectFill"
            @click="previewImage(index)"
          />
        </view>
      </view>

      <view class="detail-section" v-if="detail.description">
        <view class="section-title">
          <text class="section-title-text">商品描述</text>
        </view>
        <text class="detail-desc">{{ detail.description }}</text>
      </view>

      <view class="detail-section">
        <view class="section-title">
          <text class="section-title-text">申请信息</text>
        </view>

        <view class="detail-row">
          <text class="detail-label">申请人</text>
          <text class="detail-value">{{ detail.applicantName || '-' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">申请时间</text>
          <text class="detail-value">{{ detail.applyTime ? formatDateTime(detail.applyTime) : '-' }}</text>
        </view>
        <view class="detail-row" v-if="detail.auditTime">
          <text class="detail-label">审核时间</text>
          <text class="detail-value">{{ formatDateTime(detail.auditTime) }}</text>
        </view>
        <view class="detail-row" v-if="detail.auditorName">
          <text class="detail-label">审核人</text>
          <text class="detail-value">{{ detail.auditorName }}</text>
        </view>
        <view class="detail-row" v-if="detail.auditRemark">
          <text class="detail-label">审核备注</text>
          <text class="detail-value">{{ detail.auditRemark }}</text>
        </view>
      </view>

      <view class="bottom-spacer"></view>
    </scroll-view>

    <view class="footer-bar" v-if="detail && detail.status === 0">
      <view class="btn-delete" @click="handleDelete">
        <text class="btn-delete-text">删除</text>
      </view>
      <view class="btn-edit" @click="goEdit">
        <text class="btn-edit-text">编辑</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import NavBar from '@/components/NavBar.vue';
import {
  getNewProductApplyById,
  deleteNewProductApply,
  type NewProductApplyItem
} from '@/api/newProductApply';
import { formatMoney, formatDateTime, showConfirm, showToast } from '@/utils/common';
import { IMAGE_BASE_URL } from '@/utils/config';

const detail = ref<NewProductApplyItem | null>(null);
const applyId = ref(0);

const imageUrls = computed(() => {
  if (!detail.value?.images) return [];
  return detail.value.images
    .split(',')
    .filter((url: string) => url.trim())
    .map((url: string) => {
      if (url.startsWith('http')) return url;
      return `${IMAGE_BASE_URL}${url}`;
    });
});

const getStatusText = (status?: number) => {
  const map: Record<number, string> = {
    0: '待提交',
    1: '待审核',
    2: '已通过',
    3: '已拒绝'
  };
  return map[status ?? -1] || '未知';
};

const getStatusClass = (status?: number) => {
  const map: Record<number, string> = {
    0: 'draft',
    1: 'pending',
    2: 'approved',
    3: 'rejected'
  };
  return map[status ?? -1] || 'draft';
};

const previewImage = (index: number) => {
  uni.previewImage({
    current: imageUrls.value[index],
    urls: imageUrls.value
  });
};

const loadDetail = async (id: number) => {
  try {
    uni.showLoading({ title: '加载中...', mask: true });
    const res = await getNewProductApplyById(id);
    uni.hideLoading();
    if (res) {
      detail.value = res;
    }
  } catch (error) {
    uni.hideLoading();
    console.error('加载详情失败', error);
  }
};

const handleDelete = async () => {
  const confirmed = await showConfirm('确定要删除该申请吗？');
  if (!confirmed) return;
  try {
    await deleteNewProductApply(applyId.value);
    showToast('删除成功', 'success');
    setTimeout(() => {
      uni.navigateBack();
    }, 500);
  } catch (error) {
    console.error('删除失败', error);
  }
};

const goEdit = () => {
  uni.navigateTo({ url: `/pages/products/apply-form?id=${applyId.value}` });
};

onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1] as any;
  const options = currentPage?.options || {};
  const id = options.id ? Number(options.id) : 0;
  if (id) {
    applyId.value = id;
    loadDetail(id);
  }
});
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: $bg-color-page;
  display: flex;
  flex-direction: column;
}

.detail-scroll {
  flex: 1;
  padding: 24rpx;
  height: 0;
}

.status-banner {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 28rpx;
  border-radius: $radius-lg;
  margin-bottom: 20rpx;
  gap: 10rpx;

  &.draft {
    background: $bg-color-secondary;
    .status-dot { background: $text-color-placeholder; }
  }
  &.pending {
    background: $warning-color-bg;
    .status-dot { background: $warning-color; }
  }
  &.approved {
    background: $success-color-bg;
    .status-dot { background: $success-color; }
  }
  &.rejected {
    background: $error-color-bg;
    .status-dot { background: $error-color; }
  }
}

.status-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
}

.status-text {
  font-size: $font-size-lg;
  font-weight: 700;
  color: $text-color-primary;
}

.detail-section {
  background: $bg-color-card;
  border-radius: $radius-lg;
  padding: 0 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.section-title {
  padding: 28rpx 0 12rpx;
}

.section-title-text {
  font-size: $font-size-base;
  font-weight: 600;
  color: $text-color-primary;
}

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

.detail-label {
  font-size: $font-size-sm;
  color: $text-color-muted;
  flex-shrink: 0;
  margin-right: 24rpx;
}

.detail-value {
  font-size: $font-size-sm;
  color: $text-color-primary;
  text-align: right;
  word-break: break-all;

  &.price {
    color: $primary-color-dark;
    font-weight: 600;
  }
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  padding: 20rpx 0;
}

.gallery-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: $radius-base;
  background: $bg-color-page;
}

.detail-desc {
  display: block;
  padding: 20rpx 0;
  font-size: $font-size-sm;
  color: $text-color-secondary;
  line-height: 1.6;
}

.bottom-spacer {
  height: 140rpx;
}

.footer-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  gap: 20rpx;
  padding: 20rpx 24rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background: $bg-color-card;
  border-top: 1rpx solid $border-color;
  z-index: 100;
}

.btn-delete {
  flex: 1;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: $radius-full;
  border: 2rpx solid $error-color;

  &:active { opacity: 0.7; }
}

.btn-delete-text {
  font-size: $font-size-lg;
  color: $error-color;
  font-weight: 500;
}

.btn-edit {
  flex: 2;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: $primary-color;
  border-radius: $radius-full;

  &:active { opacity: 0.8; }
}

.btn-edit-text {
  font-size: $font-size-lg;
  color: $text-color-primary;
  font-weight: 600;
}
</style>
