<template>
  <!-- 移动端使用抽屉 -->
  <el-drawer
    v-if="isMobile"
    v-model="dialogVisible"
    title="生成月度计划"
    direction="btt"
    size="85%"
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-position="top">
      <el-alert
        title="提示"
        type="info"
        :closable="false"
        class="mb-15px"
      >
        <template #default>
          <div class="mobile-alert-text">从年度计划生成月度计划，系统将根据所选月份和分配策略自动生成对应的月度计划。</div>
        </template>
      </el-alert>

      <div class="mobile-form-section">
        <div class="mobile-form-section__title">计划信息</div>
        <el-form-item label="年度计划" prop="annualPlanId">
          <div class="plan-info">
            <div class="plan-info__code">{{ annualPlan?.planCode }}</div>
            <div class="plan-info__name">{{ annualPlan?.planName }}</div>
          </div>
        </el-form-item>

        <el-form-item label="计划周期" prop="planPeriod">
          <el-tag type="danger">{{ annualPlan?.planPeriod }}</el-tag>
        </el-form-item>
      </div>

      <div class="mobile-form-section">
        <div class="mobile-form-section__title">选择月份</div>
        <el-form-item prop="months" required>
          <div class="month-grid">
            <div
              v-for="month in availableMonths"
              :key="month"
              class="month-item"
              :class="{
                'month-item--selected': formData.months.includes(month),
                'month-item--disabled': existingMonths.includes(month)
              }"
              @click="toggleMonth(month)"
            >
              <div class="month-item__label">{{ month }}月</div>
              <div v-if="existingMonths.includes(month)" class="month-item__tag">已存在</div>
            </div>
          </div>
        </el-form-item>
      </div>

      <div class="mobile-form-section">
        <div class="mobile-form-section__title">分配策略</div>
        <el-form-item prop="splitStrategy">
          <el-radio-group v-model="formData.splitStrategy">
            <el-radio label="average">平均分配</el-radio>
            <el-radio label="proportional">按比例分配</el-radio>
          </el-radio-group>
          <div class="strategy-desc">
            <div v-if="formData.splitStrategy === 'average'">
              将年度计划数量平均分配到各月度计划
            </div>
            <div v-else>
              根据各月工作日比例分配计划数量
            </div>
          </div>
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <div class="mobile-drawer-footer">
        <el-button @click="dialogVisible = false" style="flex:1">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading" style="flex:1">
          确定生成
        </el-button>
      </div>
    </template>
  </el-drawer>

  <!-- PC端使用对话框 -->
  <Dialog v-else v-model="dialogVisible" title="生成月度计划" width="600px">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-alert
        title="提示"
        type="info"
        :closable="false"
        class="mb-15px"
      >
        <template #default>
          <div>从年度计划生成月度计划，系统将根据所选月份和分配策略自动生成对应的月度计划。</div>
        </template>
      </el-alert>

      <el-form-item label="年度计划" prop="annualPlanId">
        <div class="w-full">
          <div class="font-bold">{{ annualPlan?.planCode }}</div>
          <div class="text-sm text-gray-500">{{ annualPlan?.planName }}</div>
        </div>
      </el-form-item>

      <el-form-item label="计划周期" prop="planPeriod">
        <el-tag type="danger">{{ annualPlan?.planPeriod }}</el-tag>
      </el-form-item>

      <el-form-item label="选择月份" prop="months" required>
        <el-checkbox-group v-model="formData.months">
          <el-checkbox
            v-for="month in availableMonths"
            :key="month"
            :label="month"
            :disabled="existingMonths.includes(month)"
          >
            {{ month }}月
            <el-tag v-if="existingMonths.includes(month)" type="info" size="small" class="ml-5px">
              已存在
            </el-tag>
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="分配策略" prop="splitStrategy">
        <el-radio-group v-model="formData.splitStrategy">
          <el-radio label="average">平均分配</el-radio>
          <el-radio label="proportional">按比例分配</el-radio>
        </el-radio-group>
        <div class="text-sm text-gray-500 mt-5px">
          <div v-if="formData.splitStrategy === 'average'">
            将年度计划数量平均分配到各月度计划
          </div>
          <div v-else>
            根据各月工作日比例分配计划数量
          </div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
        确定生成
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { generateMonthlyPlans, type GenerateMonthlyPlanReqVO } from '@/api/mes/production/plan'
import { useWindowSize } from '@vueuse/core'

defineOptions({ name: 'GenerateMonthlyPlanDialog' })

const emit = defineEmits(['success'])

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

const dialogVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref()
const annualPlan = ref<any>(null)
const existingMonths = ref<number[]>([])

const formData = reactive<GenerateMonthlyPlanReqVO>({
  annualPlanId: 0,
  months: [],
  splitStrategy: 'average'
})

const availableMonths = computed(() => {
  return Array.from({ length: 12 }, (_, i) => i + 1)
})

const rules = {
  months: [{ required: true, message: '请选择要生成的月份', trigger: 'change' }],
  splitStrategy: [{ required: true, message: '请选择分配策略', trigger: 'change' }]
}

const toggleMonth = (month: number) => {
  if (existingMonths.value.includes(month)) return
  
  const index = formData.months.indexOf(month)
  if (index > -1) {
    formData.months.splice(index, 1)
  } else {
    formData.months.push(month)
  }
}

const open = (plan: any) => {
  annualPlan.value = plan
  formData.annualPlanId = plan.id
  formData.months = []
  formData.splitStrategy = 'average'
  
  if (plan.children && plan.children.length > 0) {
    existingMonths.value = plan.children
      .filter((child: any) => child.planType === 2)
      .map((child: any) => {
        const match = child.planPeriod?.match(/-(\d{2})$/)
        return match ? parseInt(match[1]) : 0
      })
      .filter((month: number) => month > 0)
  } else {
    existingMonths.value = []
  }
  
  dialogVisible.value = true
}

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    
    if (formData.months.length === 0) {
      ElMessage.warning('请至少选择一个月份')
      return
    }

    submitLoading.value = true
    await generateMonthlyPlans(formData)
    ElMessage.success('月度计划生成成功')
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('生成月度计划失败:', error)
  } finally {
    submitLoading.value = false
  }
}

defineExpose({ open })
</script>

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

.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;
  }
}

.plan-info {
  &__code {
    font-size: 15px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 4px;
  }
  
  &__name {
    font-size: 13px;
    color: #909399;
  }
}

.month-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.month-item {
  padding: 12px;
  border: 2px solid #dcdfe6;
  border-radius: 8px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  
  &__label {
    font-size: 14px;
    font-weight: 500;
    color: #606266;
  }
  
  &__tag {
    font-size: 11px;
    color: #909399;
    margin-top: 4px;
  }
  
  &--selected {
    border-color: #409eff;
    background: #ecf5ff;
    
    .month-item__label {
      color: #409eff;
      font-weight: 600;
    }
  }
  
  &--disabled {
    background: #f5f7fa;
    border-color: #e4e7ed;
    cursor: not-allowed;
    opacity: 0.6;
  }
  
  &:active:not(&--disabled) {
    transform: scale(0.95);
  }
}

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

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