<template>
  <el-dialog
    v-model="visible"
    title="智能批次推荐"
    width="700px"
    :close-on-click-modal="false"
  >
    <!-- 推荐策略选择 -->
    <div class="strategy-section">
      <el-radio-group v-model="selectedStrategy" size="small">
        <el-radio-button label="FIFO">先进先出</el-radio-button>
        <el-radio-button label="FEFO">先过期先出</el-radio-button>
        <el-radio-button label="NEAREST">最近库位</el-radio-button>
        <el-radio-button label="MANUAL">手动选择</el-radio-button>
      </el-radio-group>
      
      <div class="strategy-description">
        <el-icon><InfoFilled /></el-icon>
        <span>{{ strategyDescription }}</span>
      </div>
    </div>

    <!-- 推荐结果 -->
    <div class="recommendation-section">
      <div class="section-header">
        <h4>推荐批次列表</h4>
        <el-button 
          type="primary" 
          size="small"
          @click="applyAllRecommendations"
          :disabled="!canApplyAll"
        >
          一键应用全部推荐
        </el-button>
      </div>
      
      <el-table
        :data="recommendations"
        stripe
        border
        size="small"
        height="350px"
        v-loading="loading"
      >
        <el-table-column type="index" label="推荐" width="60" align="center">
          <template #default="{ $index }">
            <el-tag 
              v-if="$index < 3"
              :type="getRankTagType($index)"
              effect="dark"
              round
            >
              {{ $index + 1 }}
            </el-tag>
            <span v-else class="rank-text">{{ $index + 1 }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="batchNo" label="批次号" width="150">
          <template #default="{ row }">
            <div class="batch-info">
              <span class="batch-no">{{ row.batchNo }}</span>
              <el-tag 
                v-if="isNearExpiry(row.expiryDate)"
                type="warning"
                size="mini"
              >
                临期
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="库存信息" width="120">
          <template #default="{ row }">
            <div class="stock-info">
              <div class="current-stock">
                库存: <strong>{{ row.currentStock }}</strong>
              </div>
              <div class="recommended">
                推荐: <strong class="recommended-quantity">{{ row.recommendedQuantity }}</strong>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="location" label="库位" width="100">
          <template #default="{ row }">
            <el-tag size="small" type="primary">
              {{ row.location }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="效期" width="120">
          <template #default="{ row }">
            <div class="expiry-info" :class="{
              'expiry-near': isNearExpiry(row.expiryDate),
              'expiry-urgent': isUrgentExpiry(row.expiryDate)
            }">
              {{ formatDate(row.expiryDate) }}
              <el-icon 
                v-if="isNearExpiry(row.expiryDate)"
                color="#e6a23c"
                size="12"
              >
                <Warning />
              </el-icon>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="priorityScore" label="推荐度" width="100" align="center">
          <template #default="{ row }">
            <el-progress 
              :percentage="row.priorityScore"
              :stroke-width="10"
              :show-text="false"
            />
            <span class="score-text">{{ row.priorityScore }}分</span>
          </template>
        </el-table-column>
        
        <el-table-column label="推荐理由">
          <template #default="{ row }">
            <div class="reasons">
              <el-tag 
                v-for="(reason, index) in row.reason"
                :key="index"
                size="mini"
                type="info"
                effect="plain"
                class="reason-tag"
              >
                {{ reason }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="100" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="selectBatch(row)"
            >
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 推荐说明 -->
    <div class="explanation-section">
      <el-collapse v-model="activeExplanation">
        <el-collapse-item title="推荐说明" name="explanation">
          <div class="explanation-content">
            <p><strong>先进先出(FIFO)</strong>: 优先出库生产日期早的批次，减少库存积压</p>
            <p><strong>先过期先出(FEFO)</strong>: 优先出库效期近的批次，减少过期损失</p>
            <p><strong>最近库位</strong>: 优先出库距离操作台近的批次，提高作业效率</p>
            <p><strong>手动选择</strong>: 不进行自动推荐，由操作员自主选择</p>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button 
          type="primary" 
          :loading="applying"
          @click="applyRecommendations"
        >
          应用推荐
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled, Warning } from '@element-plus/icons-vue'

const props = defineProps()
const emit = defineEmits()

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const selectedStrategy = ref('FEFO')
const loading = ref(false)
const applying = ref(false)
const activeExplanation = ref(['explanation'])

// 模拟推荐数据
const recommendations = ref([
  {
    batchId: 'B001',
    batchNo: 'BATCH-202312-001',
    materialId: 'MAT001',
    materialName: '不锈钢螺丝',
    recommendedQuantity: 250,
    currentStock: 300,
    location: 'A-01-02',
    expiryDate: '2026-11-15',
    productionDate: '2023-11-15',
    supplierName: '上海五金',
    priorityScore: 95,
    reason: ['先过期先出', '库位最近']
  },
  {
    batchId: 'B002',
    batchNo: 'BATCH-202311-015',
    materialId: 'MAT001',
    materialName: '不锈钢螺丝',
    recommendedQuantity: 180,
    currentStock: 200,
    location: 'A-02-01',
    expiryDate: '2026-10-20',
    productionDate: '2023-10-20',
    supplierName: '浙江紧固件',
    priorityScore: 88,
    reason: ['先进先出', '库存充足']
  },
  {
    batchId: 'B003',
    batchNo: 'BATCH-202312-003',
    materialId: 'MAT001',
    materialName: '不锈钢螺丝',
    recommendedQuantity: 70,
    currentStock: 100,
    location: 'B-01-03',
    expiryDate: '2027-01-10',
    productionDate: '2023-12-01',
    supplierName: '江苏五金',
    priorityScore: 75,
    reason: ['新批次', '库存较少']
  }
])

// 计算属性
const strategyDescription = computed(() => {
  const descriptions = {
    'FIFO': '优先出库生产日期早的批次，减少库存积压',
    'FEFO': '优先出库效期近的批次，减少过期损失',
    'NEAREST': '优先出库距离操作台近的批次，提高作业效率',
    'MANUAL': '不进行自动推荐，由操作员自主选择'
  }
  return descriptions[selectedStrategy.value] || ''
})

const canApplyAll = computed(() => {
  if (!props.detail) return false
  const remainingNeed = props.detail.plannedQuantity - props.detail.actualQuantity
  const totalRecommended = recommendations.value.reduce(
    (sum, r) => sum + r.recommendedQuantity, 0
  )
  return remainingNeed >= totalRecommended
})

// 监听策略变化
watch(selectedStrategy, (newStrategy) => {
  if (newStrategy && newStrategy !== 'MANUAL') {
    loading.value = true
    // 模拟API调用
    setTimeout(() => {
      // 根据策略重新排序
      if (newStrategy === 'FEFO') {
        recommendations.value.sort((a, b) => {
          const dateA = new Date(a.expiryDate).getTime()
          const dateB = new Date(b.expiryDate).getTime()
          return dateA - dateB
        })
      } else if (newStrategy === 'FIFO') {
        recommendations.value.sort((a, b) => {
          const dateA = new Date(a.productionDate).getTime()
          const dateB = new Date(b.productionDate).getTime()
          return dateA - dateB
        })
      }
      loading.value = false
    }, 500)
  }
})

// 方法
const getRankTagType = (index) => {
  const types = ['danger', 'warning', 'primary']
  return types[index] || 'info'
}

const isNearExpiry = (expiryDate) => {
  const expiry = new Date(expiryDate)
  const now = new Date()
  const diffDays = Math.ceil((expiry.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
  return diffDays <= 90 && diffDays > 0
}

const isUrgentExpiry = (expiryDate) => {
  const expiry = new Date(expiryDate)
  const now = new Date()
  const diffDays = Math.ceil((expiry.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
  return diffDays <= 30 && diffDays > 0
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

const selectBatch = (batch) => {
  emit('select-batch', batch)
  visible.value = false
}

const applyAllRecommendations = async () => {
  if (!props.detail) return
  
  applying.value = true
  
  try {
    // 模拟批量应用推荐
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('已应用所有推荐批次')
    
    // 触发批次选择事件（选择第一个）
    if (recommendations.value.length > 0) {
      emit('select-batch', recommendations.value[0])
    }
    
    visible.value = false
  } catch (error) {
    ElMessage.error('应用失败')
  } finally {
    applying.value = false
  }
}

const applyRecommendations = () => {
  if (recommendations.value.length > 0) {
    selectBatch(recommendations.value[0])
  }
}
</script>

<style scoped>
.strategy-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.strategy-description {
  margin-top: 10px;
  padding: 8px 12px;
  background: #f0f9ff;
  border-radius: 4px;
  font-size: 13px;
  color: #409eff;
  display: flex;
  align-items: center;
  gap: 8px;
}

.recommendation-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.section-header h4 {
  margin: 0;
  color: #303133;
  font-weight: 600;
}

.batch-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.batch-no {
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 13px;
}

.stock-info {
  line-height: 1.4;
}

.current-stock {
  color: #606266;
  font-size: 12px;
}

.recommended {
  color: #409eff;
  font-size: 12px;
}

.recommended-quantity {
  color: #f56c6c;
  font-weight: 600;
}

.expiry-info {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
}

.expiry-info.expiry-near {
  color: #e6a23c;
  font-weight: 500;
}

.expiry-info.expiry-urgent {
  color: #f56c6c;
  font-weight: 600;
}

.rank-text {
  color: #909399;
  font-size: 12px;
}

.score-text {
  font-size: 11px;
  color: #606266;
  margin-top: 2px;
  display: inline-block;
}

.reasons {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.reason-tag {
  margin: 2px 0;
}

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

.explanation-content {
  padding: 10px;
  background: #f8fafc;
  border-radius: 4px;
  font-size: 13px;
  line-height: 1.6;
}

.explanation-content p {
  margin: 5px 0;
}

:deep(.el-collapse-item__header) {
  font-weight: 500;
  color: #303133;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>