<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" />
      <el-table-column label="原料" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" :rules="formRules.productId" class="mb-0px!">
            <el-select
              v-model="row.productId"
              clearable
              filterable
              placeholder="请选择原料"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.unitId`" :rules="formRules.unitId" class="mb-0px!">
            <el-select v-model="row.unitId" clearable filterable placeholder="请选择单位" class="w-1/1">
              <el-option
                v-for="unit in unitList"
                :key="unit.id"
                :label="unit.name"
                :value="unit.id"
              />
            </el-select>
          </el-form-item>
          
        </template>
      </el-table-column>
       <el-table-column label="用量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.usageNumber`" :rules="formRules.usageNumber" class="mb-0px!">
            <el-input-number v-model="row.usageNumber" :min="0" :precision="2" class="!w-1/1" placeholder="请输入用量"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="损耗率%" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.yieldRate`" :rules="formRules.yieldRate" class="mb-0px!">
            <el-input-number
              v-model="row.yieldRate"
              :min="0"
              :precision="2"
              class="!w-1/1"
              placeholder="请输入损耗率"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" :rules="formRules.remark" class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <el-button type="danger" @click="handleDelete($index)" link>
          <Icon icon="ep:delete" />
        </el-button>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加产品BOM明细</el-button>
  </el-row>
</template>
<script setup lang="ts">

import { BomApi } from '@/api/mes/bom'
import { ProductUnitApi, ProductUnitVO } from '@/api/erp/product/unit'
import {ProductApi, ProductVO} from "@/api/erp/product/product";

const unitList = ref<ProductUnitVO[]>([]) // 产品单位列表
const productList = ref<ProductVO[]>([]) // 产品列表
const props = defineProps<{
  bomId: undefined // BOM ID（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  productId: [{ required: true, message: '原料不能为空', trigger: 'blur' }],
  bomId: [{ required: true, message: 'BOM 不能为空', trigger: 'blur' }],
  usageNumber: [{ required: true, message: '用量不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 初始化 */
onMounted(async () => {
  // 产品单位
  unitList.value = await ProductUnitApi.getProductUnitSimpleList()
  productList.value = await ProductApi.getItemSimpleList()
  // 默认添加一个
  if (formData.value.length === 0) {
    handleAdd()
  }
})

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.bomId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      formData.value = await BomApi.getBomDetailListByBomId(val)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
  
)

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    productId: undefined,
    unitId: undefined,
    bomId: undefined,
    usageNumber: undefined,
    yieldRate: undefined,
    remark: undefined,
    isEnable: undefined
  }
  row.bomId = props.bomId
  row.yieldRate = 0
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

defineExpose({ validate, getData })

</script>
