<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="入库单类型" prop="inStockType">
              <el-select v-model="queryParams.inStockType" placeholder="请选择入库单类型" clearable>
                <el-option v-for="dict in wms_in_stock_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="关联单号" prop="inventoryAmount">
              <el-input v-model="queryParams.inventoryAmount" placeholder="请输入关联单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应商" prop="supplier">
              <el-input v-model="queryParams.supplierName" placeholder="请输入供应商" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="入库单状态" prop="inStockBillStatus">-->
            <!--              <el-select v-model="queryParams.inStockBillStatus" placeholder="请选择入库单状态" clearable>-->
            <!--                <el-option v-for="dict in wms_in_stock_bill_status" :key="dict.value" :label="dict.label" :value="dict.value" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="流程状态" prop="flowStatus">-->
            <!--              <el-input v-model="queryParams.flowStatus" placeholder="请输入流程状态" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label="创建时间" style="width: 308px">
              <el-date-picker
                v-model="dateRangeCreateTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:inStockBill:add']">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['wms:inStockBill:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['wms:inStockBill:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:inStockBill:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <!--主表-->
      <el-table
        ref="tableRef"
        v-loading="loading"
        border
        :data="inStockBillList"
        @selection-change="handleSelectionChange"
        @expand-change="handleExpandChange"
        :row-key="(row) => row.inStockBillId"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-table :data="row.data" v-loading="row.loading" border style="width: 95%; margin: 0 auto">
              <el-table-column prop="productCode" align="center" label="物料编码" />
              <el-table-column prop="productName" align="center" label="物料名称" />
              <el-table-column prop="batchNumber" align="center" label="批次号" />
              <!--<el-table-column prop="unitPrice" align="center" label="单价" />-->
              <el-table-column prop="inStockAmount" align="center" label="入库数量" />
              <el-table-column prop="unitName" align="center" label="单位" />
              <!--<el-table-column prop="totalPrice" align="center" label="总价(元)" />-->
              <el-table-column prop="warehouseName" align="center" label="仓库名称" />
            </el-table>
          </template>
        </el-table-column>

        <!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="入库单ID" align="center" prop="inStockBillId" v-if="columns[0].visible" />
        <el-table-column label="入库单号" align="center" prop="inStockCode" v-if="columns[2].visible" width="150" />
        <el-table-column label="入库单类型" align="center" prop="inStockType" v-if="columns[3].visible">
          <template #default="scope">
            <dict-tag :options="wms_in_stock_type" :value="scope.row.inStockType" />
          </template>
        </el-table-column>
        <el-table-column label="所属项目" align="center" prop="projectId" v-if="columns[4].visible">
          <template #default="scope">
            {{ getProjectName(scope.row.projectId) }}
          </template>
        </el-table-column>
        <el-table-column label="关联单号" align="center" prop="inventoryAmount" v-if="columns[5].visible" />
        <el-table-column label="供应商" align="center" prop="supplierName" v-if="columns[6].visible" />
        <el-table-column label="联系人" align="center" prop="contactUser" v-if="columns[7].visible" />
        <el-table-column label="联系电话" align="center" prop="contactNumber" v-if="columns[8].visible" />
        <el-table-column label="入库说明" align="center" prop="directions" v-if="columns[9].visible" />
        <!--<el-table-column label="入库单状态" align="center" prop="inStockBillStatus" v-if="columns[10].visible">-->
        <!--  <template #default="scope">-->
        <!--    <dict-tag :options="wms_in_stock_bill_status" :value="scope.row.inStockBillStatus" />-->
        <!--  </template>-->
        <!--</el-table-column>-->
        <!--        <el-table-column label="流程状态" align="center" prop="flowStatus" v-if="columns[11].visible">-->
        <!--          <template #default="scope">-->
        <!--            <dict-tag :options="wf_business_status" :value="scope.row.flowStatus"></dict-tag>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[13].visible" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="columns[17].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180" v-if="columns[19].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="auto">
          <template #default="scope">
            <div style="display: flex; justify-content: center">
              <!--              <el-tooltip content="查看" placement="top">-->
              <!--                <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['wms:inStockBill:edit']"></el-button>-->
              <!--              </el-tooltip>-->
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wms:inStockBill:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wms:inStockBill:remove']"></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加物料入库对话框 -->
    <el-dialog :title="addDialog.title" v-model="addDialog.visible" width="auto" min-width="1500px" append-to-body>
      <el-form ref="addFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <!--          <el-col :span="12">
                      <el-form-item label="入库单号" prop="inStockCode">
                        <el-input v-model="form.inStockCode" placeholder="入库单号自动生成" disabled />
                      </el-form-item>
                    </el-col>-->
          <el-col :span="12">
            <el-form-item label="入库单类型" prop="inStockType">
              <el-select v-model="form.inStockType" placeholder="请选择入库单类型">
                <el-option v-for="dict in wms_in_stock_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联单号" prop="inventoryAmount">
              <el-input v-model="form.inventoryAmount" placeholder="请输入关联单号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="关联项目" prop="projectId">
              <el-select v-model="form.projectId" placeholder="请选择项目" filterable clearable>
                <el-option
                  v-for="dict in projectInfoList"
                  :key="dict.projectId"
                  :label="`${dict.projectCode} - ${dict.projectName}`"
                  :value="dict.projectId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <!--<el-input v-model="form.supplierName" placeholder="请输入供应商" />-->
              <el-select v-model="form.supplierName" filterable placeholder="请选择供应商" @change="onSupplierChanged">
                <el-option v-for="s in supplierList" :key="s.supplierId" :label="s.supplierName" :value="s.supplierName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactUser">
              <el-input v-model="form.contactUser" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="form.contactNumber" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 全宽字段 -->
        <el-form-item label="入库说明" prop="directions">
          <el-input v-model="form.directions" type="textarea" :rows="3" placeholder="请输入入库说明" style="width: 100%" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" style="width: 100%" />
        </el-form-item>
      </el-form>

      <div>
        <el-card>
          <template #header>
            <div>添加入库物料</div>
          </template>

          <el-button type="primary" @click="openProductSelect" :loading="productSelectLoading">选择物料</el-button>

          <div v-if="selectedProducts.length > 0" style="margin-top: 20px">
            <h4>已选择的物料：</h4>
            <el-table :data="selectedProducts" border>
              <!--              <el-table-column prop="materialId" label="物料编码" width="120"  header/>-->
              <el-table-column prop="productCode" label="物料编码" width="120" />
              <el-table-column prop="productName" label="物料名称" width="120" />
              <el-table-column prop="productSpe" label="物料描述" width="120" />
              <el-table-column prop="batchNumber" label="批次号" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.batchNumber" placeholder="自动生成批次号" :readonly="true" size="small" />
                </template>
              </el-table-column>
              <el-table-column prop="inventoryAmount" label="库存数量" width="120" align="center">
                <template #default="scope">
                  <span>{{ scope.row.inventoryAmount || 0 }}</span>
                </template>
              </el-table-column>
              <!--<el-table-column prop="unitPrice" label="单价(元)" width="140">-->
              <!--  <template #default="scope">-->
              <!--    <el-input-number-->
              <!--      v-model="scope.row.unitPrice"-->
              <!--      :min="0"-->
              <!--      :precision="2"-->
              <!--      :step="0.5"-->
              <!--      controls-position="right"-->
              <!--      size="small"-->
              <!--      placeholder="请输入单价"-->
              <!--      @change="calculateTotalPrice(scope.row)"-->
              <!--    />-->
              <!--  </template>-->
              <!--</el-table-column>-->
              <el-table-column prop="inStockAmount" label="入库数量" width="140">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.inStockAmount"
                    :min="1"
                    :precision="2"
                    :step="1"
                    controls-position="right"
                    size="small"
                    placeholder="请输入数量"
                  />
                  <!--@change="calculateTotalPrice(scope.row)"-->
                </template>
              </el-table-column>
              <el-table-column prop="unitName" label="单位" width="80" />
              <!--<el-table-column prop="totalPrice" label="总价(元)" width="120">-->
              <!--  <template #default="scope">-->
              <!--    <span>{{ scope.row.totalPrice || 0 }}</span>-->
              <!--  </template>-->
              <!--</el-table-column>-->
              <!--选择仓库-->
              <el-table-column prop="warehouseId" label="选择仓库" width="150">
                <template #default="scope">
                  <el-select v-model="scope.row.warehouseId" placeholder="请选择仓库">
                    <el-option
                      v-for="dict in wms_warehouse"
                      :key="dict.warehouseId"
                      :label="dict.warehouseName"
                      :value="dict.warehouseId"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="80">
                <template #default="scope">
                  <el-button link type="danger" icon="Delete" @click="removeMaterial(scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>

        <product-select ref="productSelectRef" :multiple="true" @confirmCallBack="handleProductSelect" />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="handleAddSubmit">确 定</el-button>
          <el-button @click="handleAddCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="InStockBill" lang="ts">
import { addInStockBill, delInStockBill, getInStockBill, listInStockBill, updateInStockBill } from '@/api/wms/inStockBill';
import { InStockBillForm, InStockBillQuery, InStockBillVO } from '@/api/wms/inStockBill/types';
import { ref } from 'vue'; // 存储选中的物料信息
import { useRouter } from 'vue-router'; // 存储选中的物料信息
import { getWmsInStockDetailsList } from '@/api/wms/inStockDetails';
import { getWmsWarehouseInfoList } from '@/api/wms/warehouseInfo';
import { getErpProjectInfoList } from '@/api/oa/erp/projectInfo'; // 添加展开行处理函数
import ProductSelect from '@/components/WmsProductSelect/index.vue';
import { parseTime } from '@/utils/ruoyi';
import { getWmsInventoryDetailbyProductId } from '@/api/wms/inventoryDetails';
import { getCrmSupplierInfoList } from '@/api/oa/crm/crmSupplierInfo';

// 添加展开行处理函数
const handleExpandChange = async (row, expandedRows) => {
  if (expandedRows.length && !row.data) {
    try {
      row.loading = true;
      const res = await getWmsInStockDetailsList({ inStockBillId: row.inStockBillId });
      row.data = res.data;
    } finally {
      row.loading = false;
    }
  }
};

// 物料选择
const productSelectRef = ref();
// 定义选中的物料列表
const selectedProducts = ref([]);
// 项目列表
const projectInfoList = ref([]);
/** 获取项目列表 */
const getProjectInfoList = async () => {
  const res = await getErpProjectInfoList({});
  projectInfoList.value = res.data || [];
};
// 打开物料选择弹窗的方法
const openProductSelect = () => {
  productSelectRef.value.open();
};
//供应商下拉数据
const supplierList = ref<any[]>([]);
const getSupplierInfoList = async () => {
  const res = await getCrmSupplierInfoList({});
  supplierList.value = res.data || [];
};
// 供应商下拉选择改变事件
const onSupplierChanged = (supplierId: any) => {
  const supplier = supplierList.value.find((x: any) => x.supplierId === supplierId);
  console.log(supplier);
  if (supplier) {
    // 从供应商信息中带出联系人、电话、邮箱（可编辑）
    form.value.contactUser = supplier.contactPerson || '';
    form.value.contactNumber = supplier.contactPhone || supplier.contactMobile || '';
    // form.supplierContactEmail = supplier.contactEmail || '';
  }
};
/** 根据项目ID获取项目名称 */
const getProjectName = (projectId) => {
  const project = projectInfoList.value.find((item) => item.projectId === projectId);
  return project ? project.projectCode : projectId;
};
// 添加物料选择loading状态
const productSelectLoading = ref(false);
// 处理物料选择回调
const handleProductSelect = async (products) => {
  // 重置所有的物料
  // selectedProducts.value = products;
  // 为每个物料添加批次号
  productSelectLoading.value = true;
  const timestamp = parseTime(new Date(), '{y}{m}{d}');
  for (const material of products) {
    // 生成批次号：供应商代码 + 时间戳
    // const supplierCode = form.value.supplierName ? form.value.supplier.substring(0, 4) : 'SUPP';
    // const timestamp = new Date().getTime();
    material.batchNumber = `${timestamp}`;

    // 设置默认单价为采购单价
    // material.unitPrice = material.purchasePrice || 0;
    material.inStockAmount = 1; // 默认数量为1
    // material.totalPrice = (material.unitPrice * material.inStockAmount).toFixed(2);
    const res = await getWmsInventoryDetailbyProductId(material.productId);
    material.inventoryAmount = res.data?.inventoryAmount || 0;
  }
  productSelectLoading.value = false;
  selectedProducts.value.push(...products);
};

// 存储选中的物料信息
const selectedMaterials = ref([]);
const materialSelectRef = ref();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wms_in_stock_type, wms_in_stock_bill_status } = toRefs<any>(proxy?.useDict('wms_in_stock_type', 'wms_in_stock_bill_status'));
const { wf_business_status } = toRefs<any>(proxy?.useDict('wf_business_status'));
const inStockBillList = ref<InStockBillVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);
const wms_warehouse = ref([]);
const queryFormRef = ref<ElFormInstance>();
const inStockBillFormRef = ref<ElFormInstance>();

