<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="70" />
      <el-table-column label="产品" min-width="220">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" :rules="formRules.planId" class="mb-0px!">
            <el-select v-model="row.planId"  clearable filterable placeholder="请选择" >
              <el-option
                v-for="item in productList"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              />
            </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}.qualityNumber`" :rules="formRules.qualityNumber" class="mb-0px!">
            <el-input-number v-model="row.qualityNumber" :min="0"  class="!w-1/1" placeholder="" @change="numberChange(row)"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="废品数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.wasteNumber`" :rules="formRules.wasteNumber" class="mb-0px!">
            <el-input-number v-model="row.wasteNumber" :min="0" class="!w-1/1" placeholder="" @change="numberChange(row)"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="打包数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.packageNumber`" :rules="formRules.packageNumber" class="mb-0px!">
            <el-input-number v-model="row.packageNumber" :min="0"   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}.totalNumber`" :rules="formRules.totalNumber" class="mb-0px!">
            <el-input disabled v-model="row.totalNumber" placeholder="" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="成品率%" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.qualityRate`" :rules="formRules.qualityRate" class="mb-0px!">
            <el-input-number disabled v-model="row.qualityRate" :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">
        <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>+ 添加生产报工明细</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { ProduceReportApi } from '@/api/mes/producereport'
import {ProductApi, ProductVO} from "@/api/erp/product/product";
import {PlanApi} from "@/api/mes/plan";

const props = defineProps<{
  reportId: undefined // 报工单id（主表的关联字段）
  orgType?: undefined //工序类型
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  qualityNumber: [{ required: true, message: '成品数量不能为空', trigger: 'blur' }],
  wasteNumber: [{ required: true, message: '废品数量不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const productList = ref<ProductVO[]>([]) // 产品列表
/** 初始化 */
onMounted(async () => {
  // 产品单位
  productList.value = await PlanApi.getStartPlanProduct(props.orgType)

  // 默认添加一个
  if (formData.value.length === 0) {
    handleAdd()
    if(productList.value.length ==1)
      formData.value[0].productId = productList.value[0].id
  }
})

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.reportId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      formData.value = await ProduceReportApi.getProduceReportDetailListByReportId(val)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)
/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.orgType,
  async (val) => {
    console.log(val)
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      productList.value = await PlanApi.getStartPlanProduct(props.orgType)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)
/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    reportId: undefined,
    planId: undefined,
    productId: undefined,
    userId: undefined,
    orgId: undefined,
    qualityRate: undefined,
    wasteReason: undefined,
    totalTime: undefined,
    packageNumber: undefined,
    remark: undefined,
    isEnable: undefined,
    qualityNumber: 0,
    wasteNumber: 0,
    totalNumber: undefined,
    reportDate: undefined,
    reportTime: undefined,
    reportStatus: undefined,
    reportType: undefined,
    groupType: undefined,
    orgType: undefined
  }
  row.reportId = props.reportId
  formData.value.push(row)
}

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

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

/** 表单值 */
const getData = () => {
  return formData.value
}
const numberChange = async (row) =>{
  row.totalNumber = row.qualityNumber+row.wasteNumber
  row.qualityRate = row.qualityNumber/row.totalNumber * 100
}
defineExpose({ validate, getData })
</script>
