<template>
  <!-- 移动端使用抽屉 -->
  <el-drawer
    v-if="isMobile"
    v-model="visible"
    :title="formType === 'create' ? '新增生产计划' : '编辑生产计划'"
    direction="rtl"
    size="100%"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-position="top" v-loading="formLoading">
      <div class="mobile-form-section">
        <div class="mobile-form-section__title">基本信息</div>
        <el-form-item label="计划编号" prop="planCode">
          <el-input v-model="form.planCode" placeholder="请输入计划编号" />
        </el-form-item>
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="form.planName" placeholder="请输入计划名称" />
        </el-form-item>
        <el-form-item label="计划类型" prop="planType">
          <el-select v-model="form.planType" placeholder="请选择计划类型" style="width:100%">
            <el-option label="年度计划" :value="1" />
            <el-option label="月度计划" :value="2" />
            <el-option label="周度计划" :value="3" />
            <el-option label="日计划" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划周期" prop="planPeriod">
          <el-input v-model="form.planPeriod" placeholder="如:2024-01" />
        </el-form-item>
        <el-form-item label="父计划" prop="parentPlanId" v-if="filteredParentPlans.length > 0">
          <el-select 
            v-model="form.parentPlanId" 
            placeholder="请选择父计划" 
            clearable
            filterable
            style="width:100%"
          >
            <el-option
              v-for="item in filteredParentPlans"
              :key="item.id"
              :label="`${item.planName} (${item.planCode})`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </div>

      <div class="mobile-form-section">
        <div class="mobile-form-section__title">计划时间</div>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="form.startDate"
            type="date"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="form.endDate"
            type="date"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </div>

      <div class="mobile-form-section">
        <div class="mobile-form-section__title">
          计划明细
          <el-button type="primary" size="small" @click="handleAddItem" style="float:right">
            <Icon icon="ep:plus" class="mr-5px" /> 添加产品
          </el-button>
        </div>
        
        <div class="product-items">
          <div v-for="(item, index) in form.items" :key="index" class="product-item-card">
            <div class="product-item-card__header">
              <span class="product-item-card__index">{{ index + 1 }}</span>
              <el-button link type="danger" @click="handleDeleteItem(index)">
                <Icon icon="ep:delete" />
              </el-button>
            </div>
            <el-form-item label="产品">
              <el-select
                v-model="item.productId"
                placeholder="请选择产品"
                filterable
                @change="handleProductChange(item, index)"
                style="width:100%"
              >
                <el-option
                  v-for="product in productOptions"
                  :key="product.id"
                  :label="product.name"
                  :value="product.id"
                >
                  <span>{{ product.name }}</span>
                  <span class="text-gray-400 ml-10px">({{ product.barCode }})</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="计划数量">
              <el-input-number
                v-model="item.planQuantity"
                :min="1"
                :precision="0"
                controls-position="right"
                style="width:100%"
              />
            </el-form-item>
            <el-form-item label="工序路线">
              <el-select
                v-model="item.routeId"
                placeholder="请选择工序路线"
                filterable
                @change="handleRouteChange(item)"
                style="width:100%"
              >
                <el-option
                  v-for="route in routeOptions"
                  :key="route.id"
                  :label="route.name"
                  :value="route.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="优先级">
              <el-input-number
                v-model="item.priority"
                :min="1"
                :max="10"
                controls-position="right"
                style="width:100%"
              />
            </el-form-item>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="计划开始">
                  <el-date-picker
                    v-model="item.plannedStartDate"
                    type="date"
                    placeholder="开始日期"
                    value-format="YYYY-MM-DD"
                    style="width:100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计划结束">
                  <el-date-picker
                    v-model="item.plannedEndDate"
                    type="date"
                    placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    style="width:100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-if="form.items.length === 0" class="empty-items">
            <el-empty description="暂无产品，请添加" :image-size="80" />
          </div>
        </div>
      </div>
    </el-form>
    
    <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="formType === 'create' ? '新增生产计划' : '编辑生产计划'"
    v-model="visible"
    width="1200px"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" v-loading="formLoading">
      <el-row :gutter="isMobile ? 0 : 20">
        <el-col :span="isMobile ? 24 : 12">
          <el-form-item label="计划编号" prop="planCode">
            <el-input v-model="form.planCode" placeholder="请输入计划编号" />
          </el-form-item>
        </el-col>
        <el-col :span="isMobile ? 24 : 12">
          <el-form-item label="计划名称" prop="planName">
            <el-input v-model="form.planName" placeholder="请输入计划名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="isMobile ? 0 : 20">
        <el-col :span="isMobile ? 24 : 8">
          <el-form-item label="计划类型" prop="planType">
            <el-select v-model="form.planType" placeholder="请选择计划类型" class="!w-full">
              <el-option label="年度计划" :value="1" />
              <el-option label="月度计划" :value="2" />
              <el-option label="周度计划" :value="3" />
              <el-option label="日计划" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="isMobile ? 24 : 8">
          <el-form-item label="计划周期" prop="planPeriod">
            <el-input v-model="form.planPeriod" placeholder="如:2024-01" />
          </el-form-item>
        </el-col>
        <el-col :span="isMobile ? 24 : 8">
          <el-form-item label="父计划" prop="parentPlanId">
            <el-select 
              v-model="form.parentPlanId" 
              placeholder="请选择父计划" 
              clearable
              filterable
              class="!w-full"
            >
              <el-option
                v-for="item in filteredParentPlans"
                :key="item.id"
                :label="`${item.planName} (${item.planCode})`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="isMobile ? 0 : 20">
        <el-col :span="isMobile ? 24 : 12">
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
              v-model="form.startDate"
              type="date"
              placeholder="选择开始日期"
              value-format="YYYY-MM-DD"
              class="!w-full"
            />
          </el-form-item>
        </el-col>
        <el-col :span="isMobile ? 24 : 12">
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              v-model="form.endDate"
              type="date"
              placeholder="选择结束日期"
              value-format="YYYY-MM-DD"
              class="!w-full"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>

      <!-- 计划明细 -->
      <el-divider content-position="left">计划明细</el-divider>
      <el-button type="primary" @click="handleAddItem" class="mb-10px">
        <Icon icon="ep:plus" class="mr-5px" /> 添加产品
      </el-button>
      <el-table :data="form.items" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="产品" prop="productName" min-width="150" align="center">
          <template #default="{ row, $index }">
            <el-select
              v-model="row.productId"
              placeholder="请选择产品"
              filterable
              @change="handleProductChange(row, $index)"
              class="!w-full"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                <span>{{ item.name }}</span>
                <span class="text-gray-400 ml-10px">({{ item.barCode }})</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="计划数量" prop="planQuantity" width="120" align="center">
          <template #default="{ row }">
            <el-input-number
              v-model="row.planQuantity"
              :min="1"
              :precision="0"
              controls-position="right"
              class="!w-full"
            />
          </template>
        </el-table-column>
        <el-table-column label="工序路线" prop="routeName" min-width="150" align="center">
          <template #default="{ row }">
            <el-select
              v-model="row.routeId"
              placeholder="请选择工序路线"
              filterable
              @change="handleRouteChange(row)"
              class="!w-full"
            >
              <el-option
                v-for="item in routeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="优先级" prop="priority" width="100" align="center">
          <template #default="{ row }">
            <el-input-number
              v-model="row.priority"
              :min="1"
              :max="10"
              controls-position="right"
              class="!w-full"
            />
          </template>
        </el-table-column>
        <el-table-column label="计划开始日期" prop="plannedStartDate" width="150" align="center">
          <template #default="{ row }">
            <el-date-picker
              v-model="row.plannedStartDate"
              type="date"
              placeholder="开始日期"
              value-format="YYYY-MM-DD"
              class="!w-full"
            />
          </template>
        </el-table-column>
        <el-table-column label="计划结束日期" prop="plannedEndDate" width="150" align="center">
          <template #default="{ row }">
            <el-date-picker
              v-model="row.plannedEndDate"
              type="date"
              placeholder="结束日期"
              value-format="YYYY-MM-DD"
              class="!w-full"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center" fixed="right">
          <template #default="{ $index }">
            <el-button link type="danger" @click="handleDeleteItem($index)">
              <Icon icon="ep:delete" />
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </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, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Icon } from '@/components/Icon'
import {
  createProductionPlan,
  updateProductionPlan,
  getProductionPlan,
  getProductionPlanPage
} from '@/api/mes/production/plan'
import { ProductApi } from '@/api/erp/product/product'
import { YVHgetProcessRouteList } from '@/api/mes/production/process-route'
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 formType = ref<'create' | 'update'>('create')
const formRef = ref()