const addFormRef = ref<ElFormInstance>();

// 计算总价
const calculateTotalPrice = (material) => {
  if (material.unitPrice && material.inStockAmount) {
    material.totalPrice = (material.unitPrice * material.inStockAmount).toFixed(2);
  } else {
    material.totalPrice = 0;
  }
};

// 删除物料行
const removeMaterial = (index) => {
  // selectedMaterials.value.splice(index, 1);
  selectedProducts.value.splice(index, 1);
};

// 打开物料选择对话框
const openMaterialSelect = () => {
  materialSelectRef.value.open();
};
// ... existing code ...

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const addDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `入库单ID`, visible: false },
  { key: 1, label: `租户编号`, visible: false },
  { key: 2, label: `入库单号`, visible: true },
  { key: 3, label: `入库单类型`, visible: true },
  { key: 4, label: `所属项目`, visible: true },
  { key: 5, label: `关联单号`, visible: true },
  { key: 6, label: `供应商`, visible: true },
  { key: 7, label: `联系人`, visible: false },
  { key: 8, label: `联系电话`, visible: false },
  { key: 9, label: `入库说明`, visible: true },
  { key: 10, label: `入库单状态`, visible: true },
  { key: 11, label: `流程状态`, visible: true },
  { key: 12, label: `仓库ID`, visible: true },
  { key: 13, label: `备注`, visible: true },
  { key: 14, label: `删除标志`, visible: false },
  { key: 15, label: `创建部门`, visible: false },
  { key: 16, label: `创建人`, visible: false },
  { key: 17, label: `创建时间`, visible: true },
  { key: 18, label: `更新人`, visible: false },
  { key: 19, label: `更新时间`, visible: false }
]);

