<template>
  <div class="beer-selection-wizard">
    <!-- 步骤条 -->
    <el-steps :active="currentStep" finish-status="success" align-center>
      <el-step title="选择酒款" description="搜索并选择要上枪的酒款"></el-step>
      <el-step title="配置规格" description="设置售卖规格和价格"></el-step>
      <el-step title="确认上枪" description="确认信息并完成上枪"></el-step>
    </el-steps>

    <div class="wizard-content">
      <!-- 步骤1: 选择酒款 -->
      <div v-show="currentStep === 0" class="step-content">
        <el-card shadow="never">
          <template #header>
            <div class="step-header">
              <h3>第一步：选择酒款</h3>
              <p>搜索酒款数据库，选择要上枪的酒款</p>
            </div>
          </template>

          <!-- 搜索区域 -->
          <div class="search-section">
            <el-form :model="searchForm" inline @submit.prevent="handleSearch">
              <el-form-item>
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="输入酒款名称或品牌名称搜索（至少2个字符）"
                  style="width: 400px"
                  @keyup.enter.prevent="handleSearch"
                  @input="handleSearchInput"
                  clearable
                >
                  <template #append>
                    <el-button type="primary" @click="handleSearch" :loading="searching">
                      搜索
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
          </div>

          <!-- 搜索结果 -->
          <div v-if="searching" class="loading-section">
            <el-skeleton :rows="4" animated />
          </div>

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

          <div v-else-if="!hasSearched" class="default-section">
            <el-empty description="请输入关键词搜索酒款" />
          </div>

          <div v-else class="results-section">
            <div class="results-header">
              <span class="results-count">找到 {{ searchResults.length }} 款相关酒款</span>
            </div>
            
            <div class="beer-grid">
              <div
                v-for="beer in searchResults"
                :key="beer.id"
                class="beer-card"
                :class="{ selected: selectedBeer?.id === beer.id }"
                @click="selectBeer(beer)"
              >
                <div class="beer-image">
                  <img :src="beer.cover || '/images/default-beer.png'" :alt="beer.beerName" />
                </div>
                <div class="beer-info">
                  <h4 class="beer-name">{{ beer.beerName }}</h4>
                  <p class="beer-brand">{{ beer.brandName }}</p>
                  <div class="beer-tags">
                    <el-tag size="small" type="success">
                      {{ beer.beerStyles || beer.customStyle || '未知风格' }}
                    </el-tag>
                  </div>
                  <div class="beer-specs">
                    <span v-if="beer.abv" class="spec">{{ beer.abv }}%</span>
                    <span v-if="beer.ibu" class="spec">{{ beer.ibu }} IBU</span>
                  </div>
                  <!-- <div class="beer-price">
                    <span class="price">￥{{ beer.marketPrice || '未设定' }}</span>
                  </div> -->
                </div>
                <div v-if="selectedBeer?.id === beer.id" class="selected-indicator">
                  <el-icon><Check /></el-icon>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 步骤2: 配置规格 -->
      <div v-show="currentStep === 1" class="step-content">
        <el-card shadow="never">
          <template #header>
            <div class="step-header">
              <h3>第二步：配置规格</h3>
              <p>为选中的酒款设置售卖规格和价格</p>
            </div>
          </template>

          <!-- 选中酒款信息 -->
          <div v-if="selectedBeer" class="selected-beer-info">
            <div class="beer-summary">
              <img :src="selectedBeer.cover || '/images/default-beer.png'" class="beer-thumb" />
              <div class="beer-details">
                <h4>{{ selectedBeer.beerName }}</h4>
                <p>{{ selectedBeer.brandName }}</p>
                <el-tag size="small" type="success">
                  {{ selectedBeer.beerStyles || selectedBeer.customStyle }}
                </el-tag>
              </div>
            </div>
          </div>

          <el-divider />

          <!-- 酒头选择 -->
          <el-form :model="configForm" :rules="configRules" ref="configFormRef" label-width="100px">
            <el-form-item label="选择酒头" prop="tapNo">
              <el-select v-model="configForm.tapNo" placeholder="请选择酒头" style="width: 200px">
                <el-option
                  v-for="tap in availableTaps"
                  :key="tap.tapNo"
                  :label="`酒头 ${tap.tapNo} ${tap.status === 1 ? '(有酒)' : '(空闲)'}`"
                  :value="tap.tapNo"
                  :disabled="tap.status === 1"
                />
              </el-select>
            </el-form-item>

            <!-- 规格价格配置 -->
            <el-form-item label="规格价格" prop="specList">
              <div class="spec-config">
                <div class="spec-header">
                  <span class="spec-label">规格名称</span>
                  <span class="spec-label">售价 (元)</span>
                  <span class="spec-label">操作</span>
                </div>
                
                <div
                  v-for="(spec, index) in configForm.specList"
                  :key="index"
                  class="spec-row"
                >
                  <el-input
                    v-model="spec.specName"
                    placeholder="如: 330ml, 500ml"
                    style="width: 150px"
                  />
                  <el-input-number
                    v-model="spec.specPrice"
                    :min="0"
                    :precision="2"
                    placeholder="0.00"
                    style="width: 150px"
                  />
                  <div class="spec-actions">
                    <el-button
                      v-if="configForm.specList.length > 1"
                      type="danger"
                      size="small"
                      text
                      @click="removeSpec(index)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
                
                <div class="add-spec">
                  <el-button type="primary" plain size="small" @click="addSpec">
                    <el-icon><Plus /></el-icon>
                    添加规格
                  </el-button>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 步骤3: 确认上枪 -->
      <div v-show="currentStep === 2" class="step-content">
        <el-card shadow="never">
          <template #header>
            <div class="step-header">
              <h3>第三步：确认上枪</h3>
              <p>请确认以下信息无误后提交</p>
            </div>
          </template>

          <div class="confirmation-content">
            <!-- 酒款信息确认 -->
            <div class="confirm-section">
              <h4>酒款信息</h4>
              <div class="confirm-beer-info">
                <img :src="selectedBeer?.cover || '/images/default-beer.png'" class="confirm-beer-image" />
                <div class="confirm-beer-details">
                  <div class="confirm-row">
                    <span class="confirm-label">酒款名称:</span>
                    <span class="confirm-value">{{ selectedBeer?.beerName }}</span>
                  </div>
                  <div class="confirm-row">
                    <span class="confirm-label">品牌名称:</span>
                    <span class="confirm-value">{{ selectedBeer?.brandName }}</span>
                  </div>
                  <div class="confirm-row">
                    <span class="confirm-label">酒款风格:</span>
                    <span class="confirm-value">{{ selectedBeer?.beerStyles || selectedBeer?.customStyle }}</span>
                  </div>
                  <!-- <div class="confirm-row">
                    <span class="confirm-label">市场价格:</span>
                    <span class="confirm-value">￥{{ selectedBeer?.marketPrice || '未设定' }}</span>
                  </div> -->
                </div>
              </div>
            </div>

            <el-divider />

            <!-- 上枪配置确认 -->
            <div class="confirm-section">
              <h4>上枪配置</h4>
              <div class="confirm-config">
                <div class="confirm-row">
                  <span class="confirm-label">选择酒头:</span>
                  <span class="confirm-value">酒头 {{ configForm.tapNo }}</span>
                </div>
                <div class="confirm-row">
                  <span class="confirm-label">规格价格:</span>
                  <div class="confirm-specs">
                    <div
                      v-for="spec in configForm.specList"
                      :key="spec.specName"
                      class="confirm-spec-item"
                    >
                      <el-tag type="info">{{ spec.specName }}: ￥{{ spec.specPrice }}</el-tag>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="wizard-actions">
      <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
      <el-button
        v-if="currentStep < 2"
        type="primary"
        @click="nextStep"
        :disabled="!canProceed"
      >
        下一步
      </el-button>
      <el-button
        v-if="currentStep === 2"
        type="success"
        @click="submitForm"
        :loading="submitting"
      >
        确认上枪
      </el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Check, Delete, Plus } from '@element-plus/icons-vue'
