<template>
  <el-dialog
    title="从计划生成工单"
    v-model="visible"
    width="800px"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" v-loading="formLoading">
      <el-alert
        title="提示"
        type="info"
        :closable="false"
        class="mb-20px"
      >
        <template #default>
          <div>计划名称：{{ planInfo.planName }}</div>
          <div>计划周期：{{ planInfo.planPeriod }}</div>
          <div>总计划数量：{{ planInfo.totalPlanQuantity }}</div>
        </template>
      </el-alert>

      <el-form-item label="选择产品" prop="itemIds">
        <el-table
          :data="planItems"
          @selection-change="handleSelectionChange"
          border
          max-height="300"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column label="产品名称" prop="productName" min-width="150" />
          <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">{{ 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">{{ row.inProgressQuantity || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="完成率" prop="completionRate" width="120" align="center">
            <template #default="{ row }">
              <el-progress
                :percentage="row.completionRate || 0"
                :format="() => `${row.completionRate || 0}%`"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="拆分策略" prop="splitStrategy">
        <el-radio-group v-model="form.splitStrategy">
          <el-radio label="single">单个工单（不拆分）</el-radio>
          <el-radio label="weekly">按周拆分</el-radio>
          <el-radio label="daily">按天拆分</el-radio>
        </el-radio-group>
        <div class="text-sm text-gray-500 mt-5px">
          <div v-if="form.splitStrategy === 'single'">将整个计划明细生成为一个工单</div>
          <div v-if="form.splitStrategy === 'weekly'">按周拆分，每周生成一个工单</div>
          <div v-if="form.splitStrategy === 'daily'">按天拆分，每天生成一个工单</div>
        </div>
      </el-form-item>

      <el-form-item label="自动审核" prop="autoApprove">
        <el-switch v-model="form.autoApprove" />
        <span class="text-sm text-gray-500 ml-10px">
          开启后，生成的工单将自动审核通过
        </span>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm">
        生成工单
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { generateWorkOrders, getProductionPlan } from '@/api/mes/production/plan'

const emits = defineEmits(['success'])

const visible = ref(false)
const loading = ref(false)
const formLoading = ref(false)
const formRef = ref()

const planInfo = ref<any>({})
const planItems = ref<any[]>([])
const selectedItems = ref<any[]>([])

const form = reactive<any>({
  planId: undefined,
  itemIds: [],
  splitStrategy: 'daily',
  batchSize: undefined,
  autoApprove: false
})

const rules = {
  itemIds: [{ required: true, message: '请选择要生成工单的产品', trigger: 'change' }],
  splitStrategy: [{ required: true, message: '请选择拆分策略', trigger: 'change' }]
}

const open = async (plan: any) => {
  visible.value = true
  formLoading.value = true

  try {
    // 重置表单
    Object.assign(form, {
      planId: plan.id,
      itemIds: [],
      splitStrategy: 'daily',
      batchSize: undefined,
      autoApprove: false
    })

    // 获取计划详情
    const res = await getProductionPlan(plan.id)
    planInfo.value = res
    planItems.value = res.items || []
  } catch (error) {
    console.error('加载计划详情失败:', error)
    ElMessage.error('加载数据失败，请重试')
    visible.value = false
  } finally {
    formLoading.value = false
  }
}

const handleSelectionChange = (selection: any[]) => {
  selectedItems.value = selection
  form.itemIds = selection.map((item) => item.id)
}

const submitForm = () => {
  if (!form.itemIds || form.itemIds.length === 0) {
    ElMessage.warning('请至少选择一个产品')
    return
  }

  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      const res = await generateWorkOrders(form)
      ElMessage.success(`成功生成 ${res.length} 个工单`)
      visible.value = false
      emits('success')
    } catch (error) {
      console.error('生成工单失败:', error)
    } finally {
      loading.value = false
    }
  })
}

const handleClose = () => {
  formRef.value?.resetFields()
  selectedItems.value = []
}

defineExpose({ open })
</script>
