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

    <view class="content">
      <view class="search-bar">
        <view class="search-input-wrap">
          <view class="search-icon"></view>
          <input
            class="search-input"
            v-model="searchKeyword"
            placeholder="搜索商品名称或条形码"
            confirm-type="search"
            @confirm="onSearch"
          />
          <view v-if="searchKeyword" class="search-clear" @click="clearSearch">
            <view class="clear-icon"></view>
          </view>
        </view>
        <view class="filter-btn" @click="showFilter = !showFilter">
          <text :class="['filter-text', { active: form.status !== '' || form.applicantId }]">筛选</text>
        </view>
        <view class="reset-btn" @click="resetForm">
          <text class="reset-text">重置</text>
        </view>
      </view>

      <view class="filter-panel" v-if="showFilter">
        <view class="filter-section">
          <text class="filter-section-label">申请状态</text>
          <view class="filter-tags">
            <view
              class="filter-tag"
              :class="{ active: form.status === '' }"
              @click="selectStatus('')"
            >
              <text>全部</text>
            </view>
            <view
              class="filter-tag"
              :class="{ active: form.status === 0 }"
              @click="selectStatus(0)"
            >
              <text>待提交</text>
            </view>
            <view
              class="filter-tag"
              :class="{ active: form.status === 1 }"
              @click="selectStatus(1)"
            >
              <text>待审核</text>
            </view>
            <view
              class="filter-tag"
              :class="{ active: form.status === 2 }"
              @click="selectStatus(2)"
            >
              <text>已通过</text>
            </view>
            <view
              class="filter-tag"
              :class="{ active: form.status === 3 }"
              @click="selectStatus(3)"
            >
              <text>已拒绝</text>
            </view>
          </view>
        </view>
        <view class="filter-section">
          <text class="filter-section-label">申请人</text>
          <view class="filter-input-wrap">
            <input
              class="filter-input"
              v-model="applicantNameInput"
              placeholder="请输入申请人"
              confirm-type="search"
              @confirm="onSearch"
            />
          </view>
        </view>
      </view>

      <scroll-view
        class="list-scroll"
        scroll-y
        @scrolltolower="loadMore"
        refresher-enabled
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
      >
        <view v-if="dataList.length === 0 && !loading" class="empty-state">
          <view class="empty-icon"></view>
          <text class="empty-title">暂无申请记录</text>
          <text class="empty-desc">提交新品上架申请</text>
          <view class="empty-btn" @click="goApplyForm()">
            <text class="empty-btn-text">立即申请</text>
          </view>
        </view>

        <view
          class="apply-card"
          v-for="item in dataList"
          :key="item.id"
        >
          <view class="apply-header" @click="goDetail(item)">
            <view class="apply-id-wrap">
              <text class="apply-id">#{{ item.id }}</text>
              <text class="apply-name">{{ item.productName }}</text>
            </view>
            <view :class="['status-tag', getStatusClass(item.status)]">
              <text class="status-text">{{ getStatusText(item.status) }}</text>
            </view>
          </view>
          <view class="apply-info" @click="goDetail(item)">
            <view class="info-row">
              <text class="info-label">条形码</text>
              <text class="info-value">{{ item.barcode || '-' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">分类</text>
              <text class="info-value">{{ item.category || '-' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">品牌</text>
              <text class="info-value">{{ item.brand || '-' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">售价</text>
              <text class="info-value price">¥{{ formatMoney(item.price || 0) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">申请人</text>
              <text class="info-value">{{ item.applicantName || '-' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">申请时间</text>
              <text class="info-value">{{ item.applyTime ? formatDateTime(item.applyTime) : '-' }}</text>
            </view>
          </view>
          <view class="apply-footer">
            <view class="footer-left">
              <view class="action-btn view" @click="goDetail(item)">
                <text>查看</text>
              </view>
              <view
                v-if="item.status === 0"
                class="action-btn edit"
                @click="goApplyForm(item)"
              >
                <text>编辑</text>
              </view>
              <view
                v-if="item.status === 0"
                class="action-btn delete"
                @click.stop="handleDelete(item)"
              >
                <text>删除</text>
              </view>
            </view>
          </view>
        </view>

        <view class="load-more" v-if="dataList.length > 0">
          <view class="load-more-row" v-if="loading">
            <view class="load-spinner"></view>
            <text class="load-more-text">加载中...</text>
          </view>
          <text class="load-more-text" v-else-if="noMore">没有更多了</text>
        </view>
      </scroll-view>
    </view>

    <view class="fab-btn" @click="goApplyForm()">
      <text class="fab-icon">+</text>
    </view>
  </view>
</template>

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

const form = reactive({
  productName: '',
  barcode: '',
  status: '' as number | '',
  applicantId: '' as number | ''
});

const searchKeyword = ref('');
const applicantNameInput = ref('');
const showFilter = ref(false);
const dataList = ref<NewProductApplyItem[]>([]);
const loading = ref(false);
const refreshing = ref(false);
const noMore = ref(false);
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
});

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 selectStatus = (status: number | '') => {
  form.status = status;
  pagination.page = 1;
  noMore.value = false;
  loadData();
};

const onSearch = () => {
  const keyword = searchKeyword.value.trim();
  form.productName = keyword;
  form.barcode = keyword;
  const applicantVal = applicantNameInput.value.trim();
  if (applicantVal) {
    const applicantId = Number(applicantVal);
    form.applicantId = !isNaN(applicantId) ? applicantId : '';
  } else {
    form.applicantId = '';
  }
  pagination.page = 1;
  noMore.value = false;
  loadData();
};

const clearSearch = () => {
  searchKeyword.value = '';
  form.productName = '';
  form.barcode = '';
  pagination.page = 1;
  noMore.value = false;
  loadData();
};

const resetForm = () => {
  searchKeyword.value = '';
  applicantNameInput.value = '';
  form.productName = '';
  form.barcode = '';
  form.status = '';
  form.applicantId = '';
  showFilter.value = false;
  pagination.page = 1;
  noMore.value = false;
  loadData();
};

const loadData = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.page,
      pageSize: pagination.pageSize
    };
    if (form.productName) params.productName = form.productName;
    if (form.barcode) params.barcode = form.barcode;
    if (form.status !== '') params.status = form.status;
    if (form.applicantId) params.applicantId = form.applicantId;

    const res = await getNewProductApplyList(params);
    if (res) {
      const list = res.list || [];
      if (pagination.page === 1) {
        dataList.value = list;
      } else {
        dataList.value = [...dataList.value, ...list];
      }
      pagination.total = res.total || 0;
      noMore.value = dataList.value.length >= pagination.total;
    }
  } catch (error) {
    console.error('加载新品申请列表失败', error);
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

const onRefresh = async () => {
  refreshing.value = true;
  pagination.page = 1;
  noMore.value = false;
  await loadData();
};

const loadMore = () => {
  if (loading.value || noMore.value) return;
  pagination.page++;
  loadData();
};

const handleDelete = async (item: NewProductApplyItem) => {
  const confirmed = await showConfirm('是否确认删除?');
  if (!confirmed) return;
  try {
    await deleteNewProductApply(item.id!);
    showToast('删除成功', 'success');
    pagination.page = 1;
    noMore.value = false;
    await loadData();
  } catch (error) {
    console.error('删除失败', error);
  }
};

const goApplyForm = (item?: NewProductApplyItem) => {
  const url = item?.id
    ? `/pages/products/apply-form?id=${item.id}`
    : '/pages/products/apply-form';
  uni.navigateTo({ url });
};

const goDetail = (item: NewProductApplyItem) => {
  uni.navigateTo({ url: `/pages/products/apply-detail?id=${item.id}` });
};

onMounted(() => {
  loadData();
});
</script>

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

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 20rpx 24rpx;
}

.search-input-wrap {
  flex: 1;
  display: flex;
  align-items: center;
  background: $bg-color-card;
  border-radius: $radius-full;
  padding: 0 24rpx;
  height: 72rpx;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 12rpx;
  border: 3rpx solid $text-color-muted;
  border-radius: 50%;
  position: relative;

  &::after {
    content: '';
    position: absolute;
    bottom: -4rpx;
    right: -4rpx;
    width: 8rpx;
    height: 3rpx;
    background: $text-color-muted;
    border-radius: 3rpx;
    transform: rotate(45deg);
    transform-origin: left center;
  }
}

.search-input {
  flex: 1;
  height: 72rpx;
  font-size: $font-size-sm;
  color: $text-color-primary;
}

.search-clear {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: $bg-color-secondary;

  &:active { opacity: 0.7; }
}

.clear-icon {
  width: 20rpx;
  height: 20rpx;
  position: relative;

  &::before,
  &::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 16rpx;
    height: 2rpx;
    background: $text-color-muted;
    border-radius: 1rpx;
  }

  &::before { transform: translate(-50%, -50%) rotate(45deg); }
  &::after { transform: translate(-50%, -50%) rotate(-45deg); }
}

.filter-btn {
  padding: 0 20rpx;
  height: 72rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: $bg-color-card;
  border-radius: $radius-full;

  &:active { opacity: 0.8; }
}

.filter-text {
  font-size: $font-size-sm;
  color: $text-color-secondary;

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

.reset-btn {
  padding: 0 20rpx;
  height: 72rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: $bg-color-card;
  border-radius: $radius-full;

  &:active { opacity: 0.8; }
}

.reset-text {
  font-size: $font-size-sm;
  color: $text-color-muted;
}

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

.filter-section {
  padding: 14rpx 0;

  & + .filter-section {
    padding-top: 18rpx;
  }
}

.filter-section-label {
  font-size: $font-size-sm;
  color: $text-color-secondary;
  font-weight: 500;
  margin-bottom: 12rpx;
  display: block;
}

.filter-tags {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
}

.filter-tag {
  padding: 10rpx 28rpx;
  background: #FAFAFA;
  border-radius: $radius-full;

  text {
    font-size: $font-size-sm;
    color: $text-color-secondary;
  }

  &.active {
    background: $primary-color-bg;

    text {
      color: $primary-color-dark;
      font-weight: 600;
    }
  }
}

.filter-input-wrap {
  background: #FAFAFA;
  border-radius: $radius-base;
  padding: 0 20rpx;
  height: 72rpx;
  display: flex;
  align-items: center;
}

.filter-input {
  flex: 1;
  height: 72rpx;
  font-size: $font-size-sm;
  color: $text-color-primary;
}

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

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

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

.apply-id-wrap {
  flex: 1;
  display: flex;
  align-items: center;
  margin-right: 16rpx;
}

.apply-id {
  font-size: $font-size-xs;
  color: $text-color-muted;
  margin-right: 12rpx;
  flex-shrink: 0;
}

.apply-name {
  font-size: $font-size-lg;
  font-weight: 600;
  color: $text-color-primary;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status-tag {
  padding: 6rpx 16rpx;
  border-radius: $radius-full;
  flex-shrink: 0;

  &.draft {
    background: $bg-color-secondary;

    .status-text { color: $text-color-muted; }
  }
  &.pending {
    background: $warning-color-bg;

    .status-text { color: $warning-color; }
  }
  &.approved {
    background: $success-color-bg;

    .status-text { color: $success-color; }
  }
  &.rejected {
    background: $error-color-bg;

    .status-text { color: $error-color; }
  }
}

.status-text {
  font-size: $font-size-xs;
  font-weight: 600;
}

.apply-info {
  margin-bottom: 12rpx;
}

.info-row {
  display: flex;
  align-items: baseline;
  padding: 6rpx 0;
}

.info-label {
  font-size: 22rpx;
  color: $text-color-muted;
  margin-right: 12rpx;
  flex-shrink: 0;
  min-width: 80rpx;
}

.info-value {
  font-size: 24rpx;
  color: $text-color-secondary;
  word-break: break-all;

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

.apply-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 20rpx;
}

.footer-left {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  padding: 8rpx 24rpx;
  border-radius: $radius-full;

  text {
    font-size: $font-size-xs;
    font-weight: 500;
  }

  &.view {
    background: $info-color-bg;

    text { color: $info-color; }
  }
  &.edit {
    background: $primary-color-bg;

    text { color: $primary-color-dark; }
  }
  &.delete {
    background: $error-color-bg;

    text { color: $error-color; }
  }

  &:active {
    opacity: 0.7;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 0 80rpx;
}

.empty-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: $bg-color-secondary;
  margin-bottom: 24rpx;
  position: relative;

  &::before,
  &::after {
    content: '';
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    background: $text-color-placeholder;
  }

  &::before {
    top: 30rpx;
    width: 32rpx;
    height: 4rpx;
    border-radius: 2rpx;
  }

  &::after {
    top: 46rpx;
    width: 24rpx;
    height: 4rpx;
    border-radius: 2rpx;
  }
}

.empty-title {
  font-size: $font-size-base;
  font-weight: 500;
  color: $text-color-secondary;
  margin-bottom: 8rpx;
}

.empty-desc {
  font-size: $font-size-sm;
  color: $text-color-muted;
  margin-bottom: 32rpx;
}

.empty-btn {
  padding: 16rpx 48rpx;
  background: $primary-color;
  border-radius: $radius-full;

  &:active { opacity: 0.8; }
}

.empty-btn-text {
  font-size: $font-size-base;
  color: $text-color-primary;
  font-weight: 600;
}

.load-more {
  padding: 20rpx 0 40rpx;
  text-align: center;
}

.load-more-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

.load-spinner {
  width: 28rpx;
  height: 28rpx;
  border: 3rpx solid $border-color;
  border-top-color: $text-color-muted;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.load-more-text {
  font-size: 22rpx;
  color: $text-color-muted;
}

.fab-btn {
  position: fixed;
  right: 40rpx;
  bottom: 140rpx;
  width: 100rpx;
  height: 100rpx;
  background: $primary-color;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(255, 193, 7, 0.4);
  z-index: 100;

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

.fab-icon {
  font-size: 52rpx;
  color: $text-color-primary;
  font-weight: 700;
  line-height: 1;
}
</style>
