<template>
  <el-dialog
    title="生产计划分析"
    v-model="visible"
    width="1000px"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <div v-loading="loading">
      <!-- 基本信息卡片 -->
      <el-card shadow="never" class="mb-15px">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-bold">计划概览</span>
            <el-tag type="primary">{{ analysisData?.planCode }}</el-tag>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="4">
            <div class="stat-item">
              <div class="stat-label">计划名称</div>
              <div class="stat-value text-blue-600">{{ analysisData?.planName }}</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="stat-item">
              <div class="stat-label">计划总数量</div>
              <div class="stat-value text-gray-600">{{ analysisData?.totalPlanQuantity }} 件</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="stat-item">
              <div class="stat-label">已完成数量</div>
              <div class="stat-value text-green-600">{{ analysisData?.totalCompletedQuantity }} 件</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="stat-item">
              <div class="stat-label">剩余数量</div>
              <div class="stat-value text-orange-600">{{ analysisData?.totalRemainingQuantity }} 件</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="stat-item">
              <div class="stat-label">预计生产周期</div>
              <div class="stat-value text-blue-500">{{ analysisData?.estimatedProductionHours }} 小时</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="stat-item">
              <div class="stat-label">预计交货日期</div>
              <div class="stat-value text-purple-600">{{ analysisData?.estimatedDeliveryDate }}</div>
            </div>
          </el-col>
        </el-row>
        <el-alert type="info" :closable="false" class="mt-10px">
          <template #title>
            <span>※ 以下物料需求分析基于<strong>剩余未完成数量</strong>计算</span>
          </template>
        </el-alert>
      </el-card>

      <!-- 风险提示 -->
      <el-alert
        v-if="analysisData?.riskWarnings && analysisData.riskWarnings.length > 0"
        title="风险提示"
        type="warning"
        :closable="false"
        class="mb-15px"
      >
        <template #default>
          <div v-for="(warning, index) in analysisData.riskWarnings" :key="index" class="mb-5px">
            ⚠ {{ warning }}
          </div>
        </template>
      </el-alert>

      <!-- 采购建议 -->
      <el-card shadow="never" class="mb-15px">
        <template #header>
          <span class="font-bold">采购建议</span>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="建议采购提前天数">
            <el-tag type="warning">{{ analysisData?.suggestedPurchaseLeadDays }} 天</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="建议采购日期">
            <el-tag type="danger">{{ analysisData?.suggestedPurchaseDate }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 辅料需求汇总 -->
      <el-card shadow="never" class="mb-15px">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-bold">辅料需求汇总</span>
            <el-tag type="info">共 {{ analysisData?.materialRequirements?.length || 0 }} 种物料</el-tag>
          </div>
        </template>
        <el-table :data="analysisData?.materialRequirements" border max-height="300">
          <el-table-column label="物料编码" prop="materialCode" width="100" align="center" />
          <el-table-column label="物料名称" prop="materialName" min-width="120" align="center" />
          <el-table-column label="类型" prop="materialType" width="90" align="center" />
          <el-table-column label="需求数量" width="100" align="center">
            <template #default="{ row }">
              {{ row.requiredQuantity }} {{ row.unit }}
            </template>
          </el-table-column>
          <el-table-column label="当前库存" width="100" align="center">
            <template #default="{ row }">
              {{ row.currentStock }} {{ row.unit }}
            </template>
          </el-table-column>
          <el-table-column label="库存缺口" width="100" align="center">
            <template #default="{ row }">
              <span :class="getGapClass(row.stockGap)">
                {{ row.stockGap > 0 ? '+' : '' }}{{ row.stockGap }} {{ row.unit }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="库存状态" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="getStockStatusType(row.stockStatus)" size="small">
                {{ getStockStatusText(row.stockStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="建议采购" width="100" align="center">
            <template #default="{ row }">
              <span class="text-orange-600 font-bold" v-if="row.suggestedPurchaseQuantity > 0">
                {{ row.suggestedPurchaseQuantity }} {{ row.unit }}
              </span>
              <span v-else class="text-gray-400">-</span>
            </template>
          </el-table-column>
          <el-table-column label="采购提前期" width="90" align="center">
            <template #default="{ row }">
              {{ row.purchaseLeadTime }} 天
            </template>
          </el-table-column>
          <el-table-column label="预计金额" width="100" align="center">
            <template #default="{ row }">
              <span v-if="row.estimatedPurchaseAmount > 0" class="text-red-600">
                ¥{{ row.estimatedPurchaseAmount }}
              </span>
              <span v-else class="text-gray-400">-</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="mt-10px text-right" v-if="totalPurchaseAmount > 0">
          <span class="text-gray-500">预计采购总金额：</span>
          <span class="text-red-600 font-bold text-lg">¥{{ totalPurchaseAmount.toFixed(2) }}</span>
        </div>
      </el-card>

      <!-- 产品明细分析 -->
      <el-card shadow="never" class="mb-15px">
        <template #header>
          <span class="font-bold">产品明细分析</span>
        </template>
        <el-collapse v-model="activeProducts">
          <el-collapse-item
            v-for="(product, index) in analysisData?.productAnalysisList"
            :key="index"
            :name="index"
          >
            <template #title>
              <div class="flex items-center gap-10px">
                <span class="font-bold">{{ product.productName }}</span>
                <el-tag size="small">{{ product.planQuantity }} {{ product.unit || '件' }}</el-tag>
                <el-tag size="small" type="success">已完成 {{ product.completedQuantity }}</el-tag>
                <el-tag size="small" type="warning">剩余 {{ product.remainingQuantity }}</el-tag>
                <el-tag size="small" type="info">{{ product.estimatedHours }} 小时</el-tag>
              </div>
            </template>
            <div class="pl-20px">
              <el-descriptions :column="3" border size="small" class="mb-10px">
                <el-descriptions-item label="产品编码">{{ product.productCode }}</el-descriptions-item>
                <el-descriptions-item label="工序路线">{{ product.routeName || '-' }}</el-descriptions-item>
                <el-descriptions-item label="预计周期">{{ product.estimatedHours }} 小时</el-descriptions-item>
                <el-descriptions-item label="计划开始">{{ product.plannedStartDate || '-' }}</el-descriptions-item>
                <el-descriptions-item label="计划结束">{{ product.plannedEndDate || '-' }}</el-descriptions-item>
              </el-descriptions>
              <div class="text-sm text-gray-500 mb-5px">该产品辅料需求：</div>
              <el-table :data="product.materialRequirements" border size="small">
                <el-table-column label="物料名称" prop="materialName" min-width="100" />
                <el-table-column label="需求数量" width="100" align="center">
                  <template #default="{ row }">
                    {{ row.requiredQuantity }} {{ row.unit }}
                  </template>
                </el-table-column>
                <el-table-column label="库存状态" width="80" align="center">
                  <template #default="{ row }">
                    <el-tag :type="getStockStatusType(row.stockStatus)" size="small">
                      {{ getStockStatusText(row.stockStatus) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-card>

      <!-- 描述性分析文本 -->
      <el-card shadow="never">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-bold">分析报告</span>
            <el-button type="primary" size="small" @click="copyAnalysisText">
              <Icon icon="ep:document-copy" class="mr-5px" /> 复制报告
            </el-button>
          </div>
        </template>
        <pre class="analysis-text">{{ analysisData?.analysisDescription }}</pre>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" @click="handleExport">
        <Icon icon="ep:download" class="mr-5px" /> 导出报告
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Icon } from '@/components/Icon'
import { analyzeProductionPlan, type ProductionPlanAnalysisVO } from '@/api/mes/production/plan'

const visible = ref(false)
const loading = ref(false)
const analysisData = ref<ProductionPlanAnalysisVO | null>(null)
const activeProducts = ref<number[]>([0])

const totalPurchaseAmount = computed(() => {
  if (!analysisData.value?.materialRequirements) return 0
  return analysisData.value.materialRequirements.reduce((sum, item) => {
    return sum + (item.estimatedPurchaseAmount || 0)
  }, 0)
})

const open = async (planId: number) => {
  visible.value = true
  loading.value = true
  
  try {
    analysisData.value = await analyzeProductionPlan(planId)
  } catch (error) {
    console.error('获取分析数据失败:', error)
    ElMessage.error('获取分析数据失败')
    visible.value = false
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  analysisData.value = null
  activeProducts.value = [0]
}

const getStockStatusType = (status: string) => {
  const map: Record<string, string> = {
    sufficient: 'success',
    warning: 'warning',
    shortage: 'danger'
  }
  return map[status] || 'info'
}

const getStockStatusText = (status: string) => {
  const map: Record<string, string> = {
    sufficient: '充足',
    warning: '预警',
    shortage: '短缺'
  }
  return map[status] || '未知'
}

const getGapClass = (gap: number) => {
  if (gap <= 0) return 'text-green-600'
  return 'text-red-600'
}

const copyAnalysisText = async () => {
  if (!analysisData.value?.analysisDescription) return
  
  try {
    await navigator.clipboard.writeText(analysisData.value.analysisDescription)
    ElMessage.success('分析报告已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败，请手动复制')
  }
}

const handleExport = () => {
  if (!analysisData.value?.analysisDescription) return
  
  const blob = new Blob([analysisData.value.analysisDescription], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `生产计划分析报告_${analysisData.value.planCode}_${new Date().toISOString().slice(0, 10)}.txt`
  link.click()
  URL.revokeObjectURL(url)
  ElMessage.success('报告导出成功')
}

defineExpose({ open })
</script>

<style scoped lang="scss">
.stat-item {
  text-align: center;
  padding: 10px;
  
  .stat-label {
    font-size: 12px;
    color: #909399;
    margin-bottom: 5px;
  }
  
  .stat-value {
    font-size: 16px;
    font-weight: bold;
  }
}

.analysis-text {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.8;
  color: #303133;
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin: 0;
  max-height: 400px;
  overflow-y: auto;
}

:deep(.el-collapse-item__header) {
  font-size: 14px;
}

:deep(.el-collapse-item__content) {
  padding-bottom: 15px;
}
</style>
