<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="t('FactoryModeling.ProductBOM.detailTableIndexColumn')" type="index" width="100" />
      <el-table-column :label="t('FactoryModeling.ProductBOM.detailTableMaterialColumn')" 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="t('FactoryModeling.ProductBOM.detailMaterialPlaceholder')"
            >
              <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="t('FactoryModeling.ProductBOM.detailTableUnitColumn')" 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="t('FactoryModeling.ProductBOM.detailUnitPlaceholder')" 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="t('FactoryModeling.ProductBOM.detailTableUsageNumberColumn')" 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="t('FactoryModeling.ProductBOM.detailUsageNumberPlaceholder')"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :label="t('FactoryModeling.ProductBOM.detailTableLossRateColumn')" 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="t('FactoryModeling.ProductBOM.detailLossRatePlaceholder')"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :label="t('FactoryModeling.ProductBOM.detailTableRemarkColumn')" 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="t('FactoryModeling.ProductBOM.detailRemarkPlaceholder')" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" :label="t('FactoryModeling.ProductBOM.detailTableOperateColumn')" width="60">
        <template #default="{ $index }">
          <el-button type="danger" @click="handleDelete($index)" link>
            <Icon icon="ep:delete" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ {{ t('FactoryModeling.ProductBOM.detailAddButtonText') }}</el-button>
  </el-row>
</template>
<script setup lang="ts">

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

const { t } = useI18n()

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: t('FactoryModeling.ProductBOM.validatorDetailMaterialRequired'), trigger: 'blur' }],
  bomId: [{ required: true, message: t('FactoryModeling.ProductBOM.validatorDetailBomRequired'), trigger: 'blur' }],
  usageNumber: [{ required: true, message: t('FactoryModeling.ProductBOM.validatorDetailUsageNumberRequired'), 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>
