<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}.itemId`" :rules="formRules.itemId" class="mb-0px!">
             <el-select
               v-model="row.itemId"
               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="80">
        <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="请选择原料"
            >
              <el-option
                v-for="item in unitList"
                :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}.weight`" :rules="formRules.weight" class="mb-0px!">
            <el-input-number v-model="row.weight" :min="0" :precision="2" class="!w-1/1" placeholder=""
            />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link type="danger">
            <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>+ 添加投料明细</el-button>
  </el-row> -->
</template>
<script setup lang="ts">
import { FeedingRecordApi } from '@/api/mes/feedingrecord'
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<{
  recordId: undefined // 记录id（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  itemId: [{ required: true, message: '原料不能为空', trigger: 'blur' }],
  unitId: [{ required: true, message: '单位不能为空', trigger: 'blur' }],
  weight: [{ 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.recordId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      formData.value = await FeedingRecordApi.getFeedingRecordDetailListByRecordId(val)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    recordId: undefined,
    itemId: undefined,
    weight: undefined,
    unitId: 3,
    userId: undefined,
    feedingTime: undefined,
  }
  row.recordId = props.recordId
  formData.value.push(row)
}

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

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

defineExpose({ validate, getData })
</script>