const initFormData: InStockBillForm = {
  inStockBillId: undefined,
  inStockCode: undefined,
  inStockType: undefined,
  projectId: undefined,
  inventoryAmount: undefined,
  supplierName: undefined,
  contactUser: undefined,
  contactNumber: undefined,
  directions: undefined,
  inStockBillStatus: undefined,
  flowStatus: undefined,
  warehouseId: undefined,
  remark: undefined
};
const data = reactive<PageData<InStockBillForm, InStockBillQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    inStockType: undefined,
    projectId: undefined,
    inventoryAmount: undefined,
    supplierName: undefined,
    inStockBillStatus: undefined,
    flowStatus: undefined,
    warehouseId: undefined,
    params: {
      createTime: undefined
    }
  },
  rules: {
    // inStockBillId: [{ required: true, message: '入库单ID不能为空', trigger: 'blur' }],
    inStockType: [{ required: true, message: '请选择入库单类型', trigger: 'blur' }],
    projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }]

    // inStockBillId: [{ required: true, message: '入库单ID不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询物料入库列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  const res = await listInStockBill(queryParams.value);
  inStockBillList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  inStockBillFormRef.value?.resetFields();
};
// 添加表格ref
const tableRef = ref();
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  closeChildTable();
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeCreateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  closeChildTable();

  handleQuery();
};
// 关闭所有展开的子表
const closeChildTable = () => {
  if (tableRef.value) {
    tableRef.value.store.states.expandRows.value.forEach((row) => {
      tableRef.value.toggleRowExpansion(row, false);
    });
  }
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: InStockBillVO[]) => {
  ids.value = selection.map((item) => item.inStockBillId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const router = useRouter();

const getWarehouseList = async () => {
  const res = await getWmsWarehouseInfoList();
  wms_warehouse.value = res.data;
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  addFormRef.value?.resetFields();
  selectedProducts.value = [];
  // selectedMaterials.value = [];
  addDialog.title = '添加物料入库';
  addDialog.visible = true;
  // getWarehouseList();
  // dialog.title = '添加物料入库';
  // materialSelectRef.value.open();
  // router.push('/wms/inStockBill/add');
};

/** 添加表单提交 */
const handleAddSubmit = () => {
  addFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 验证是否选择了物料
      if (selectedProducts.value.length === 0) {
        proxy?.$modal.msgError('请至少选择一个物料');
        return;
      }

      // 验证物料信息的完整性
      const invalidMaterials = selectedProducts.value.filter((material) => {
        return !material.inStockAmount || material.inStockAmount <= 0 || !material.warehouseId;
      });

      if (invalidMaterials.length > 0) {
        proxy?.$modal.msgError('请完善物料信息，确保数量都大于0，且选择了仓库');
        return;
      }

      buttonLoading.value = true;
      try {
        // 准备提交数据，包含物料明细
        const submitData = {
          ...form.value,
          // 添加物料明细信息
          inStockDetailsList: selectedProducts.value.map((material) => ({
            inStockDetailsId: material.inStockDetailsId, // 物料ID
            materialId: material.productId, // 物料ID
            batchNumber: material.batchNumber, // 批次号
            // unitPrice: material.unitPrice, // 单价
            inStockAmount: material.inStockAmount, // 数量
            unitName: material.unitName, // 单位
            // totalPrice: material.totalPrice, // 总价
            warehouseId: material.warehouseId // 仓库ID
          }))
        };

        // 根据是否有inStockBillId判断是新增还是修改
        if (form.value.inStockBillId) {
          // 修改操作
          await updateInStockBill(submitData);
          closeChildTable();
          proxy?.$modal.msgSuccess('修改成功');
        } else {
          // 新增操作
          await addInStockBill(submitData);
          proxy?.$modal.msgSuccess('添加成功');
        }

        addDialog.visible = false;

        // 清空已选择的物料
        selectedProducts.value = [];
        await getList();
      } catch (error) {
        console.error('操作失败:', error);
        proxy?.$modal.msgError(form.value.inStockBillId ? '修改失败，请重试' : '添加失败，请重试');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 添加表单取消 */
const handleAddCancel = () => {
  addDialog.visible = false;
  addFormRef.value?.resetFields();
};

/** 修改按钮操作 */
const handleUpdate = async (row?: InStockBillVO) => {
  reset();
  const _inStockBillId = row?.inStockBillId || ids.value[0];
  const res = await getInStockBill(_inStockBillId);
  Object.assign(form.value, res.data);

  const childList = await getWmsInStockDetailsList({ inStockBillId: row.inStockBillId });
  selectedProducts.value = childList.data;

  addDialog.title = '修改物料入库';
  addDialog.visible = true;
};

/*/!** 提交按钮 *!/
const submitForm = () => {
  inStockBillFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.inStockBillId) {
        await updateInStockBill(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addInStockBill(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};*/

/** 删除按钮操作 */
const handleDelete = async (row?: InStockBillVO) => {
  const _inStockBillIds = row?.inStockBillId || ids.value;
  await proxy?.$modal.confirm('是否确认删除物料入库编号为"' + _inStockBillIds + '"的数据项？').finally(() => (loading.value = false));
  await delInStockBill(_inStockBillIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'wms/inStockBill/export',
    {
      ...queryParams.value
    },
    `inStockBill_${new Date().getTime()}.xlsx`
  );
};
/** 查看按钮操作 */
const handleView = (row?: InStockBillVO) => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: '/wms/inStockEdit',
    query: {
      id: row.inStockBillId,
      type: row.flowStatus === 'draft' ? 'update' : 'view'
    }
  });
};
onMounted(() => {
  getList();
  getWarehouseList();
  getProjectInfoList(); // 获取项目 列表
  getSupplierInfoList();
});
</script>
