<template>
  <div class="edit-spec-form">
    <div class="beer-info">
      <div class="beer-header">
        <img :src="tapBeer.beerCover || '/images/default-beer.png'" class="beer-image" />
        <div class="beer-details">
          <h4 class="beer-name">{{ tapBeer.beerName }}</h4>
          <div class="beer-brand">{{ tapBeer.brandName }}</div>
          <div class="beer-style">{{ tapBeer.beerStyles || tapBeer.customStyle }}</div>
          <div class="tap-info">
            <el-tag type="info" size="small">酒头编号：{{ tapBeer.tapNo }}</el-tag>
          </div>
        </div>
      </div>
    </div>

    <el-divider />

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="规格价格" prop="specList">
        <div class="spec-list">
          <div class="spec-header">
            <span>规格名称</span>
            <span>价格 (元)</span>
            <!-- <span>操作</span> -->
          </div>
          
          <div
            v-for="(spec, index) in form.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="form.specList.length > 1"
                type="danger"
                size="small"
                @click="removeSpec(index)"
              >
                删除
              </el-button>
            </div>
          </div>
          
          <div class="add-spec">
            <el-button 
              type="primary" 
              plain 
              size="small" 
              @click="addSpec"
              :disabled="form.specList.length >= 2"
            >
              <el-icon><Plus /></el-icon>
              添加规格
            </el-button>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        保存修改
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const props = defineProps({
  tapBeer: {
    type: Object,
    required: true
  }
})

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

// 响应式数据
const formRef = ref()
const submitting = ref(false)

const form = reactive({
  tapId: null,
  specList: []
})

// 表单验证规则
const rules = reactive({
  specList: [
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('至少需要添加一个规格'))
        } else {
          let hasError = false
          for (let i = 0; i < value.length; i++) {
            const spec = value[i]
            if (!spec.specName || spec.specName.trim() === '') {
              callback(new Error(`第${i + 1}个规格的名称不能为空`))
              hasError = true
              break
            }
            if (spec.specPrice === null || spec.specPrice === undefined || spec.specPrice < 0) {
              callback(new Error(`第${i + 1}个规格的价格不能为空或负数`))
              hasError = true
              break
            }
          }
          if (!hasError) {
            callback()
          }
        }
      }
    }
  ]
})

// 初始化表单
const initForm = (tapBeer) => {
  form.tapId = tapBeer.tapId || tapBeer.id
  
  // 初始化规格列表
  if (tapBeer.specList && tapBeer.specList.length > 0) {
    form.specList = tapBeer.specList.map(spec => ({
      id: spec.id,
      specName: spec.specName,
      specPrice: parseFloat(spec.specPrice) || 0,
      sortOrder: spec.sortOrder || 1
    }))
  } else {
    // 如果没有规格列表，创建默认规格
    form.specList = [
      {
        specName: '330ml',
        specPrice: 0,
        sortOrder: 1
      }
    ]
  }
}

// 监听tapBeer变化，初始化表单
watch(() => props.tapBeer, (newTapBeer) => {
  if (newTapBeer) {
    initForm(newTapBeer)
  }
}, { immediate: true })

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

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

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    const submitData = {
      tapId: form.tapId,
      specList: form.specList.map((spec, index) => ({
        ...spec,
        sortOrder: index + 1
      }))
    }
    
    submitting.value = true
    emit('submit', submitData)
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

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

// 组件挂载时初始化
onMounted(() => {
  if (props.tapBeer) {
    initForm(props.tapBeer)
  }
})
</script>

<style scoped>
.edit-spec-form {
  padding: 20px;
}

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

.beer-header {
  display: flex;
  align-items: center;
  gap: 16px;
}

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

.beer-details {
  flex: 1;
}

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

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

.beer-style {
  color: #67c23a;
  font-size: 14px;
  margin-bottom: 8px;
}

.tap-info {
  margin-top: 8px;
}

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

.spec-header {
  display: grid;
  grid-template-columns: 1fr 1fr 100px;
  gap: 16px;
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
  color: #606266;
  font-size: 14px;
}

.spec-row {
  display: grid;
  grid-template-columns: 1fr 1fr 100px;
  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;
}

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

.form-actions .el-button {
  margin-left: 10px;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>