<template>
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="1000px"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产品" prop="productId">
            <el-select
              v-model="formData.productId"
              placeholder="请选择产品"
              filterable
              class="!w-100%"
              :disabled="isViewMode"
              @change="handleProductChange"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="`${item.name} (${item.barCode || '-'})`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="BOM名称" prop="bomName">
            <el-input v-model="formData.bomName" placeholder="请输入BOM名称" :disabled="isViewMode" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="BOM编码" prop="bomCode">
            <el-input v-model="formData.bomCode" placeholder="自动生成" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版本号" prop="version">
            <el-input v-model="formData.version" placeholder="如：V1.0" :disabled="isViewMode" />
          </el-form-item>
        </el-col>

      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="默认版本" prop="isDefault">
            <el-radio-group v-model="formData.isDefault" :disabled="isViewMode">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status" :disabled="isViewMode">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" :disabled="isViewMode" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- BOM明细 -->
      <el-divider content-position="left">BOM明细</el-divider>
      <el-form-item v-if="!isViewMode">
        <el-button type="primary" @click="addItem">
          <Icon icon="ep:plus" class="mr-5px" /> 添加物料
        </el-button>
      </el-form-item>

      <el-table :data="formData.items" border style="width: 100%">
        <el-table-column label="物料" min-width="200">
          <template #default="{ row, $index }">
            <el-select
              v-if="!isViewMode"
              v-model="row.materialId"
              placeholder="请选择物料"
              filterable
              class="!w-100%"
              @change="(val: number) => handleMaterialChange(val, $index)"
            >
              <el-option
                v-for="item in materialList"
                :key="item.id"
                :label="`${item.name} (${item.barCode || '-'})`"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ row.materialName }} ({{ row.materialCode || '-' }})</span>
          </template>
        </el-table-column>
        <el-table-column label="物料类型" width="120">
          <template #default="{ row }">
            <el-input v-if="!isViewMode" v-model="row.materialType" placeholder="类型" :disabled="true" />
            <span v-else>{{ row.materialType || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单位" width="80">
          <template #default="{ row }">
            <el-input v-if="!isViewMode" v-model="row.unit" placeholder="单位" />
            <span v-else>{{ row.unit || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单位用量" width="120">
          <template #default="{ row }">
            <el-input-number
              v-if="!isViewMode"
              v-model="row.unitQuantity"
              :min="0"
              :precision="4"
              :step="0.1"
              :controls="false"
              class="!w-100%"
            />
            <span v-else>{{ row.unitQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column label="损耗率(%)" width="100">
          <template #default="{ row }">
            <el-input-number
              v-if="!isViewMode"
              v-model="row.lossRate"
              :min="0"
              :max="100"
              :precision="2"
              :controls="false"
              class="!w-100%"
            />
            <span v-else>{{ row.lossRate || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="100">
          <template #default="{ row }">
            <el-input-number
              v-if="!isViewMode"
              v-model="row.unitPrice"
              :min="0"
              :precision="2"
              :controls="false"
              class="!w-100%"
            />
            <span v-else>{{ row.unitPrice ? '¥' + row.unitPrice : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="必需" width="80">
          <template #default="{ row }">
            <el-checkbox v-if="!isViewMode" v-model="row.required" :true-label="1" :false-label="0" />
            <el-tag v-else :type="row.required === 1 ? 'success' : 'info'" size="small">
              {{ row.required === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="!isViewMode" label="操作" width="80" fixed="right">
          <template #default="{ $index }">
            <el-button link type="danger" @click="removeItem($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">{{ isViewMode ? '关闭' : '取消' }}</el-button>
      <el-button v-if="!isViewMode" type="primary" @click="submitForm" :loading="formLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Icon } from '@/components/Icon'
import { createProductBom, updateProductBom, getProductBom, ProductBomItemVO } from '@/api/mes/product/bom'
import { getProductVOListByStatus } from '@/api/erp/product/product'
import { ProductCategoryApi } from '@/api/erp/product/category'

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formRef = ref()

const isViewMode = computed(() => formType.value === 'view')

const productList = ref<any[]>([])
const materialList = ref<any[]>([])
const categoryList = ref<any[]>([])

const formData = reactive({
  id: undefined as number | undefined,
  bomCode: '',
  bomName: '',
  productId: undefined as number | undefined,
  productCode: '',
  productName: '',
  version: 'V1.0',
  isDefault: 1,
  remark: '',
  status: 1,
  items: [] as ProductBomItemVO[]
})

const formRules = {
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
  bomName: [{ required: true, message: '请输入BOM名称', trigger: 'blur' }]
}

const resetForm = () => {
  formData.id = undefined
  formData.bomCode = ''
  formData.bomName = ''
  formData.productId = undefined
  formData.productCode = ''
  formData.productName = ''
  formData.version = 'V1.0'
  formData.isDefault = 1
  formData.remark = ''
  formData.status = 1
  formData.items = []
  formRef.value?.resetFields()
}

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  formType.value = type
  if (type === 'create') {
    dialogTitle.value = '新增产品BOM'
  } else if (type === 'update') {
    dialogTitle.value = '编辑产品BOM'
  } else {
    dialogTitle.value = '查看产品BOM'
  }
  resetForm()

  // 加载产品列表和分类列表
  try {
    const [productData, categoryData] = await Promise.all([
      getProductVOListByStatus(0),
      ProductCategoryApi.getProductCategorySimpleList()
    ])
    productList.value = productData || []
    materialList.value = productData || []
    categoryList.value = categoryData || []
  } catch (error) {
    console.error('加载数据失败:', error)
  }

  if (id) {
    formLoading.value = true
    try {
      const data = await getProductBom(id)
      formData.id = data.id
      formData.bomCode = data.bomCode || ''
      formData.bomName = data.bomName || ''
      formData.productId = data.productId
      formData.productCode = data.productCode || ''
      formData.productName = data.productName || ''
      formData.version = data.version || 'V1.0'
      formData.isDefault = data.isDefault ?? 0
      formData.remark = data.remark || ''
      formData.status = data.status ?? 1
      formData.items = data.items || []
    } finally {
      formLoading.value = false
    }
  }
}

const handleProductChange = (productId: number) => {
  const product = productList.value.find((p) => p.id === productId)
  if (product) {
    formData.productCode = product.barCode || ''
    formData.productName = product.name || ''
    // 自动设置BOM名称
    if (!formData.bomName) {
      formData.bomName = product.name + ' BOM'
    }
  }
}

const handleMaterialChange = (materialId: number, index: number) => {
  const material = materialList.value.find((m) => m.id === materialId)
  if (material && formData.items[index]) {
    formData.items[index].materialCode = material.barCode || ''
    formData.items[index].materialName = material.name || ''
    formData.items[index].unit = material.unitName || ''
    if (material.purchasePrice) {
      formData.items[index].unitPrice = material.purchasePrice
    }
    // 根据分类自动设置物料类型
    if (material.categoryId) {
      const category = categoryList.value.find((c) => c.id === material.categoryId)
      formData.items[index].materialType = category?.name || ''
    }
  }
}

const addItem = () => {
  formData.items.push({
    materialId: undefined as any,
    materialCode: '',
    materialName: '',
    materialType: '',
    unit: '',
    unitQuantity: 1,
    lossRate: 0,
    purchaseLeadTime: 7,
    unitPrice: 0,
    required: 1,
    sort: formData.items.length,
    remark: ''
  })
}

const removeItem = (index: number) => {
  formData.items.splice(index, 1)
}

const submitForm = async () => {
  await formRef.value?.validate()
  // 校验明细
  if (formData.items.length === 0) {
    ElMessage.warning('请至少添加一条BOM明细')
    return
  }
  for (const item of formData.items) {
    if (!item.materialId) {
      ElMessage.warning('请选择物料')
      return
    }
    if (!item.unitQuantity || item.unitQuantity <= 0) {
      ElMessage.warning('单位用量必须大于0')
      return
    }
  }

  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await createProductBom(formData)
      ElMessage.success('新增成功')
    } else {
      await updateProductBom(formData)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const handleClose = () => {
  resetForm()
}

defineExpose({ open })
</script>
