<template>
  <view class="my-publish-container">
    <!-- 顶部Tab标签页 -->
    <view class="tab-header">
      <view class="tab-list">
        <view 
          class="tab-item"
          :class="{ active: activeTab === 'published' }"
          @click="switchTab('published')"
        >
          <text class="tab-text">销售信息</text>
        </view>
        <view 
          class="tab-item"
          :class="{ active: activeTab === 'purchase' }"
          @click="switchTab('purchase')"
        >
          <text class="tab-text">收购信息</text>
        </view>
      </view>
      <view class="tab-indicator" :style="{ left: activeTab === 'published' ? '0' : '50%' }"></view>
    </view>

    <!-- 我的发布页面 -->
    <view v-if="activeTab === 'published'" class="tab-content">
      <!-- 搜索筛选 -->
      <view class="search-section">
        <view class="search-box">
          <image class="search-icon" src="/static/icons/search.png" mode="aspectFit"></image>
          <input 
            class="search-input" 
            placeholder="搜索我的农产品" 
            placeholder-style="color: #999;"
            v-model="searchKeyword"
            @confirm="handleSearch"
          />
        </view>
      </view>
      
      <!-- 我的发布列表 -->
      <view class="products-container">
        <view class="products-list">
          <view 
            class="published-card"
            v-for="item in filteredPublishedProducts" 
            :key="item.id"
            @click="navigateToDetail(item)"
          >
            <view class="card-content">
              <view class="product-image">
                <image :src="getImageUrl(item.imageUrl)" mode="aspectFill"></image>
              </view>
              <view class="product-info">
                <view class="product-header">
                  <view class="product-name">{{ item.title }}</view>
                  <view class="price-info">¥{{ item.price || 0 }}/{{ getUnitLabel(item.unit) }}</view>
                </view>
                <view class="product-desc">{{ item.description }}</view>
                <view class="product-footer">
                  <view class="publish-time">{{ item.publishTime }}</view>
                  <view class="status-tag" :class="getStatusClassName(item.status)">
                    {{ getStatusText(item.status) }}
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 收购信息页面 -->
    <view v-if="activeTab === 'purchase'" class="tab-content">
      <!-- 搜索筛选 -->
      <view class="search-section">
        <view class="search-box">
          <image class="search-icon" src="/static/icons/search.png" mode="aspectFit"></image>
          <input 
            class="search-input" 
            placeholder="搜索收购信息" 
            placeholder-style="color: #999;"
            v-model="searchKeyword"
            @confirm="handleSearch"
          />
        </view>
      </view>
      
      <!-- 收购信息列表 -->
      <view class="products-container">
        <view class="products-list">
          <view 
            class="published-card"
            v-for="item in filteredPurchaseList" 
            :key="item.id"
            @click="navigateToPurchaseDetail(item)"
          >
            <view class="card-content">
              <view class="product-image">
                <image :src="getImageUrl(item.imageUrl)" mode="aspectFill"></image>
              </view>
              <view class="product-info">
                <view class="product-header">
                  <view class="product-name">{{ item.title }}</view>
                  <view class="price-info">¥{{ item.price || 0 }}/{{ getUnitLabel(item.unit) }}</view>
                </view>
                <view class="product-desc">需求数量：{{ item.quantity }}</view>
                <view class="product-footer">
                  <view class="publish-time">{{ item.publishTime }}</view>
                  <view class="status-tag" :class="getStatusClassName(item.status)">
                    {{ getStatusText(item.status) }}
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部固定按钮 -->
    <view class="bottom-action-bar">
      <view class="action-btn" @click="showPublishModal = true">
        <text class="btn-text">发布</text>
      </view>
    </view>

    <!-- 发布选择弹窗 -->
    <view class="publish-modal" v-if="showPublishModal" @click="showPublishModal = false">
      <view class="publish-content" @click.stop>
        <view class="publish-header">
          <text class="publish-title">选择发布类型</text>
          <text class="publish-close" @click="showPublishModal = false">✕</text>
        </view>
        <view class="publish-options">
          <view class="option-item" @click="navigateToPublish">
            <view class="option-text">
              <text class="option-title">发布农产品</text>
              <text class="option-desc">出售我的农产品</text>
            </view>
          </view>
          <view class="option-item" @click="navigateToPurchasePublish">
            <view class="option-text">
              <text class="option-title">发布收购信息</text>
              <text class="option-desc">收购农产品需求</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getProductInfoList } from '@/api/services/productInfo.js'
