<template>
  <div class="page-container">
    <PageTitle title="协议供货商品" />
    <!-- 搜索表单区 -->
    <div class="search-form-card">
      <!-- 第一行：商品编号、商品名称、商品品牌 -->
      <div class="form-row">
        <div class="form-item">
          <span class="form-label">商品编号：</span>
          <el-input v-model="queryParams.productNo" placeholder="请输入商品编号" clearable style="flex:1" @keyup.enter="handleQuery" />
        </div>
        <div class="form-item">
          <span class="form-label">商品名称：</span>
          <el-input v-model="queryParams.itemName" placeholder="请输入商品名称" clearable style="flex:1" @keyup.enter="handleQuery" />
        </div>
      </div>
      <!-- 第二行：售价区间、商品类别 -->
      <div class="form-row">
        <div class="form-item">
          <span class="form-label">售价区间：</span>
          <el-input v-model="queryParams.minPrice" placeholder="售价最低" style="width: 110px" />
          <span class="range-sep">-</span>
          <el-input v-model="queryParams.maxPrice" placeholder="售价最高" style="width: 110px" />
        </div>
        <div class="form-item category-item">
          <span class="form-label">商品类别：</span>
          <el-select v-model="queryParams.topCategoryId" placeholder="请选择" clearable @change="handleFirstCategoryChange" style="flex:1">
            <el-option v-for="item in categoryList1" :key="item.id" :label="item.categoryName" :value="item.id" />
          </el-select>
          <el-select v-model="queryParams.middleCategoryId" placeholder="请选择" clearable :disabled="!queryParams.topCategoryId" @change="handleSecondCategoryChange" style="flex:1">
            <el-option v-for="item in categoryList2" :key="item.id" :label="item.categoryName" :value="item.id" />
          </el-select>
          <el-select v-model="queryParams.bottomCategoryId" placeholder="请选择" clearable :disabled="!queryParams.middleCategoryId" style="flex:1">
            <el-option v-for="item in categoryList3" :key="item.id" :label="item.categoryName" :value="item.id" />
          </el-select>
        </div>
      </div>
      <!-- 第三行：操作按钮 -->
      <div class="form-actions">
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">清除选择</el-button>
      </div>
    </div>

    <!-- 商品内容区 -->
    <div class="content-card">
      <!-- 排序栏 -->
      <div class="sort-bar">
        <el-button
          :class="['sort-btn', { active: queryParams.sortField === '1' }]"
          size="small"
          @click="handleSortToggle('1')"
        >默认排序 <el-icon><Sort /></el-icon></el-button>
        <el-button
          :class="['sort-btn', { active: queryParams.sortField === '3' }]"
          size="small"
          @click="handleSortToggle('3')"
        >价格排序 <el-icon><Sort /></el-icon></el-button>
      </div>
      <!-- 商品列表 -->
      <div v-if=" productList.length > 0">
        <div class="product-grid">
          <div v-for="(item, index) in productList" :key="item.id || index" class="product-card">
            <div class="product-image" @click="onPath(`/item?id=${item.id}`)">
              <el-image :src="item.productImage" fit="contain">
                <template #error
                  ><div class="image-placeholder">
                    <el-icon :size="40" color="#ccc"><Picture /></el-icon></div
                ></template>
              </el-image>
            </div>
            <div class="product-info">
              <div class="product-name">{{ item.itemName }}</div>
              <div class="product-price">
                <span class="price-tag">协议价</span>
                <span class="current-price">¥{{ formatPrice(item.agreementPrice || item.price) }}</span>
                <span class="original-price">¥{{ formatPrice(item.marketPrice) }}</span>
                <div class="add-cart" @click="handleAddCart(item)">
                  <el-icon><Plus /></el-icon>
                </div>
              </div>
            </div>
          </div>
        </div>
        <TablePagination
          v-model:page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          @change="loadProductList"
        />
      </div>
      <!-- 空状态 -->
      <div v-else class="empty-area">
        <el-icon :size="80" color="#d0d0d0"><Box /></el-icon>
        <p class="empty-title">未收到任何系统消息</p>
        <p class="empty-desc">
          <a href="#" class="empty-link">还不快来建立自己的产品专区~~</a>
          与我们签订产品协议价格，您将拥有您的专属产品专区，价格更低、服务更优！<br />
          如需要建立自己专属的协议产品专区请联系您的专属客服【取客服联系方式】或致电400-111-0027。
        </p>
        <el-button class="policy-btn">了解协议供货政策</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Picture, Plus, Sort, Box } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { PageTitle, TablePagination } from '@/components';
