<template>
  <div class="beer-search-page">
    <el-card class="search-card">
      <div class="search-header">
        <h2>酒款搜索</h2>
        <p>快速搜索和浏览酒款信息，支持多种搜索方式和筛选条件</p>
      </div>

      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :model="searchForm" inline size="large">
          <el-form-item>
            <el-input
              v-model="searchForm.keyword"
              placeholder="输入酒款名称、品牌名称或风格关键词"
              style="width: 400px"
              @keyup.enter="handleSearch"
              clearable
            >
              <template #prepend>
                <el-select v-model="searchForm.type" style="width: 120px">
                  <el-option label="智能搜索" value="intelligent" />
                  <el-option label="酒款搜索" value="beer" />
                  <el-option label="品牌搜索" value="brand" />
                  <el-option label="风格搜索" value="style" />
                </el-select>
              </template>
              <template #append>
                <el-button type="primary" @click="handleSearch" :loading="searching">
                  搜索
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>

      <!-- 快速搜索标签 -->
      <div class="quick-search">
        <span class="quick-label">热门搜索:</span>
        <el-tag
          v-for="tag in quickSearchTags"
          :key="tag"
          @click="quickSearch(tag)"
          class="quick-tag"
          type="info"
          effect="plain"
        >
          {{ tag }}
        </el-tag>
      </div>
    </el-card>

    <!-- 筛选和结果区域 -->
    <el-row :gutter="20">
      <!-- 筛选侧边栏 -->
      <el-col :span="6">
        <el-card class="filter-card">
          <template #header>
            <div class="filter-header">
              <span>筛选条件</span>
              <el-button text type="primary" size="small" @click="resetFilters">
                重置
              </el-button>
            </div>
          </template>

          <div class="filter-content">
            <!-- 品牌方筛选 -->
            <div class="filter-group">
              <h4>品牌方</h4>
              <el-select
                v-model="filterForm.breweryId"
                placeholder="选择品牌方"
                style="width: 100%"
                clearable
                filterable
                @change="applyFilters"
              >
                <el-option
                  v-for="brewery in breweryOptions"
                  :key="brewery.id"
                  :label="brewery.brandName"
                  :value="brewery.id"
                />
              </el-select>
            </div>

            <!-- 价格筛选 -->
            <div class="filter-group">
              <h4>价格范围</h4>
              <div class="price-range">
                <el-input-number
                  v-model="filterForm.minPrice"
                  placeholder="最低价"
                  :min="0"
                  style="width: 100%"
                  @change="applyFilters"
                />
                <span class="range-separator">-</span>
                <el-input-number
                  v-model="filterForm.maxPrice"
                  placeholder="最高价"
                  :min="0"
                  style="width: 100%"
                  @change="applyFilters"
                />
              </div>
            </div>

            <!-- 风格筛选 -->
            <div class="filter-group">
              <h4>酒款风格</h4>
              <div class="style-tags">
                <el-tag
                  v-for="style in popularStyles"
                  :key="style"
                  :type="filterForm.style === style ? 'primary' : 'info'"
                  :effect="filterForm.style === style ? 'dark' : 'plain'"
                  size="small"
                  @click="toggleStyle(style)"
                  class="style-tag"
                >
                  {{ style }}
                </el-tag>
              </div>
            </div>

            <!-- 排序方式 -->
            <div class="filter-group">
              <h4>排序方式</h4>
              <el-radio-group 
                v-model="filterForm.orderBy" 
                @change="applyFilters"
                style="width: 100%"
              >
                <el-radio label="launch_date" style="width: 100%; margin-bottom: 8px;">
                  上市时间
                </el-radio>
                <el-radio label="beer_overall_rating" style="width: 100%; margin-bottom: 8px;">
                  评分排序
                </el-radio>
                <el-radio label="beer_reviews_count" style="width: 100%; margin-bottom: 8px;">
                  评论数量
                </el-radio>
                <el-radio label="market_price" style="width: 100%; margin-bottom: 8px;">
                  价格排序
                </el-radio>
              </el-radio-group>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 搜索结果区域 -->
      <el-col :span="18">
        <el-card class="results-card">
          <!-- 结果统计 -->
          <div v-if="hasSearched" class="results-header">
            <div class="results-info">
              <span class="results-count">找到 {{ pagination.total }} 款相关酒款</span>
              <span v-if="searchForm.keyword" class="search-keyword">
                搜索: "{{ searchForm.keyword }}"
              </span>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="searching" class="loading-state">
            <el-skeleton :rows="6" animated />
          </div>

          <!-- 空状态 -->
          <div v-else-if="searchResults.length === 0 && hasSearched" class="empty-state">
            <el-empty description="未找到相关酒款">
              <el-button type="primary" @click="resetSearch">重新搜索</el-button>
            </el-empty>
          </div>

          <!-- 默认推荐 -->
          <div v-else-if="!hasSearched" class="default-state">
            <div class="recommendation">
              <h3>热门推荐</h3>
              <p>试试搜索这些热门酒款或品牌</p>
              <div class="recommendation-grid">
                <div
                  v-for="item in recommendations"
                  :key="item.id"
                  class="recommendation-item"
                  @click="quickSearch(item.name)"
                >
                  <img :src="item.image" :alt="item.name" />
                  <span>{{ item.name }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 搜索结果列表 -->
          <div v-else class="beer-results">
            <div
              v-for="beer in searchResults"
              :key="beer.id"
              class="beer-result-item"
            >
              <div class="beer-image-section">
                <img :src="beer.cover || '/images/default-beer.png'" class="beer-image" />
                <div class="beer-actions">
                  <el-button type="primary" size="small" @click="addToTap(beer)">
                    快速上枪
                  </el-button>
                  <el-button size="small" @click="viewDetails(beer)">
                    查看详情
                  </el-button>
                </div>
              </div>

              <div class="beer-info-section">
                <div class="beer-header">
                  <h4 class="beer-name">{{ beer.beerName }}</h4>
                  <div class="beer-brand">{{ beer.brandName }}</div>
                </div>

                <div class="beer-tags">
                  <el-tag size="small" type="success">
                    {{ beer.beerStyles || beer.customStyle || '未知风格' }}
                  </el-tag>
                  <el-tag v-if="beer.isOnSale" size="small" type="primary">在售</el-tag>
                  <el-tag v-if="beer.isNew" size="small" type="warning">新品</el-tag>
                </div>

                <div class="beer-specs">
                  <div v-if="beer.abv" class="spec-item">
                    <span class="spec-label">酒精度:</span>
                    <span class="spec-value">{{ beer.abv }}%</span>
                  </div>
                  <div v-if="beer.ibu" class="spec-item">
                    <span class="spec-label">苦度:</span>
                    <span class="spec-value">{{ beer.ibu }} IBU</span>
                  </div>
                  <div v-if="beer.og" class="spec-item">
                    <span class="spec-label">原麦汁:</span>
                    <span class="spec-value">{{ beer.og }}°P</span>
                  </div>
                </div>

                <div class="beer-description">
                  <p>{{ beer.description || beer.intro || '暂无描述' }}</p>
                </div>

                <div class="beer-footer">
                  <div class="beer-price">
                    <span class="price-label">市场价:</span>
                    <span class="price-value">￥{{ beer.marketPrice || '未设定' }}</span>
                  </div>
                  <div v-if="beer.beerOverallRating" class="beer-rating">
                    <el-rate
                      :model-value="beer.beerOverallRating"
                      disabled
                      size="small"
                      show-score
                      text-color="#ff9900"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div v-if="searchResults.length > 0" class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.pageNum"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快速上枪对话框 -->
    <el-dialog v-model="addTapDialog.visible" title="快速上枪" width="600px">
      <AddBeerForm 
        :selected-beer="addTapDialog.beer"
        @submit="handleAddToTap" 
        @cancel="addTapDialog.visible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { commonSearch, getAllBreweries, getBeerInfo } from '@/api/barmgr/platform'
import AddBeerForm from '../tap/components/AddBeerForm.vue'

// 响应式数据
const searching = ref(false)
const hasSearched = ref(false)
const searchResults = ref([])
const breweryOptions = ref([])

const searchForm = reactive({
  keyword: '',
  type: 'intelligent'
})

const filterForm = reactive({
  breweryId: null,
  minPrice: null,
  maxPrice: null,
  style: null,
  orderBy: 'launch_date'
})

const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const addTapDialog = reactive({
  visible: false,
  beer: null
})

// 快速搜索标签
const quickSearchTags = ref([
  'IPA', 'Lager', 'Stout', 'Wheat Beer', 'Pilsner', 
  '精酿啤酒', '小麦啤酒', '世涛', '拉格', '淡色艾尔'
])

// 热门风格
const popularStyles = ref([
  'IPA', 'Lager', 'Stout', 'Wheat Beer', 'Pilsner', 
  'Porter', 'Saison', 'Sour Beer', 'Belgian Ale', 'Pale Ale'
])

// 推荐内容
const recommendations = ref([
  { id: 1, name: 'IPA', image: '/images/beer-style-ipa.jpg' },
  { id: 2, name: 'Lager', image: '/images/beer-style-lager.jpg' },
  { id: 3, name: 'Stout', image: '/images/beer-style-stout.jpg' },
  { id: 4, name: '精酿啤酒', image: '/images/craft-beer.jpg' }
])

// 搜索方法
const handleSearch = async () => {
  if (!searchForm.keyword || searchForm.keyword.trim().length < 2) {
    ElMessage.warning('请输入至少2个字符的搜索关键词')
    return
  }

  try {
    searching.value = true
    hasSearched.value = true
    
    const params = {
      search: searchForm.keyword,
      type: searchForm.type,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    }
    
    // 添加筛选条件
    if (filterForm.breweryId) params.brewery_id = filterForm.breweryId
    if (filterForm.minPrice) params.min_price = filterForm.minPrice
    if (filterForm.maxPrice) params.max_price = filterForm.maxPrice
    if (filterForm.style) params.style = filterForm.style
    if (filterForm.orderBy) params.orderBy = filterForm.orderBy

    const response = await commonSearch(params)
    
    if (response.code === 200) {
      searchResults.value = response.data.beers || []
      pagination.total = response.data.total || 0
    } else {
      throw new Error(response.msg || '搜索失败')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败: ' + error.message)
    searchResults.value = []
  } finally {
    searching.value = false
  }
}

// 快速搜索
const quickSearch = (keyword) => {
  searchForm.keyword = keyword
  searchForm.type = 'intelligent'
  pagination.pageNum = 1
  handleSearch()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.type = 'intelligent'
  hasSearched.value = false
  searchResults.value = []
  pagination.pageNum = 1
  pagination.total = 0
}

// 重置筛选
const resetFilters = () => {
  filterForm.breweryId = null
  filterForm.minPrice = null
  filterForm.maxPrice = null
  filterForm.style = null
  filterForm.orderBy = 'launch_date'
  if (hasSearched.value) {
    pagination.pageNum = 1
    handleSearch()
  }
}

// 应用筛选
const applyFilters = () => {
  if (hasSearched.value) {
    pagination.pageNum = 1
    handleSearch()
  }
}

// 切换风格筛选
const toggleStyle = (style) => {
  filterForm.style = filterForm.style === style ? null : style
  applyFilters()
}

// 查看详情
const viewDetails = async (beer) => {
  try {
    const response = await getBeerInfo(beer.id)
    if (response.code === 200) {
      console.log('酒款详情:', response.data)
      ElMessage.success('查看详情功能待实现')
    }
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

// 快速上枪
const addToTap = (beer) => {
  addTapDialog.beer = beer
  addTapDialog.visible = true
}

// 处理上枪
const handleAddToTap = (data) => {
  console.log('上枪数据:', data)
  ElMessage.success('上枪功能待实现')
  addTapDialog.visible = false
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.pageNum = 1
  if (hasSearched.value) {
    handleSearch()
  }
}

const handleCurrentChange = (val) => {
  pagination.pageNum = val
  if (hasSearched.value) {
    handleSearch()
  }
}

// 获取品牌方列表
const fetchBreweries = async () => {
  try {
    const response = await getAllBreweries({
      pageNum: 1,
      pageSize: 100
    })
    if (response.code === 200) {
      breweryOptions.value = response.data.rows || []
    }
  } catch (error) {
    console.error('获取品牌方列表失败:', error)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchBreweries()
})
</script>

<style scoped>
.beer-search-page {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-header {
  text-align: center;
  margin-bottom: 30px;
}

.search-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.search-header p {
  margin: 0;
  color: #909399;
}

.search-section {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.quick-search {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.quick-label {
  color: #909399;
  font-size: 14px;
}

.quick-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.quick-tag:hover {
  color: #409eff;
  border-color: #409eff;
}

.filter-card {
  height: fit-content;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.filter-group h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
}

.price-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-separator {
  color: #909399;
}

.style-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.style-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.results-card {
  min-height: 600px;
}

.results-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.results-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.results-count {
  font-weight: bold;
  color: #303133;
}

.search-keyword {
  color: #409eff;
}

.loading-state,
.empty-state,
.default-state {
  padding: 40px;
  text-align: center;
}

.recommendation h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.recommendation p {
  margin: 0 0 30px 0;
  color: #909399;
}

.recommendation-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 20px;
}

.recommendation-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.recommendation-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.recommendation-item img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
}

.beer-results {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.beer-result-item {
  display: flex;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  transition: all 0.3s;
}

.beer-result-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.beer-image-section {
  width: 120px;
  margin-right: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.beer-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.beer-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.beer-info-section {
  flex: 1;
}

.beer-header {
  margin-bottom: 12px;
}

.beer-name {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin: 0 0 4px 0;
}

.beer-brand {
  color: #909399;
  font-size: 14px;
}

.beer-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.beer-specs {
  display: flex;
  gap: 20px;
  margin-bottom: 12px;
}

.spec-item {
  display: flex;
  gap: 4px;
}

.spec-label {
  color: #909399;
  font-size: 12px;
}

.spec-value {
  color: #606266;
  font-size: 12px;
  font-weight: bold;
}

.beer-description {
  margin-bottom: 12px;
}

.beer-description p {
  margin: 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

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

.beer-price {
  display: flex;
  align-items: center;
  gap: 8px;
}

.price-label {
  color: #909399;
  font-size: 14px;
}

.price-value {
  color: #e6a23c;
  font-size: 18px;
  font-weight: bold;
}

.pagination-container {
  margin-top: 30px;
  text-align: center;
}
</style>