import { useDict } from '@/utils/composables/useDict'
import storage from "@/utils/storage.js"

// 使用字典
const { dictData } = useDict(['agricultural_unit'])

const activeTab = ref('published')
const searchKeyword = ref('')
const purchaseSearchKeyword = ref('')
const showPublishModal = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const noMoreData = ref(false)
const isLoading = ref(false)
const isRefreshing = ref(false)
const currentUserInfo = storage.getUserInfo()
const publishedProductsList = ref([])
const purchaseList = ref([])
const productsList = ref([])

const filteredPublishedProducts = computed(() => {
  let products = productsList.value
  return products
})

const filteredPurchaseList = computed(() => {
  let list = productsList.value
  return list
})

// 页面显示时刷新数据
onShow(() => {
	console.log("加载");
  loadMyPublishInfo()
})

// 页面加载时获取数据
onMounted(() => {
  loadMyPublishInfo()
})

// 上拉加载更多
const loadMore = () => {
  if (!isLoading.value && !noMoreData.value) {
    pageNum.value++
    loadMyPublishInfo()
  }
}

const getImageUrl = (item) => {
  if (item == null) return
  const imageUrls = item.split(',')
  return imageUrls[0]
}

const getUnitLabel = (value) => {
  const unit = dictData.agricultural_unit?.find(u => u.dictValue == value)
  return unit ? unit.dictLabel : ''
}

const loadMyPublishInfo = (keyword) => {
  isLoading.value = true
  uni.showLoading({
    title: '加载中'
  })
  console.log("currentUserInfo",currentUserInfo);
  // 构建查询参数
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    // createBy: currentUserInfo.username,
	userId: currentUserInfo.userid,
    type: 0 // 默认查询出售信息
  }
  
  if (keyword != null && keyword != '') {
    params.searchKeyword = keyword
  }
  
  // 分类逻辑
  if (activeTab.value !== 'published') {
    params.type = 1
  }
  
  getProductInfoList(params).then(res => {
    if (res.data.code === 200) {
      const { rows, total } = res.data
      if (pageNum.value === 1) {
        productsList.value = rows
      } else {
        productsList.value = [...productsList.value, ...rows]
      }
      // 判断是否还有更多数据
      noMoreData.value = productsList.value.length >= total
      uni.hideLoading()
    } else {
      uni.showToast({
        title: res.data.msg || '获取农品列表失败',
        icon: 'none'
      })
    }
  }).catch(err => {
    console.error('获取农品列表失败:', err)
    uni.showToast({
      title: '获取农品列表失败',
      icon: 'none'
    })
  }).finally(() => {
    isLoading.value = false
    isRefreshing.value = false
  })
}

const switchTab = (tab) => {
  activeTab.value = tab
  productsList.value = []
  pageNum.value = 1
  loadMyPublishInfo(searchKeyword.value.trim())
}

const getStatusText = (status) => {
  const statusMap = {
    1: '审核中',
    2: '已上架',
    3: '已下架',
    4: '未通过'
  }
  return statusMap[status] || '未知'
}

const getStatusClassName = (status) => {
  const statusMapClassName = {
    1: 'pending',
    2: 'approved',
    3: 'rejected',
    4: 'rejected'
  }
  return statusMapClassName[status] || '未知'
}

const handleSearch = () => {
  const keyword = searchKeyword.value.trim().toLowerCase()
  pageNum.value = 1
  productsList.value = []
  loadMyPublishInfo(keyword)
}