import { getAgreementSupplyProductList, addProductShoppingCart } from '@/api/goods/index';
import { getProductCategoryList } from '@/api/home/index';
import { onPath } from '@/utils/siteConfig';

const queryParams = reactive({
  pageNum: 1,
  pageSize: 15,
  searchKeyword: '',
  productNo: '',
  itemName: '',
  brand: '',
  minPrice: '',
  maxPrice: '',
  topCategoryId: '' as number | string,
  middleCategoryId: '' as number | string,
  bottomCategoryId: '' as number | string,
  sortField: '',
  sortOrder: ''
});
const total = ref(0);

interface ProductItem {
  id?: number | string;
  itemName?: string;
  productImage?: string;
  price?: string | number;
  agreementPrice?: string | number;
  memberPrice?: string | number;
  [key: string]: any;
}

const productList = ref<ProductItem[]>([]);

// 商品类别列表
interface CategoryItem {
  id?: number | string;
  categoryName?: string;
  [key: string]: any;
}

const categoryList1 = ref<CategoryItem[]>([]);
const categoryList2 = ref<CategoryItem[]>([]);
const categoryList3 = ref<CategoryItem[]>([]);

// 加载一级商品类别
const loadCategoryList = async () => {
  try {
    const res = await getProductCategoryList({ classLevel: 1 });
    if (res.data) {
      categoryList1.value = res.data;
    }
  } catch (error) {
    console.error('获取商品类别失败:', error);
  }
};

// 一级类别变化：加载二级，清空二三级选中
const handleFirstCategoryChange = async (val: number | string) => {
  queryParams.middleCategoryId = '';
  queryParams.bottomCategoryId = '';
  categoryList2.value = [];
  categoryList3.value = [];
  if (!val) return;
  try {
    const res = await getProductCategoryList({ classLevel: 2, parentId: val });
    if (res.data) categoryList2.value = res.data;
  } catch (error) {
    console.error('获取二级类别失败:', error);
  }
};

// 二级类别变化：加载三级，清空三级选中
const handleSecondCategoryChange = async (val: number | string) => {
  queryParams.bottomCategoryId = '';
  categoryList3.value = [];
  if (!val) return;
  try {
    const res = await getProductCategoryList({ classLevel: 3, parentId: val });
    if (res.data) categoryList3.value = res.data;
  } catch (error) {
    console.error('获取三级类别失败:', error);
  }
};

// 加载协议供货商品列表
const loadProductList = async () => {
  try {
    const res = await getAgreementSupplyProductList({ ...queryParams });

    if (res.rows) {
      productList.value = res.rows;
      total.value = res.total;
    }
  } catch (error) {
    console.error('获取协议供货商品失败:', error);
    ElMessage.error('获取商品列表失败');
  }
};

// 查询处理
const handleQuery = () => {
  queryParams.pageNum = 1;
  loadProductList();
};

// 重置
const handleReset = () => {
  queryParams.searchKeyword = '';
  queryParams.productNo = '';
  queryParams.itemName = '';
  queryParams.brand = '';
  queryParams.minPrice = '';
  queryParams.maxPrice = '';
  queryParams.topCategoryId = '';
  queryParams.middleCategoryId = '';
  queryParams.bottomCategoryId = '';
  queryParams.sortField = '';
  queryParams.sortOrder = '';
  categoryList2.value = [];
  categoryList3.value = [];
  queryParams.pageNum = 1;
  loadProductList();
};

