<template>
  <doc-alert title="【MES】生产计划详情" url="https://doc.iocoder.cn/mes/production-plan/" />

  <ContentWrap v-loading="loading">
    <!-- 计划基本信息 -->
    <el-descriptions title="计划基本信息" :column="isMobile ? 1 : 3" border>
      <el-descriptions-item label="计划编号">{{ planInfo.planCode }}</el-descriptions-item>
      <el-descriptions-item label="计划名称">{{ planInfo.planName }}</el-descriptions-item>
      <el-descriptions-item label="计划类型">
        <el-tag :type="getPlanTypeTagType(planInfo.planType)">
          {{ getPlanTypeText(planInfo.planType) }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="计划周期">{{ planInfo.planPeriod }}</el-descriptions-item>
      <el-descriptions-item label="开始日期">{{ planInfo.startDate }}</el-descriptions-item>
      <el-descriptions-item label="结束日期">{{ planInfo.endDate }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="getStatusType(planInfo.status)">
          {{ getStatusText(planInfo.status) }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ planInfo.createTime }}</el-descriptions-item>
      <el-descriptions-item label="备注" :span="isMobile ? 1 : 3">{{ planInfo.remark || '-' }}</el-descriptions-item>
    </el-descriptions>

    <!-- 完成情况统计 -->
    <el-card class="mt-20px" shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="font-bold">完成情况统计</span>
          <el-button
            type="primary"
            size="small"
            @click="handleRefresh"
          >
            <Icon icon="ep:refresh" class="mr-5px" /> 刷新进度
          </el-button>
        </div>
      </template>
      <el-row :gutter="isMobile ? 10 : 20">
        <el-col :span="isMobile ? 12 : 6">
          <div class="stat-card">
            <div class="stat-label">总计划数量</div>
            <div class="stat-value text-blue-600">{{ planInfo.totalPlanQuantity || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="isMobile ? 12 : 6">
          <div class="stat-card">
            <div class="stat-label">已完成数量</div>
            <div class="stat-value text-green-600">{{ planInfo.totalCompletedQuantity || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="isMobile ? 12 : 6" :class="isMobile ? 'mt-10px' : ''">
          <div class="stat-card">
            <div class="stat-label">进行中数量</div>
            <div class="stat-value text-orange-600">{{ planInfo.totalInProgressQuantity || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="isMobile ? 12 : 6" :class="isMobile ? 'mt-10px' : ''">
          <div class="stat-card">
            <div class="stat-label">整体完成率</div>
            <div class="stat-value" :style="{ color: getProgressColor(planInfo.overallCompletionRate) }">
              {{ planInfo.overallCompletionRate || 0 }}%
            </div>
          </div>
        </el-col>
      </el-row>
      <el-progress
        :percentage="planInfo.overallCompletionRate || 0"
        :color="getProgressColor(planInfo.overallCompletionRate)"
        class="mt-20px"
      />
    </el-card>

    <!-- 计划明细 -->
    <el-card class="mt-20px" shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="font-bold">计划明细</span>
          <el-button type="primary" size="small" @click="handleQueryOrders">
            <Icon icon="ep:search" class="mr-5px" /> 查询工单
          </el-button>
        </div>
      </template>
      <el-table :data="planInfo.items" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="产品信息" min-width="150" align="center">
          <template #default="{ row }">
            <div class="font-bold">{{ row.productName }}</div>
            <div class="text-sm text-gray-500">{{ row.productCode }}</div>
          </template>
        </el-table-column>
        <el-table-column label="工序路线" prop="routeName" min-width="120" align="center" />
        <el-table-column label="计划数量" prop="planQuantity" width="100" align="center" />
        <el-table-column label="已完成" prop="completedQuantity" width="100" align="center">
          <template #default="{ row }">
            <span class="text-green-600 font-bold">{{ row.completedQuantity || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="进行中" prop="inProgressQuantity" width="100" align="center">
          <template #default="{ row }">
            <span class="text-orange-600 font-bold">{{ row.inProgressQuantity || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="完成率" prop="completionRate" width="150" align="center">
          <template #default="{ row }">
            <el-progress
              :percentage="row.completionRate || 0"
              :color="getProgressColor(row.completionRate)"
            />
          </template>
        </el-table-column>
        <el-table-column label="优先级" prop="priority" width="80" align="center" />
        <el-table-column label="计划时间" min-width="180" align="center">
          <template #default="{ row }">
            <div>开始：{{ row.plannedStartDate || '-' }}</div>
            <div class="mt-5px">结束：{{ row.plannedEndDate || '-' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="实际时间" min-width="180" align="center">
          <template #default="{ row }">
            <div>开始：{{ row.actualStartDate || '-' }}</div>
            <div class="mt-5px">结束：{{ row.actualEndDate || '-' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" min-width="150" show-overflow-tooltip />
      </el-table>
    </el-card>

    <!-- 工单列表 -->
    <el-card class="mt-20px" shadow="never" v-if="showOrders">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="font-bold">工单列表</span>
          <el-tag type="info">共 {{ orderList.length }} 条工单</el-tag>
        </div>
      </template>
      <el-table :data="orderList" border v-loading="orderLoading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="工单编号" prop="code" min-width="150" align="center" />
        <el-table-column label="工单名称" prop="name" min-width="150" align="center" />
        <el-table-column label="产品信息" min-width="150" align="center">
          <template #default="{ row }">
            <div class="font-bold">{{ row.productName }}</div>
            <div class="text-sm text-gray-500">{{ row.productCode }}</div>
          </template>
        </el-table-column>
        <el-table-column label="工艺路线" prop="routeName" min-width="120" align="center" />
        <el-table-column label="计划数量" prop="planQuantity" width="100" align="center" />
        <el-table-column label="已生产" prop="producedQuantity" width="100" align="center">
          <template #default="{ row }">
            <span class="text-blue-600 font-bold">{{ row.producedQuantity || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合格数" prop="qualifiedQuantity" width="100" align="center">
          <template #default="{ row }">
            <span class="text-green-600 font-bold">{{ row.qualifiedQuantity || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="不合格" prop="unqualifiedQuantity" width="100" align="center">
          <template #default="{ row }">
            <span class="text-red-600 font-bold">{{ row.unqualifiedQuantity || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="优先级" prop="priority" width="80" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getOrderStatusType(row.status)">
              {{ getOrderStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="计划时间" min-width="180" align="center">
          <template #default="{ row }">
            <div>开始：{{ row.planStartTime || '-' }}</div>
            <div class="mt-5px">结束：{{ row.planEndTime || '-' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="实际时间" min-width="180" align="center">
          <template #default="{ row }">
            <div>开始：{{ row.actualStartTime || '-' }}</div>
            <div class="mt-5px">结束：{{ row.actualEndTime || '-' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" min-width="150" show-overflow-tooltip />
      </el-table>
    </el-card>

    <!-- 操作按钮 -->
    <div class="mt-20px text-center">
      <el-button @click="goBack">返回</el-button>
      <el-button
        type="primary"
        @click="handleEdit"
        v-if="planInfo.status === 0"
        v-hasPermi="['mes:production-plan:update']"
      >
        编辑计划
      </el-button>
      <el-button
        type="success"
        @click="handlePublish"
        v-if="planInfo.status === 0"
        v-hasPermi="['mes:production-plan:publish']"
      >
        发布计划
      </el-button>
<!--      <el-button-->
<!--        type="warning"-->
<!--        @click="handleGenerateOrders"-->
<!--        v-if="planInfo.status >= 1 && planInfo.status <= 2"-->
<!--        v-hasPermi="['mes:production-plan:generate-orders']"-->
<!--      >-->
<!--        生成工单-->
<!--      </el-button>-->
    </div>
  </ContentWrap>

  <!-- 生成工单弹窗 -->
  <GenerateOrderDialog ref="generateOrderRef" @success="getDetail" />
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Icon } from '@/components/Icon'
import GenerateOrderDialog from '../list/GenerateOrderDialog.vue'
import {
  getProductionPlan,
  publishProductionPlan,
  updatePlanProgress
} from '@/api/mes/production/plan'
import { YVHgetWorkOrderPage } from '@/api/mes/production/workorder'
import { useWindowSize } from '@vueuse/core'

const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)

defineOptions({ name: 'MesProductionPlanDetail' })

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const planInfo = ref<any>({})
const generateOrderRef = ref()
const showOrders = ref(false)
const orderLoading = ref(false)
const orderList = ref<any[]>([])

const planId = ref<number>(Number(route.query.id))

const getDetail = async () => {
  loading.value = true
  try {
    const res = await getProductionPlan(planId.value)
    planInfo.value = res
  } catch (error) {
    console.error('获取计划详情失败:', error)
    ElMessage.error('获取计划详情失败')
  } finally {
    loading.value = false
  }
}

const handleRefresh = async () => {
  try {
    await updatePlanProgress(planId.value)
    ElMessage.success('进度更新成功')
    getDetail()
  } catch (error) {
    console.error('更新进度失败:', error)
  }
}

const handleEdit = () => {
  router.push({
    path: '/mes/production/plan/list',
    query: { editId: planId.value }
  })
}

const handlePublish = async () => {
  try {
    await ElMessageBox.confirm('确定要发布该计划吗？发布后将不能修改。', '提示', {
      type: 'warning'
    })
    await publishProductionPlan(planId.value)
    ElMessage.success('发布成功')
    getDetail()
  } catch {}
}

const handleGenerateOrders = () => {
  generateOrderRef.value.open(planInfo.value)
}

const goBack = () => {
  router.back()
}

const handleQueryOrders = async () => {
  orderLoading.value = true
  showOrders.value = true
  try {
    const res = await YVHgetWorkOrderPage({
      sourceType: 2,
      sourceId: planId.value,
      pageNo: 1,
      pageSize: 100
    })
    orderList.value = res.list || []
    ElMessage.success(`查询成功，共找到 ${orderList.value.length} 条工单`)
  } catch (error) {
    console.error('查询工单失败:', error)
    ElMessage.error('查询工单失败')
  } finally {
    orderLoading.value = false
  }
}

const getOrderStatusText = (status: number) => {
  const map: Record<number, string> = {
    0: '草稿',
    1: '待审核',
    2: '已审核',
    3: '生产中',
    4: '已完成',
    5: '已关闭',
    6: '已取消',
    7: '已入库'
  }
  return map[status] || '未知'
}

const getOrderStatusType = (status: number) => {
  const map: Record<number, string> = {
    0: 'info',
    1: 'warning',
    2: 'primary',
    3: 'warning',
    4: 'success',
    5: 'danger',
    6: 'info'
  }
  return map[status] || ''
}

const getPlanTypeText = (type: number) => {
  const map: Record<number, string> = {
    1: '年度',
    2: '月度',
    3: '周度'
  }
  return map[type] || '未知'
}

const getPlanTypeTagType = (type: number) => {
  const map: Record<number, string> = {
    1: 'danger',
    2: 'warning',
    3: 'info'
  }
  return map[type] || ''
}

const getStatusText = (status: number) => {
  const map: Record<number, string> = {
    0: '草稿',
    1: '已发布',
    2: '执行中',
    3: '已完成',
    4: '已关闭'
  }
  return map[status] || '未知'
}

const getStatusType = (status: number) => {
  const map: Record<number, string> = {
    0: 'info',
    1: 'primary',
    2: 'warning',
    3: 'success',
    4: 'danger'
  }
  return map[status] || ''
}

const getProgressColor = (percentage: number) => {
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
}

onMounted(() => {
  if (planId.value) {
    getDetail()
  }
})
</script>

<style scoped lang="scss">
.stat-card {
  text-align: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;

  .stat-label {
    font-size: 14px;
    color: #606266;
    margin-bottom: 10px;
  }

  .stat-value {
    font-size: 32px;
    font-weight: bold;
  }
}

@media screen and (max-width: 768px) {
  .stat-card {
    padding: 12px;

    .stat-label {
      font-size: 12px;
      margin-bottom: 6px;
    }

    .stat-value {
      font-size: 20px;
    }
  }
}
</style>
