<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>
	import {
		getProductInfoList
	} from '@/api/services/productInfo.js';
	import dictMixin from '@/utils/mixins/dictMixin';
	import storage from "@/utils/storage.js";
export default {
	mixins: [dictMixin],
  data() {
    return {
      activeTab: 'published',
      searchKeyword: '',
      purchaseSearchKeyword: '',
      showPublishModal: false,
      pageNum: 1,
      pageSize: 10,
      noMoreData: false,
      isLoading: false,
      isRefreshing: false,
	  dictTypeList: ['agricultural_unit'],
	  currentUserInfo: storage.getUserInfo(),
      // 我的发布列表
      publishedProductsList: [],
      // 收购信息列表
      purchaseList: [],
	  productsList: [], // 二和一存储
    }
  },
  
  computed: {
    filteredPublishedProducts() {
      // let products = this.publishedProductsList;
      let products = this.productsList;
      
      // if (this.searchKeyword.trim()) {
      //   const keyword = this.searchKeyword.trim().toLowerCase();
      //   products = products.filter(item => 
      //     item.name.toLowerCase().includes(keyword) || 
      //     item.description.toLowerCase().includes(keyword)
      //   );
      // }
      
      return products;
    },
    
    filteredPurchaseList() {
      // let list = this.purchaseList;
      let list = this.productsList;
      
      // if (this.purchaseSearchKeyword.trim()) {
      //   const keyword = this.purchaseSearchKeyword.trim().toLowerCase();
      //   list = list.filter(item => 
      //     item.title.toLowerCase().includes(keyword) || 
      //     item.category.toLowerCase().includes(keyword)
      //   );
      // }
      
      return list;
    }
  },
  onShow() {
  	// console.log("my-publish",this.formData);
  	this.loadMyPublishInfo()
  },
  // 页面加载时获取数据
  onLoad() {
  	this.loadMyPublishInfo();
  },
  methods: {
	  // 上拉加载更多
	  loadMore() {
	  	if (!this.isLoading && !this.noMoreData) {
	  		this.pageNum++;
	  		this.loadMyPublishInfo();
	  	}
	  },
	  getImageUrl(item) {
	  	// 默认返回url或path
	  	if (item == null) return
	  	const imageUrls = item.split(',');
	  	// console.log("imageUrls", imageUrls);
	  	return imageUrls[0];
	  },
	  getUnitLabel(value) {
	  	const unit = this.dictData.agricultural_unit.find(u => u.dictValue == value)
	  	return unit ? unit.dictLabel : ''
	  },
	  loadMyPublishInfo(keyword) {
	  	this.isLoading = true;
	  	uni.showLoading({
	  		title: '加载中'
	  	});
	  	// 构建查询参数
	  	const params = {
	  		pageNum: this.pageNum,
	  		pageSize: this.pageSize,
			createBy: this.currentUserInfo.username,
			type: 0 // 默认查询出售信息
	  	};
	  	if (keyword != null && keyword != '') {
	  		params.searchKeyword = keyword
	  	}
	  
	  	// 分类逻辑
	  	if (this.activeTab !== 'published' ) {
	  		// 默认场景：推荐查询
	  		params.type = 1;
	  	}
	  
	  	getProductInfoList(params).then(res => {
	  		if (res.data.code === 200) {
	  			const {
	  				rows,
	  				total
	  			} = res.data;
	  			if (this.pageNum === 1) {
	  				this.productsList = rows;
	  			} else {
	  				this.productsList = [...this.productsList, ...rows];
	  			}
	  			// 判断是否还有更多数据
	  			this.noMoreData = this.productsList.length >= total;
	  			uni.hideLoading();
	  		} else {
	  			uni.showToast({
	  				title: res.data.msg || '获取农品列表失败',
	  				icon: 'none'
	  			});
	  		}
	  	}).catch(err => {
	  		console.error('获取农品列表失败:', err);
	  		uni.showToast({
	  			title: '获取农品列表失败',
	  			icon: 'none'
	  		});
	  	}).finally(() => {
	  		this.isLoading = false;
	  		this.isRefreshing = false;
	  	});
	  },
    switchTab(tab) {
      this.activeTab = tab;
	  // this.publishedProductsList = [] // 切换时置空数据数组
	  // this.purchaseList = [] 
	  this.productsList = []
	  // 滚动到当前分类位置
	  this.loadMyPublishInfo(this.searchKeyword.trim())
    },
    
    getStatusText(status) {
      const statusMap = {
        1: '审核中',
        2: '已上架',
        3: '已下架',
		4: '未通过'
      };
      return statusMap[status] || '未知';
    },
	getStatusClassName(status) {
	  const statusMapClassName = {
	    1: 'pending',
	    2: 'approved',
	    3: 'rejected',
		4: 'rejected'
	  };
	  return statusMapClassName[status] || '未知';
	},
    
    handleSearch() {
	  const keyword = this.searchKeyword.trim().toLowerCase();
	  this.loadMyPublishInfo(keyword)
    },
    
    navigateToDetail(product) {
      uni.navigateTo({
        url: `/pages/service/sales-detail?id=${product.id}&type=sale&name=${encodeURIComponent(product.title)}&source=myPublish&status=${product.status}`
      });
    },
    
    navigateToPurchaseDetail(item) {
      uni.navigateTo({
        url: `/pages/service/sales-detail?id=${item.id}&type=purchase&title=${encodeURIComponent(item.title)}&source=myPublish&status=${item.status}`
      });
    },
    
    navigateToPublish() {
      this.showPublishModal = false;
      uni.navigateTo({
        url: '/pages/service/sales-publish'
      });
    },
    
    navigateToPurchasePublish() {
      this.showPublishModal = false;
      uni.navigateTo({
        url: '/pages/service/purchase-publish'
      });
    },
  }
}
</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> 