// 排序切换
const handleSortToggle = (field: string) => {
  if (queryParams.sortField === field) {
    queryParams.sortOrder = queryParams.sortOrder === 'Asc' ? 'Desc' : 'Asc';
  } else {
    queryParams.sortField = field;
    queryParams.sortOrder = 'Asc';
  }
  queryParams.pageNum = 1;
  loadProductList();
};

// 添加购物车
const handleAddCart = async (item: ProductItem) => {
  try {
    await addProductShoppingCart({ productId: item.id, productNum: 1 });
    ElMessage.success('已加入购物车');
  } catch (error) {
    console.error('加入购物车失败:', error);
    ElMessage.error('加入购物车失败');
  }
};

// 格式化价格显示
const formatPrice = (price: string | number | undefined): string => {
  if (price === undefined || price === null) return '0';
  const numPrice = typeof price === 'string' ? parseFloat(price) : price;
  return numPrice.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

// 初始化加载
onMounted(() => {
  loadCategoryList();
  loadProductList();
});
</script>

<style scoped lang="scss">
.page-container {
  background: #f5f5f5;
  min-height: 100%;
  padding-bottom: 20px;
}

// 搜索表单卡片
.search-form-card {
  background: #fff;
  border-radius: 4px;
  padding: 20px 24px 16px;
  margin-bottom: 12px;

  .form-row {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 16px;

    .form-item {
      display: flex;
      align-items: center;
      flex: 1;

      &.category-item {
        flex: 2;
        gap: 8px;
      }

      .form-label {
        font-size: 14px;
        color: #333;
        white-space: nowrap;
        min-width: 70px;
      }

      .range-sep {
        margin: 0 8px;
        color: #999;
      }
    }
  }

  .form-actions {
    display: flex;
    align-items: center;
    gap: 10px;
    padding-top: 4px;
  }
}

// 商品内容卡片
.content-card {
  background: #fff;
  border-radius: 4px;
  padding: 16px 20px;
}

// 排序栏
.sort-bar {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;

  .sort-btn {
    border-color: #d9d9d9;
    color: #555;

    &.active {
      border-color: #409eff;
      color: #409eff;
      background: #ecf5ff;
    }
  }
}

// 商品网格
.product-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 15px;
  margin-bottom: 16px;
}

.product-card {
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.2s;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .product-image {
    height: 160px;
    background: #f9f9f9;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px;

    .el-image {
      width: 100%;
      height: 100%;
    }

    .image-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f5f5;
    }
  }

  .product-info {
    padding: 12px;

    .product-name {
      font-size: 13px;
      color: #333;
      line-height: 1.4;
      height: 36px;
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      margin-bottom: 8px;
    }

    .product-price {
      display: flex;
      align-items: center;
      gap: 5px;
      position: relative;

      .price-tag {
        font-size: 12px;
        color: #e60012;
      }

      .current-price {
        font-size: 16px;
        font-weight: bold;
        color: #e60012;
      }

      .original-price {
        font-size: 12px;
        color: #999;
        text-decoration: line-through;
      }

      .add-cart {
        position: absolute;
        right: 0;
        bottom: 0;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        border: 1px solid #e60012;
        color: #e60012;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.2s;

        &:hover {
          background: #e60012;
          color: #fff;
        }
      }
    }
  }
}

// 空状态区域
.empty-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 20px;

  .empty-title {
    font-size: 16px;
    color: #999;
    margin: 16px 0 12px;
  }

  .empty-desc {
    font-size: 13px;
    color: #666;
    text-align: center;
    line-height: 1.8;
    margin-bottom: 24px;
  }

  .empty-link {
    color: #e60012;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }

  .policy-btn {
    width: 200px;
    border-color: #d9d9d9;
  }
}
</style>
