<template>
  <div class="min-h-screen bg-gray-100 dark:bg-gray-900">
    <!-- 顶部导航 -->
    <div class="bg-white dark:bg-gray-800 shadow">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <div class="flex justify-between items-center">
          <h1 class="text-2xl font-bold text-gray-900 dark:text-white">生产管理</h1>
          <div class="flex space-x-4">
            <button @click="showAddPlanModal = true" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700">
              新增计划
            </button>
            <button @click="exportData" class="bg-green-600 text-white px-4 py-2 rounded-md hover:bg-green-700">
              导出数据
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 生产统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">本月计划</div>
          <div class="mt-2 text-3xl font-bold text-blue-600 dark:text-blue-400">{{ monthlyPlans }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            完成率 <span :class="completionRate >= 80 ? 'text-green-600' : 'text-yellow-600'">{{ completionRate }}%</span>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">进行中</div>
          <div class="mt-2 text-3xl font-bold text-yellow-600 dark:text-yellow-400">{{ inProgress }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            平均进度 <span class="text-blue-600">{{ averageProgress }}%</span>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">已完成</div>
          <div class="mt-2 text-3xl font-bold text-green-600 dark:text-green-400">{{ completed }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            按时完成 <span class="text-green-600">{{ onTimeCompleted }}</span>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">延迟</div>
          <div class="mt-2 text-3xl font-bold text-red-600 dark:text-red-400">{{ delayed }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            平均延迟 <span class="text-red-600">{{ averageDelay }}天</span>
          </div>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">搜索</label>
            <input type="text" v-model="searchText" placeholder="计划名称/产品名称" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">生产线</label>
            <select v-model="filters.line" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">所有生产线</option>
              <option v-for="line in productionLines" :key="line.id" :value="line.id">{{ line.name }}</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">状态</label>
            <select v-model="filters.status" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">所有状态</option>
              <option v-for="status in statusTypes" :key="status.id" :value="status.id">{{ status.name }}</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">时间范围</label>
            <select v-model="filters.timeRange" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">所有时间</option>
              <option v-for="range in timeRanges" :key="range.id" :value="range.id">{{ range.name }}</option>
            </select>
          </div>
        </div>
      </div>

      <!-- 生产计划列表 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h2 class="text-lg font-medium text-gray-900 dark:text-white">生产计划列表</h2>
        </div>
        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
          <thead class="bg-gray-50 dark:bg-gray-700">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">计划信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">生产线</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">进度</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
            <tr v-for="plan in filteredPlans" :key="plan.id">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ plan.name }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ plan.productName }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">
                  {{ formatDate(plan.startDate) }} - {{ formatDate(plan.endDate) }}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900 dark:text-white">{{ plan.lineName }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">负责人: {{ plan.manager }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-700">
                  <div class="bg-blue-600 h-2.5 rounded-full" :style="{ width: plan.progress + '%' }"></div>
                </div>
                <div class="mt-1 text-sm text-gray-500 dark:text-gray-400">{{ plan.progress }}%</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getStatusClass(plan.status)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                  {{ getStatusName(plan.status) }}
                </span>
                <div v-if="plan.delay" class="mt-1 text-sm text-red-600 dark:text-red-400">
                  延迟: {{ plan.delay }}天
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewPlan(plan)" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 mr-3">查看</button>
                <button @click="editPlan(plan)" class="text-yellow-600 hover:text-yellow-900 dark:text-yellow-400 dark:hover:text-yellow-300 mr-3">编辑</button>
                <button @click="deletePlan(plan)" class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 新增计划模态框 -->
    <div v-if="showAddPlanModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
        <h2 class="text-xl font-bold mb-4 text-gray-900 dark:text-white">新增生产计划</h2>
        <form @submit.prevent="addPlan">
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">计划名称</label>
            <input type="text" v-model="newPlan.name" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">产品</label>
            <select v-model="newPlan.productId" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="product in products" :key="product.id" :value="product.id">{{ product.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">生产线</label>
            <select v-model="newPlan.lineId" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="line in productionLines" :key="line.id" :value="line.id">{{ line.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">计划数量</label>
            <input type="number" v-model="newPlan.quantity" required min="1" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">开始日期</label>
            <input type="date" v-model="newPlan.startDate" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">结束日期</label>
            <input type="date" v-model="newPlan.endDate" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">负责人</label>
            <select v-model="newPlan.managerId" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="manager in managers" :key="manager.id" :value="manager.id">{{ manager.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">备注</label>
            <textarea v-model="newPlan.remark" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"></textarea>
          </div>
          <div class="flex justify-end space-x-3">
            <button type="button" @click="showAddPlanModal = false" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
              取消
            </button>
            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
              添加
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 生产计划数据
const productionPlans = ref([
  {
    id: 1,
    name: '2024年Q1生产计划',
    productId: 1,
    productName: '产品A',
    lineId: 1,
    lineName: '生产线A',
    quantity: 1000,
    startDate: '2024-01-01',
    endDate: '2024-03-31',
    managerId: 1,
    manager: '张三',
    progress: 80,
    status: 1,
    delay: 0,
    remark: '第一季度生产计划'
  },
  {
    id: 2,
    name: '2024年Q2生产计划',
    productId: 2,
    productName: '产品B',
    lineId: 2,
    lineName: '生产线B',
    quantity: 2000,
    startDate: '2024-04-01',
    endDate: '2024-06-30',
    managerId: 2,
    manager: '李四',
    progress: 30,
    status: 2,
    delay: 5,
    remark: '第二季度生产计划'
  }
])

// 产品数据
const products = ref([
  { id: 1, name: '产品A', code: 'P001' },
  { id: 2, name: '产品B', code: 'P002' }
])

// 生产线数据
const productionLines = ref([
  { id: 1, name: '生产线A', location: 'A区' },
  { id: 2, name: '生产线B', location: 'B区' }
])

// 负责人数据
const managers = ref([
  { id: 1, name: '张三', position: '生产主管' },
  { id: 2, name: '李四', position: '生产经理' }
])

// 状态类型
const statusTypes = ref([
  { id: 1, name: '进行中' },
  { id: 2, name: '延迟' },
  { id: 3, name: '已完成' },
  { id: 4, name: '已取消' }
])

// 时间范围
const timeRanges = ref([
  { id: 1, name: '本周' },
  { id: 2, name: '本月' },
  { id: 3, name: '本季度' },
  { id: 4, name: '本年' }
])

// 筛选条件
const searchText = ref('')
const filters = ref({
  line: '',
  status: '',
  timeRange: ''
})

// 模态框状态
const showAddPlanModal = ref(false)

// 新计划表单
const newPlan = ref({
  name: '',
  productId: '',
  lineId: '',
  quantity: '',
  startDate: '',
  endDate: '',
  managerId: '',
  remark: ''
})

// 计算属性
const filteredPlans = computed(() => {
  return productionPlans.value.filter(plan => {
    const matchesSearch = !searchText.value || 
      plan.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
      plan.productName.toLowerCase().includes(searchText.value.toLowerCase())
    const matchesLine = !filters.value.line || plan.lineId === filters.value.line
    const matchesStatus = !filters.value.status || plan.status === filters.value.status
    const matchesTimeRange = !filters.value.timeRange || checkTimeRange(plan, filters.value.timeRange)
    return matchesSearch && matchesLine && matchesStatus && matchesTimeRange
  })
})

const monthlyPlans = computed(() => {
  return productionPlans.value.filter(plan => {
    const planDate = new Date(plan.startDate)
    const now = new Date()
    return planDate.getMonth() === now.getMonth() && planDate.getFullYear() === now.getFullYear()
  }).length
})

const completionRate = computed(() => {
  const monthlyPlans = productionPlans.value.filter(plan => {
    const planDate = new Date(plan.startDate)
    const now = new Date()
    return planDate.getMonth() === now.getMonth() && planDate.getFullYear() === now.getFullYear()
  })
  if (monthlyPlans.length === 0) return 0
  const completedPlans = monthlyPlans.filter(plan => plan.status === 3)
  return Math.round((completedPlans.length / monthlyPlans.length) * 100)
})

const inProgress = computed(() => {
  return productionPlans.value.filter(plan => plan.status === 1).length
})

const averageProgress = computed(() => {
  const inProgressPlans = productionPlans.value.filter(plan => plan.status === 1)
  if (inProgressPlans.length === 0) return 0
  const totalProgress = inProgressPlans.reduce((sum, plan) => sum + plan.progress, 0)
  return Math.round(totalProgress / inProgressPlans.length)
})

const completed = computed(() => {
  return productionPlans.value.filter(plan => plan.status === 3).length
})

const onTimeCompleted = computed(() => {
  return productionPlans.value.filter(plan => plan.status === 3 && plan.delay === 0).length
})

const delayed = computed(() => {
  return productionPlans.value.filter(plan => plan.status === 2).length
})

const averageDelay = computed(() => {
  const delayedPlans = productionPlans.value.filter(plan => plan.status === 2)
  if (delayedPlans.length === 0) return 0
  const totalDelay = delayedPlans.reduce((sum, plan) => sum + plan.delay, 0)
  return Math.round(totalDelay / delayedPlans.length)
})

// 检查时间范围
const checkTimeRange = (plan, rangeId) => {
  const now = new Date()
  const planDate = new Date(plan.startDate)
  switch (rangeId) {
    case 1: // 本周
      const weekStart = new Date(now.setDate(now.getDate() - now.getDay()))
      const weekEnd = new Date(now.setDate(now.getDate() - now.getDay() + 6))
      return planDate >= weekStart && planDate <= weekEnd
    case 2: // 本月
      return planDate.getMonth() === now.getMonth() && planDate.getFullYear() === now.getFullYear()
    case 3: // 本季度
      const quarterStart = new Date(now.getFullYear(), Math.floor(now.getMonth() / 3) * 3, 1)
      const quarterEnd = new Date(now.getFullYear(), Math.floor(now.getMonth() / 3) * 3 + 3, 0)
      return planDate >= quarterStart && planDate <= quarterEnd
    case 4: // 本年
      return planDate.getFullYear() === now.getFullYear()
    default:
      return true
  }
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

// 获取状态名称
const getStatusName = (statusId) => {
  const status = statusTypes.value.find(s => s.id === statusId)
  return status ? status.name : '未知状态'
}

// 获取状态样式
const getStatusClass = (statusId) => {
  const classes = {
    1: 'bg-blue-100 text-blue-800 dark:bg-blue-700 dark:text-blue-300',
    2: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-700 dark:text-yellow-300',
    3: 'bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-300',
    4: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
  }
  return classes[statusId] || 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
}

// 导出数据
const exportData = () => {
  // 实现导出数据逻辑
  console.log('导出数据')
}

// 添加计划
const addPlan = () => {
  const product = products.value.find(p => p.id === newPlan.value.productId)
  const line = productionLines.value.find(l => l.id === newPlan.value.lineId)
  const manager = managers.value.find(m => m.id === newPlan.value.managerId)
  const plan = {
    id: productionPlans.value.length + 1,
    name: newPlan.value.name,
    productId: newPlan.value.productId,
    productName: product.name,
    lineId: newPlan.value.lineId,
    lineName: line.name,
    quantity: parseInt(newPlan.value.quantity),
    startDate: newPlan.value.startDate,
    endDate: newPlan.value.endDate,
    managerId: newPlan.value.managerId,
    manager: manager.name,
    progress: 0,
    status: 1,
    delay: 0,
    remark: newPlan.value.remark
  }
  productionPlans.value.push(plan)
  showAddPlanModal.value = false
  resetNewPlan()
}

// 重置新计划表单
const resetNewPlan = () => {
  newPlan.value = {
    name: '',
    productId: '',
    lineId: '',
    quantity: '',
    startDate: '',
    endDate: '',
    managerId: '',
    remark: ''
  }
}

// 查看计划
const viewPlan = (plan) => {
  // 实现查看计划逻辑
  console.log('查看计划:', plan)
}

// 编辑计划
const editPlan = (plan) => {
  // 实现编辑计划逻辑
  console.log('编辑计划:', plan)
}

// 删除计划
const deletePlan = (plan) => {
  if (confirm(`确定要删除生产计划"${plan.name}"吗？`)) {
    const index = productionPlans.value.findIndex(p => p.id === plan.id)
    if (index !== -1) {
      productionPlans.value.splice(index, 1)
    }
  }
}
</script> 