<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" :show-overflow-tooltip="true" highlight-current-row>
      <el-table-column :label="t('ProductionPlan.Task.saleDetailTableIndexColumn')" type="index" width="80" />
      <el-table-column :label="t('ProductionPlan.Task.saleDetailTableProductColumn')" 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('ProductionPlan.Task.saleDetailProductPlaceholder')"
            >
              <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('ProductionPlan.Task.saleDetailTableUnitColumn')" min-width="100">
        <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="t('ProductionPlan.Task.saleDetailTableNumberColumn')" min-width="180">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.number`" :rules="formRules.number" class="mb-0px!">
            <el-input-number v-model="row.number" :min="0" class="!w-1/1" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.Task.saleDetailTablePackageSizeColumn')" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.packageSize`" :rules="formRules.packageSize" class="mb-0px!">
            <el-input-number v-model="row.packageSize" :min="0"  class="!w-1/1" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.Task.saleDetailTablePackageNumberColumn')" 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" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.Task.saleDetailTableProjectNameColumn')" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.projectName`" :rules="formRules.projectName" class="mb-0px!">
            <el-input v-model="row.projectName" placeholder="" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.Task.saleDetailTableTechRequirementsColumn')" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.techRequirements`" :rules="formRules.techRequirements" class="mb-0px!">
            <el-input v-model="row.techRequirements" placeholder="" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.Task.saleDetailTableRemarkColumn')" 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 :label="t('ProductionPlan.Task.saleDetailTableFinishDateColumn')" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.finishDate`" :rules="formRules.finishDate" class="mb-0px!">
            <el-date-picker
              v-model="row.finishDate"
              type="date"
              value-format="x"
              placeholder=""
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.Task.saleDetailTableBoxingDateColumn')" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.boxingDate`" :rules="formRules.boxingDate" class="mb-0px!">
            <el-date-picker
              v-model="row.boxingDate"
              type="date"
              value-format="x"
              placeholder=""
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.Task.saleDetailTableArriveDateColumn')" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.arriveDate`" :rules="formRules.arriveDate" class="mb-0px!">
            <el-date-picker
              v-model="row.arriveDate"
              type="date"
              value-format="x"
              placeholder=""
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.Task.saleDetailTableBarCodeColumn')" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.barCode`" :rules="formRules.barCode" class="mb-0px!">
            <el-input v-model="row.barCode" placeholder="" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column align="center" fixed="right" :label="t('ProductionPlan.Task.saleDetailTableOperateColumn')" 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('ProductionPlan.Task.saleDetailAddRowButtonText') }}</el-button>
    <el-button @click="openOrderItemsList" round>{{ t('ProductionPlan.Task.saleDetailAddFromOrderButtonText') }}</el-button>
  </el-row>
  <el-row>
    <SaleOrderIndex ref="orderItemsRef" @success="dealOrder"/>
  </el-row>
</template>
<script setup lang="ts">
import { TaskApi } from '@/api/mes/task'
import { ProductUnitApi, ProductUnitVO } from '@/api/erp/product/unit'
import {ProductApi, ProductVO} from "@/api/erp/product/product";
import SaleOrderIndex from './SaleOrderIndex.vue'
import {SaleOrderApi, SaleOrderItemsVO, SaleOrderVO} from "@/api/mes/saleorder";

const unitList = ref<ProductUnitVO[]>([]) // 产品单位列表
const productList = ref<ProductVO[]>([]) // 产品列表

const { t } = useI18n()

const props = defineProps<{
  taskId?: undefined // task ID（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  productId: [{ required: true, message: t('ProductionPlan.Task.validatorRowProductRequired'), trigger: 'blur' }],
  unitId: [{ required: true, message: t('ProductionPlan.Task.validatorRowUnitRequired'), trigger: 'blur' }],
  taskId: [{ required: true, message: t('ProductionPlan.Task.validatorRowTaskRequired'), trigger: 'blur' }],
  number: [{ required: true, message: t('ProductionPlan.Task.validatorRowNumberRequired'), trigger: 'blur' }],

})
const formRef = ref() // 表单 Ref

/** 添加/修改操作 */
const orderItemsRef = ref()
const openOrderItemsList = () => {
  orderItemsRef.value.open()
}

const selectionList = ref<SaleOrderItemsVO[]>([])
/** 表单值 */
const dealOrder = async (e)  => {
  selectionList.value = e
  if(selectionList.value.length > 0){
    selectionList.value.forEach((item, index) => {
      console.log(`Item ${index}:`, item);
      // 在这里处理每个item
      const row = {
        id: undefined,
        productId: item.productId,
        unitId: item.productUnitId,
        taskId: props.taskId,
        number: item.count,
        packageSize: undefined,
        projectName: undefined,
        techRequirements: undefined,
        remark: item.remark,
        isEnable: true,
        packageNumber: undefined,
        finishDate: undefined,
        boxingDate: undefined,
        arriveDate: undefined,
        barCode: undefined,
        attachment: undefined,
      }
      formData.value.push(row)
    });
  }
}
/** 初始化 */
onMounted(async () => {
  // 产品单位
  unitList.value = await ProductUnitApi.getProductUnitSimpleList()
  productList.value = await ProductApi.getMesProductSimpleList()
  // 默认添加一个
  if (formData.value.length === 0) {
    // 1. 重置表单
    formData.value = []
    handleAdd()
  }
})

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

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    productId: undefined,
    unitId: undefined,
    taskId: undefined,
    number: undefined,
    packageSize: undefined,
    projectName: undefined,
    techRequirements: undefined,
    remark: undefined,
    isEnable: undefined,
    packageNumber: undefined,
    finishDate: undefined,
    boxingDate: undefined,
    arriveDate: undefined,
    barCode: undefined,
    attachment: undefined,
  }
  row.taskId = props.taskId
  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>