import { commonSearch } from '@/api/barmgr/platform'
import { getBarInfo } from '@/api/barmgr/tap'

const emit = defineEmits(['submit', 'cancel'])

// 响应式数据
const currentStep = ref(0)
const searching = ref(false)
const hasSearched = ref(false)
const submitting = ref(false)
const searchResults = ref([])
const selectedBeer = ref(null)
const availableTaps = ref([])
const configFormRef = ref()
const barInfo = ref({ tapCount: 6 }) // 酒吧信息，默认6个酒头

const searchForm = reactive({
  keyword: ''
})

const configForm = reactive({
  tapNo: null,
  specList: [
    { specName: '330ml', specPrice: 0, sortOrder: 1 }
  ]
})

// 表单验证规则
const configRules = {
  tapNo: [
    { required: true, message: '请选择酒头', trigger: 'change' },
    { 
      validator: (rule, value, callback) => {
        if (value && value > barInfo.value.tapCount) {
          callback(new Error(`酒头编号不能超过 ${barInfo.value.tapCount}`))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  specList: [
    { 
      required: true, 
      message: '请添加至少一个规格', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请添加至少一个规格'))
        } else {
          const hasEmpty = value.some(spec => !spec.specName || !spec.specPrice || spec.specPrice <= 0)
          if (hasEmpty) {
            callback(new Error('请完善规格信息，价格必须大于0'))
          } else {
            callback()
          }
        }
      }
    }
  ]
}

// 计算属性 - 是否可以进行下一步
const canProceed = computed(() => {
  if (currentStep.value === 0) {
    return selectedBeer.value !== null
  }
  if (currentStep.value === 1) {
    return configForm.tapNo && configForm.specList.length > 0 && 
           configForm.specList.every(spec => spec.specName && spec.specPrice > 0)
  }
  return true
})

let searchTimer = null

// 防抖搜索输入
const handleSearchInput = (value) => {
  if (value && value.length >= 2) {
    // 清除之前的定时器
    if (searchTimer) {
      clearTimeout(searchTimer)
    }
    
    // 设置新的定时器，500ms后执行搜索
    searchTimer = setTimeout(() => {
      handleSearch()
    }, 500)
  } else {
    searchResults.value = []
    hasSearched.value = false
  }
}

// 搜索酒款
const handleSearch = async (event) => {
  // 阻止默认行为（防止表单提交刷新页面）
  if (event && event.preventDefault) {
    event.preventDefault()
  }
  
  if (!searchForm.keyword || searchForm.keyword.trim().length < 2) {
    ElMessage.warning('请输入至少2个字符的搜索关键词')
    return
  }

  try {
    searching.value = true
    hasSearched.value = true
    
    const response = await commonSearch({
      search: searchForm.keyword,
      type: 'intelligent',
      pageNum: 1,
      pageSize: 20
    })
    
    console.log('搜索酒款响应:', response)
    
    // 修复：检查 response.data.code 而不是 response.code
    if (response.data && response.data.code === 200) {
      // 处理两种不同的数据结构
      const responseData = response.data.data
      
      if (responseData.beers) {
        // 直接酒款搜索结果：data.beers
        searchResults.value = responseData.beers || []
        console.log('酒款搜索结果:', searchResults.value)
      } else if (responseData.breweries) {
        // 品牌搜索结果：data.breweries[0].allBeers
        const breweries = responseData.breweries || []
        if (breweries.length > 0) {
          searchResults.value = breweries[0].allBeers || []
        } else {
          searchResults.value = []
        }
        console.log('品牌搜索结果:', searchResults.value)
      } else {
        searchResults.value = []
        console.log('未知数据结构，搜索结果为空')
      }
    } else {
      throw new Error((response.data && response.data.msg) || '搜索失败')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败: ' + error.message)
    searchResults.value = []
  } finally {
    searching.value = false
  }
}

// 选择酒款
const selectBeer = (beer) => {
  selectedBeer.value = beer
  
  // 根据酒款信息设置默认规格
  if (beer.marketPrice) {
    configForm.specList = [
      { specName: '330ml', specPrice: beer.marketPrice, sortOrder: 1 }
    ]
  }
}

// 添加规格
const addSpec = () => {
  configForm.specList.push({
    specName: '',
    specPrice: 0,
    sortOrder: configForm.specList.length + 1
  })
}

// 删除规格
const removeSpec = (index) => {
  if (configForm.specList.length > 1) {
    configForm.specList.splice(index, 1)
    // 重新设置排序
    configForm.specList.forEach((spec, idx) => {
      spec.sortOrder = idx + 1
    })
  } else {
    ElMessage.warning('至少需要保留一个规格')
  }
}

// 下一步
const nextStep = async () => {
  if (currentStep.value === 1) {
    try {
      await configFormRef.value.validate()
      currentStep.value++
    } catch (error) {
      console.error('表单验证失败:', error)
      return
    }
  } else {
    currentStep.value++
  }
}

// 上一步
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 提交表单
const submitForm = async () => {
  try {
    submitting.value = true
    
    const submitData = {
      tapNo: configForm.tapNo,
      beerType: 'main',
      beerId: selectedBeer.value.id,
      specList: configForm.specList.map((spec, index) => ({
        ...spec,
        sortOrder: index + 1
      }))
    }
    
    emit('submit', submitData)
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败: ' + error.message)
  } finally {
    submitting.value = false
  }
}

// 取消
const handleCancel = () => {
  emit('cancel')
}

// 初始化酒头数据
onMounted(async () => {
  try {
    // 获取酒吧信息（包含酒头数量）
    const response = await getBarInfo()
    if (response.data && response.data.code === 200) {
      barInfo.value = response.data.data
      
      // 生成酒头选项列表（1到酒头总数）
      availableTaps.value = Array.from({ length: barInfo.value.tapCount }, (_, i) => ({
        tapNo: i + 1,
        label: `酒头 ${i + 1}`
      }))
    } else {
      throw new Error('获取酒吧信息失败')
    }
  } catch (error) {
    console.error('获取酒吧信息失败:', error)
    ElMessage.error('获取酒吧信息失败，使用默认配置')
    
    // 使用默认配置
    availableTaps.value = Array.from({ length: barInfo.value.tapCount }, (_, i) => ({
      tapNo: i + 1,
      label: `酒头 ${i + 1}`
    }))
  }
})
</script>

<style scoped>
.beer-selection-wizard {
  padding: 20px;
}

.wizard-content {
  margin: 30px 0;
  min-height: 500px;
}

.step-content {
  width: 100%;
}

.step-header {
  text-align: center;
  margin-bottom: 20px;
}

.step-header h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.step-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
  text-align: center;
}

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

.results-section {
  margin-top: 20px;
}

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

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

.beer-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.beer-card {
  position: relative;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

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

.beer-card.selected {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.beer-image {
  text-align: center;
  margin-bottom: 12px;
}

.beer-image img {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  object-fit: cover;
}

.beer-info {
  text-align: center;
}

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

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

.beer-tags {
  margin-bottom: 8px;
}

.beer-specs {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-bottom: 8px;
}

.spec {
  font-size: 12px;
  color: #606266;
  background-color: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.beer-price {
  font-size: 16px;
  font-weight: bold;
  color: #e6a23c;
}

.selected-indicator {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  background-color: #67c23a;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.selected-beer-info {
  margin-bottom: 20px;
}

.beer-summary {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

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

.beer-details h4 {
  margin: 0 0 4px 0;
  color: #303133;
}

.beer-details p {
  margin: 0 0 8px 0;
  color: #606266;
}

.spec-config {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
}

.spec-header {
  display: grid;
  grid-template-columns: 1fr 1fr 80px;
  gap: 16px;
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.spec-label {
  font-weight: bold;
  color: #606266;
  font-size: 14px;
}

.spec-row {
  display: grid;
  grid-template-columns: 1fr 1fr 80px;
  gap: 16px;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  align-items: center;
}

.spec-row:last-child {
  border-bottom: none;
}

.spec-actions {
  display: flex;
  justify-content: center;
}

.add-spec {
  padding: 16px;
  text-align: center;
  background-color: #fafbfc;
}

.confirmation-content {
  max-width: 600px;
  margin: 0 auto;
}

.confirm-section {
  margin-bottom: 24px;
}

.confirm-section h4 {
  margin: 0 0 16px 0;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

.confirm-beer-info {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

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

.confirm-beer-details {
  flex: 1;
}

.confirm-row {
  display: flex;
  margin-bottom: 8px;
}

.confirm-label {
  width: 100px;
  color: #909399;
  font-size: 14px;
}

.confirm-value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.confirm-specs {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.wizard-actions {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.wizard-actions .el-button {
  margin: 0 8px;
}
</style>