const productOptions = ref<any[]>([])
const routeOptions = ref<any[]>([])
const parentPlanOptions = ref<any[]>([])

const form = reactive<any>({
  id: undefined,
  planCode: '',
  planName: '',
  planType: 2,
  planPeriod: '',
  startDate: '',
  endDate: '',
  parentPlanId: undefined,
  remark: '',
  items: []
})

// 根据计划类型过滤可选的父计划
// 层级关系: 年度计划(1) > 月度计划(2) > 周度计划(3) > 日计划(4)
const filteredParentPlans = computed(() => {
  if (!form.planType) return []
  
  // 年度计划没有父计划
  if (form.planType === 1) {
    return []
  }
  
  // 月度计划只能选择年度计划作为父计划
  if (form.planType === 2) {
    return parentPlanOptions.value.filter(plan => plan.planType === 1)
  }
  
  // 周度计划只能选择月度计划作为父计划
  if (form.planType === 3) {
    return parentPlanOptions.value.filter(plan => plan.planType === 2)
  }
  
  // 日计划只能选择周度计划作为父计划
  if (form.planType === 4) {
    return parentPlanOptions.value.filter(plan => plan.planType === 3)
  }
  
  return []
})

const rules = {
  planCode: [{ required: true, message: '请输入计划编号', trigger: 'blur' }],
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  planType: [{ required: true, message: '请选择计划类型', trigger: 'change' }],
  planPeriod: [{ required: true, message: '请输入计划周期', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
}

// 监听计划类型变化，自动清除不符合条件的父计划
watch(() => form.planType, () => {
  // 如果当前选择的父计划不在过滤后的列表中，则清空
  if (form.parentPlanId && !filteredParentPlans.value.find(p => p.id === form.parentPlanId)) {
    form.parentPlanId = undefined
  }
})

const open = async (type: 'create' | 'update', id?: number) => {
  formType.value = type
  visible.value = true
  formLoading.value = true

  try {
    // 重置表单
    Object.assign(form, {
      id: undefined,
      planCode: type === 'create' ? generatePlanCode() : '',
      planName: '',
      planType: 2,
      planPeriod: getCurrentPeriod(),
      startDate: '',
      endDate: '',
      parentPlanId: undefined,
      remark: '',
      items: []
    })

    // 并行获取产品列表、工序路线列表和父计划列表
    const [products, routes, plans] = await Promise.all([
      ProductApi.getProductSimpleList().catch(() => []),
      YVHgetProcessRouteList().catch(() => []),
      getProductionPlanPage({ pageNo: 1, pageSize: 100 }).then(res => res.list || []).catch(() => [])
    ])

    productOptions.value = products ? products.filter((p) => p.categoryName?.includes('成品')) : []
    routeOptions.value = routes || []
    // 过滤掉当前编辑的计划,避免循环引用
    parentPlanOptions.value = plans.filter(p => p.id !== id)

    // 如果是编辑模式，获取计划详情
    if (type === 'update' && id) {
      const res = await getProductionPlan(id)
      Object.assign(form, res)
    }
  } catch (error) {
    console.error('初始化表单失败:', error)
    ElMessage.error('加载数据失败，请重试')
    visible.value = false
  } finally {
    formLoading.value = false
  }
}

const handleAddItem = () => {
  form.items.push({
    productId: undefined,
    productCode: '',
    productName: '',
    planQuantity: 1,
    routeId: undefined,
    routeName: '',
    priority: 5,
    plannedStartDate: form.startDate,
    plannedEndDate: form.endDate,
    remark: ''
  })
}

const handleDeleteItem = (index: number) => {
  form.items.splice(index, 1)
}

const handleProductChange = (row: any, index: number) => {
  const product = productOptions.value.find((item) => item.id === row.productId)
  if (product) {
    row.productCode = product.barCode
    row.productName = product.name

    // 自动匹配工序路线
    const route = routeOptions.value.find((r) => r.name === product.name || r.name.includes(product.name))
    if (route) {
      row.routeId = route.id
      row.routeName = route.name
    }
  }
}

const handleRouteChange = (row: any) => {
  const route = routeOptions.value.find((item) => item.id === row.routeId)
  if (route) {
    row.routeName = route.name
  }
}

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

  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      if (formType.value === 'create') {
        await createProductionPlan(form)
        ElMessage.success('新增成功')
      } else {
        await updateProductionPlan(form)
        ElMessage.success('修改成功')
      }
      visible.value = false
      emits('success')
    } catch (error) {
      console.error('保存计划失败:', error)
    } finally {
      loading.value = false
    }
  })
}

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

const generatePlanCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  return `PLAN${year}${month}001`
}

const getCurrentPeriod = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  return `${year}-${month}`
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.mobile-form-section {
  margin-bottom: 24px;
  
  &__title {
    font-size: 15px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 16px;
    padding-bottom: 10px;
    border-bottom: 2px solid #409eff;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.product-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.product-item-card {
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  
  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #dcdfe6;
  }
  
  &__index {
    font-size: 14px;
    font-weight: 600;
    color: #409eff;
    background: #ecf5ff;
    padding: 4px 12px;
    border-radius: 12px;
  }
}

.empty-items {
  padding: 40px 20px;
  text-align: center;
}

.mobile-drawer-footer {
  display: flex;
  gap: 12px;
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
  position: sticky;
  bottom: 0;
  background: #fff;
  z-index: 10;
}

:deep(.el-drawer__body) {
  padding-bottom: 70px;
}
</style>