const navigateToDetail = (product) => {
  uni.navigateTo({
    url: `/pages/service/sales-detail?id=${product.id}&type=sale&name=${encodeURIComponent(product.title)}&source=myPublish&status=${product.status}`
  })
}

const navigateToPurchaseDetail = (item) => {
  uni.navigateTo({
    url: `/pages/service/sales-detail?id=${item.id}&type=purchase&title=${encodeURIComponent(item.title)}&source=myPublish&status=${item.status}`
  })
}

const navigateToPublish = () => {
  showPublishModal.value = false
  uni.navigateTo({
    url: '/pages/service/sales-publish'
  })
}

const navigateToPurchasePublish = () => {
  showPublishModal.value = false
  uni.navigateTo({
    url: '/pages/service/purchase-publish'
  })
}

// 导出 onShow 供 uni-app 使用
defineExpose({
  onShow
})
</script>

<style lang="scss">
.my-publish-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: calc(128rpx + env(safe-area-inset-bottom));
}

.tab-header {
  background-color: #fff;
  position: relative;
  border-bottom: 1rpx solid #f0f0f0;
}

.tab-list {
  display: flex;
  align-items: center;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 32rpx 0;
  position: relative;
  
  .tab-text {
    font-size: 30rpx;
    color: #666;
    font-weight: 500;
    transition: color 0.3s ease;
  }
  
  &.active .tab-text {
    color: #4CAF50;
    font-weight: bold;
  }
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 50%;
  height: 4rpx;
  background-color: #4CAF50;
  transition: left 0.3s ease;
}

.tab-content {
  flex: 1;
}

.search-section {
  background-color: #fff;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f8f8f8;
  border-radius: 32rpx;
  padding: 16rpx 24rpx;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 16rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  line-height: 1.5;
}

.products-container, .purchase-container {
  padding: 20rpx;
}

.products-list, .purchase-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.published-card {
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease;
  
  &:active {
    transform: scale(0.98);
  }
}

.card-content {
  display: flex;
  padding: 20rpx;
  gap: 20rpx;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  overflow: hidden;
  flex-shrink: 0;
  
  image {
    width: 100%;
    height: 100%;
  }
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

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

.product-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #4CAF50;
  flex: 1;
  margin-right: 16rpx;
}

.price-info {
  font-size: 26rpx;
  color: #333;
  font-weight: bold;
  white-space: nowrap;
}

.product-desc {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 16rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

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

.publish-time {
  font-size: 24rpx;
  color: #999;
}

.status-tag {
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  font-size: 22rpx;
  
  &.pending {
    background-color: #fff7e6;
    color: #fa8c16;
  }
  
  &.approved {
    background-color: #f6ffed;
    color: #52c41a;
  }
  
  &.rejected {
    background-color: #fff2f0;
    color: #ff4d4f;
  }
}

// 收购信息现在使用统一的 .published-card 样式

// 底部固定按钮
.bottom-action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  background-color: #fff;
  border-top: 1rpx solid #f0f0f0;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  z-index: 1000;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
}

.action-btn {
  width: 100%;
  height: 88rpx;
  background-color: #4CAF50;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s ease;
  box-sizing: border-box;
  
  &:active {
    background-color: #45a049;
  }
  
  .btn-text {
    font-size: 32rpx;
    color: #fff;
    font-weight: bold;
  }
}

.publish-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  display: flex;
  align-items: flex-end;
}

.publish-content {
  width: 100%;
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 0;
}

.publish-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .publish-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .publish-close {
    font-size: 36rpx;
    color: #999;
  }
}

.publish-options {
  padding: 20rpx;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 24rpx 20rpx;
  border-radius: 12rpx;
  margin-bottom: 16rpx;
  background-color: #f8f8f8;
  transition: background-color 0.2s ease;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &:active {
    background-color: #e8f5e8;
  }
}

.option-text {
  flex: 1;
  
  .option-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    display: block;
    margin-bottom: 8rpx;
  }
  
  .option-desc {
    font-size: 26rpx;
    color: #666;
    display: block;
  }
}
</style> 