<template>
  <!-- 移动端使用抽屉 -->
  <el-drawer
    v-if="isMobile"
    v-model="visible"
    title="从计划生成工单"
    direction="btt"
    size="90%"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <div v-loading="formLoading">
      <el-alert
        title="提示"
        type="info"
        :closable="false"
        class="mb-15px"
      >
        <template #default>
          <div class="mobile-alert-text">
            <div>计划名称：{{ planInfo.planName }}</div>
            <div>计划周期：{{ planInfo.planPeriod }}</div>
            <div>总计划数量：{{ planInfo.totalPlanQuantity }}</div>
          </div>
        </template>
      </el-alert>

      <div class="mobile-form-section">
        <div class="mobile-form-section__title">选择产品</div>
        <div class="product-list">
          <div
            v-for="item in planItems"
            :key="item.id"
            class="product-card"
            :class="{ 'product-card--selected': form.itemIds.includes(item.id) }"
            @click="toggleProduct(item)"
          >
            <div class="product-card__header">
              <el-checkbox :model-value="form.itemIds.includes(item.id)" @click.stop="toggleProduct(item)" />
              <span class="product-card__name">{{ item.productName }}</span>
            </div>
            <div class="product-card__stats">
              <div class="stat-item">
                <span class="stat-label">计划</span>
                <span class="stat-value">{{ item.planQuantity }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">已完成</span>
                <span class="stat-value success">{{ item.completedQuantity || 0 }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">进行中</span>
                <span class="stat-value warning">{{ item.inProgressQuantity || 0 }}</span>
              </div>
            </div>
            <div class="product-card__progress">
              <el-progress
                :percentage="item.completionRate || 0"
                :format="() => `${item.completionRate || 0}%`"
              />
            </div>
          </div>
        </div>
      </div>

      <div class="mobile-form-section">
        <div class="mobile-form-section__title">拆分策略</div>
        <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="strategy-desc">
          <div v-if="form.splitStrategy === 'single'">将整个计划明细生成为一个工单</div>
          <div v-if="form.splitStrategy === 'weekly'">按周拆分，每周生成一个工单</div>
          <div v-if="form.splitStrategy === 'daily'">按天拆分，每天生成一个工单</div>
        </div>
      </div>

      <div class="mobile-form-section">
        <div class="mobile-form-section__title">其他设置</div>
        <div class="switch-item">
          <span class="switch-item__label">自动审核</span>
          <el-switch v-model="form.autoApprove" />
        </div>
        <div class="switch-item__desc">开启后，生成的工单将自动审核通过</div>
      </div>
    </div>

    <template #footer>
      <div class="mobile-drawer-footer">
        <el-button @click="visible = false" style="flex:1">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submitForm" style="flex:1">
          生成工单
        </el-button>
      </div>
    </template>
  </el-drawer>

  <!-- PC端使用对话框 -->
  <el-dialog
    v-else
    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, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { generateWorkOrders, getProductionPlan } from '@/api/mes/production/plan'
import { useWindowSize } from '@vueuse/core'

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

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 toggleProduct = (item: any) => {
  const index = form.itemIds.indexOf(item.id)
  if (index > -1) {
    form.itemIds.splice(index, 1)
    const selectedIndex = selectedItems.value.findIndex(i => i.id === item.id)
    if (selectedIndex > -1) {
      selectedItems.value.splice(selectedIndex, 1)
    }
  } else {
    form.itemIds.push(item.id)
    selectedItems.value.push(item)
  }
}

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>

<style lang="scss" scoped>
.mobile-alert-text {
  font-size: 13px;
  line-height: 1.6;
  
  div {
    margin-bottom: 4px;
  }
}

.mobile-form-section {
  margin-bottom: 20px;
  
  &__title {
    font-size: 15px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
  }
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.product-card {
  padding: 12px;
  border: 2px solid #dcdfe6;
  border-radius: 8px;
  background: #fff;
  transition: all 0.3s;
  cursor: pointer;
  
  &__header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 10px;
  }
  
  &__name {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    flex: 1;
  }
  
  &__stats {
    display: flex;
    justify-content: space-around;
    margin-bottom: 10px;
    padding: 8px 0;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
  }
  
  &__progress {
    margin-top: 8px;
  }
  
  &--selected {
    border-color: #409eff;
    background: #ecf5ff;
  }
  
  &:active {
    transform: scale(0.98);
  }
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  
  .stat-label {
    font-size: 11px;
    color: #909399;
  }
  
  .stat-value {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    
    &.success {
      color: #67c23a;
    }
    
    &.warning {
      color: #e6a23c;
    }
  }
}

.strategy-desc {
  margin-top: 8px;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 6px;
  font-size: 12px;
  color: #606266;
  line-height: 1.5;
}

.switch-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  
  &__label {
    font-size: 14px;
    color: #303133;
  }
  
  &__desc {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
    line-height: 1.5;
  }
}

.mobile-drawer-footer {
  display: flex;
  gap: 12px;
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
}
</style>
