<template>
  <div class="p-2">
    <el-card shadow="never">
      <el-form label-width="120px" label-position="right" :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="订单编号" prop="poNo">
          <el-input v-model="queryForm.poNo" placeholder="请输入订单编号" clearable/>
        </el-form-item>
        <el-form-item label="订单状态" prop="poStatus">
          <el-select v-model="queryForm.poStatus" placeholder="请选择订单状态" clearable>
            <el-option v-for="dict in wms_po_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="订单类型" prop="poType">-->
<!--          <el-select v-model="queryForm.poType" placeholder="请选择订单类型" clearable>-->
<!--            <el-option v-for="dict in wms_po_type" :key="dict.value" :label="dict.label" :value="dict.value"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="物料大类" prop="materialCategoryId">-->
<!--          <el-select v-model="queryForm.materialCategoryId" placeholder="请选择物料大类" clearable>-->
<!--            <el-option v-for="item in mategoryOptions"-->
<!--                       :key="item.materialCategoryId"-->
<!--                       :label="item.materialCategoryName"-->
<!--                       :value="item.materialCategoryId"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="审核状态" prop="auditStatus">-->
<!--          <el-select v-model="queryForm.auditStatus" placeholder="请选择审核状态" clearable>-->
<!--            <el-option v-for="dict in wms_audit_status" :key="dict.value" :label="dict.label" :value="dict.value"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button :loading="parentTableLoad" type="primary" @click="query">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 8px" shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="parentTableAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="ids.length !== 1" @click="parentTableUpdate()">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="ids.length < 1" @click="parentTableDelete()">删除
            </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true"
                         @queryTable="getParentTable"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="parentTableLoad" :data="parentTableData" style="width: 100%" highlight-current-row
                @current-change="parentTableCellClick"
                @selection-change="selectionChange" ref="parentTableRef">
        <el-table-column type="selection" width="55"/>

        <el-table-column label="订单编号" align="center" prop="poNo"/>
        <el-table-column label="订单状态" align="center" prop="poStatus">
          <template #default="scope">
            <dict-tag :options="wms_po_status" :value="scope.row.poStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="计划交货日期" align="center" prop="planDeliveryDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.planDeliveryDate, '{y}-{m}-{d} ') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="供应商" align="center" prop="supplierName"/>
        <el-table-column label="订单类型" align="center" prop="poType">
          <template #default="scope">
            <dict-tag :options="wms_po_type" :value="scope.row.poType"/>
          </template>
        </el-table-column>
        <!-- <el-table-column label="单据的ID" align="center" prop="erpId"/> -->
        <el-table-column label="备注" align="center" prop="remark"/>
        <!-- <el-table-column label="租户号" align="center" prop="tenantId"/> -->
        <!-- <el-table-column label="创建人" align="center" prop="createBy"/>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180"> -->
        <!-- <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="updateBy"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <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" prop="materialCategoryId">-->

<!--        </el-table-column>-->
<!--        <el-table-column label="审核人" align="center" prop="auditBy"/>-->
<!--        <el-table-column label="审核时间" align="center" prop="auditTime" width="180">-->
<!--          <template #default="scope">-->
<!--            <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="审核状态" align="center" prop="auditStatus">-->
<!--          <template #default="scope">-->
<!--            <dict-tag :options="wms_audit_status" :value="scope.row.auditStatus"/>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="审核意见" align="center" prop="auditComments"/>-->
        <!-- <el-table-column label="入库方式" align="center" prop="inMethod">
          <template #default="scope">
            <dict-tag :options="wms_allocate_way" :value="scope.row.inMethod"/>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <!--            <el-button size="small" @click.stop="viewDetails(scope.row)">-->
            <!--              查看-->
            <!--            </el-button>-->
            <el-button size="small" @click.stop="parentTableUpdate(scope.row)">
              修改
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click.stop="parentTableDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="parentTableTotal > 0" :total="parentTableTotal" v-model:page="queryForm.pageNum"
                  v-model:limit="queryForm.pageSize" @pagination="getParentTable"/>
    </el-card>

    <el-card style="margin-top: 8px" shadow="never">
      <el-table :data="childrenTableData" style="width: 100%" v-loading="childrenTableLoad">
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <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="materialCode"/>
        <el-table-column label="物料名称" align="center" prop="materialName"/>
        <el-table-column label="采购订单编号" align="center" prop="poNo"/>
        <el-table-column label="含税单价" align="center" prop="taxPrice"/>
        <el-table-column label="采购数量" align="center" prop="purchaseQty"/>
        <el-table-column label="物料规格" align="center" prop="materialSpe"/>
        <el-table-column label="计量单位名称" align="center" prop="unitName"/>
        <el-table-column label="送货数量" align="center" prop="deliveryQty"/>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <!-- <el-button size="small" @click="childrenTableUpdate( scope.row)">
             打印
             </el-button> -->
            <el-button
              size="small"
              type="danger"
              @click="childrenTableUDelete(scope.row)"
            >
              删除
            </el-button>
            <!-- <el-tooltip content="打印" placement="top">
              <el-button type="primary" @click="handlePrint(scope.row)">打印</el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%">
      <el-card shadow="never">
        <el-form :model="dialogForm" :inline="true" label-width="120px" :disabled="isView">
          <!-- <el-form-item label="订单编号" prop="poNo">
          <el-input v-model="dialogForm.poNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="订单状态" prop="poStatus">
          <el-select v-model="dialogForm.poStatus" placeholder="请选择订单状态">
            <el-option
                v-for="dict in wms_po_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
          <el-form-item label="计划交货日期" prop="planDeliveryDate">
            <el-date-picker clearable
                            v-model="dialogForm.planDeliveryDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择计划交货日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="供应商" prop="supplierId">
            <!--          <el-input v-model="form.supplierId" placeholder="请输入供应商ID" />-->
            <el-select v-model="dialogForm.supplierId" placeholder="请选择供应商">
              <el-option
                v-for="item in supplierList"
                :key="item.supplierId"
                :label="item.supplierName"
                :value="item.supplierId"
              ></el-option>
            </el-select>
          </el-form-item>
<!--          <el-form-item label="订单类型" prop="poType">-->
<!--            <el-select v-model="dialogForm.poType" placeholder="请选择订单类型">-->
<!--              <el-option-->
<!--                v-for="dict in wms_po_type"-->
<!--                :key="dict.value"-->
<!--                :label="dict.label"-->
<!--                :value="dict.value"-->
<!--              ></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <!--        <el-form-item label="单据的ID，连表扩充" prop="erpId">
                    <el-input v-model="form.erpId" placeholder="请输入单据的ID，连表扩充" />
                  </el-form-item>-->
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dialogForm.remark" placeholder="请输入备注"/>
          </el-form-item>
<!--          <el-form-item label="物料大类" prop="materialCategoryId">-->
<!--            <el-select v-model="dialogForm.materialCategoryId" placeholder="请选择物料大类" @change="setMaterialList">-->
<!--              <el-option v-for="item in mategoryOptions"-->
<!--                         :key="item.materialCategoryId"-->
<!--                         :label="item.materialCategoryName"-->
<!--                         :value="item.materialCategoryId"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="审核人" prop="auditBy">-->
<!--            <el-select v-model="dialogForm.auditBy" placeholder="请选择审核人">-->
<!--              <el-option-->
<!--                v-for="item in userList"-->
<!--                :key="item.userId"-->
<!--                :label="item.userName"-->
<!--                :value="item.userName"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
        </el-form>
      </el-card>
      <el-card style="margin-top: 8px" shadow="never">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="addDialogTableCell">新增</el-button>
          </el-col>
        </el-row>
        <el-table :data="dialogtable" border style="width: 100%">
          <el-table-column label="物料编码" prop="materialCode">
            <!--            <template #default="scope">
                          <el-select
                            v-model="scope.row.materialId"
                            placeholder="选择物料"
                            style="width: 240px"
                          >
                            <el-option
                              v-for="i in materialList"
                              :label="i.materialCode"
                              :value="i.materialId"
                              :key="i.materialId"
                            />
                          </el-select>
                        </template>-->
            <template #default="scope">
              <el-input
                v-model="scope.row.materialCode"
                placeholder="请点击检索物料"
                readonly
                @click="handleMaterialAdd('material', scope.$index)">
                <template #append>
                  <el-icon class="el-input__icon">
                    <search/>
                  </el-icon>
                </template>
              </el-input>
            </template>
          </el-table-column>

          <el-table-column label="物料名称" prop="materialName">
            <template #default="scope">
              <el-select
                v-model="scope.row.materialName"
                placeholder="选择物料"
                style="width: 240px"
                :disabled="true"
              >
                <el-option
                  v-for="i in materialList"
                  :label="i.materialName"
                  :value="i.materialName"
                  :key="i.materialId"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="物料单位" prop="unitName">
            <template #default="scope">
              <el-select
                v-model="scope.row.unitName"
                placeholder="选择物料"
                style="width: 240px"
                :disabled="true"
              >
                <el-option
                  v-for="i in materialList"
                  :label="i.materialUnit"
                  :value="i.materialUnit"
                  :key="i.materialId"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="物料规格" prop="materialSpe">
            <template #default="scope">
              <el-select
                v-model="scope.row.materialSpe"
                placeholder="选择物料"
                style="width: 240px"
                :disabled="true"
              >
                <el-option
                  v-for="i in materialList"
                  :label="i.materialSpec"
                  :value="i.materialSpec"
                  :key="i.materialId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="含税单价" prop="taxPrice">
            <template #default="scope">
              <el-input v-model="scope.row.taxPrice" placeholder="请输入含税单价" style="width: 240px"/>
            </template>
          </el-table-column>
          <el-table-column label="采购数量" prop="purchaseQty">
            <template #default="scope">
              <el-input v-model="scope.row.purchaseQty" placeholder="请输入采购数量" style="width: 240px"/>
            </template>
          </el-table-column>
           <el-table-column label="送货数量" prop="deliveryQty" readonly>
            <template #default="scope">
              <el-input v-model="scope.row.deliveryQty" placeholder="送货数量不可编辑" style="width: 240px" disabled/>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="200">
            <template #default="scope">
              <el-button
                size="small"
                type="danger"
                @click="tableUDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="dialogSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="parentTableInfoVisible" title="修改父表格" width="40%">
      <el-form :model="parentTableInfoForm" label-width="120px">
        <el-form-item label="计划日期" prop="supplierId">
          <el-date-picker clearable
                          v-model="parentTableInfoForm.planDeliveryDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择计划交货日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="parentTableInfoForm.supplierId" placeholder="请选择供应商">
            <el-option
              v-for="item in supplierList"
              :key="item.supplierId"
              :label="item.supplierCode"
              :value="item.supplierId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="parentTableInfoForm.remark" placeholder="请输入备注" />
        </el-form-item>

<!--        <el-form-item label="订单类型" prop="poType">-->
<!--          <el-select v-model="parentTableInfoForm.poType" placeholder="请选择订单类型">-->
<!--            <el-option-->
<!--              v-for="dict in wms_po_type"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="dict.value"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="物料大类" prop="materialCategoryId">
          <el-select v-model="parentTableInfoForm.materialCategoryId" placeholder="请选择物料大类">
            <el-option v-for="item in mategoryOptions"
                       :key="item.materialCategoryId"
                       :label="item.materialCategoryName"
                       :value="item.materialCategoryId"
            />
          </el-select>
        </el-form-item>-->
<!--        <el-form-item label="审核人" prop="auditBy">-->
<!--          <el-select v-model="parentTableInfoForm.auditBy" placeholder="请选择审核人">-->
<!--            <el-option-->
<!--              v-for="item in userList"-->
<!--              :key="item.userId"-->
<!--              :label="item.userName"-->
<!--              :value="item.userName"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="parentTableInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="parentTableInfoSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="childrenTableInfoVisible" title="条码生成" width="40%">
      <el-form :model="childrenTableInfoForm" label-width="120px">
        <el-form-item label="物料" prop="materialCode">
          <el-select v-model="childrenTableInfoForm.materialId" placeholder="请选择物料" :disabled="true">
            <el-option
              v-for="item in materialList"
              :key="item.materialId"
              :label="item.materialCode"
              :value="item.materialId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库数量" prop="instockQty">
          <el-input v-model="childrenTableInfoForm.instockQty" placeholder="请输入入库数量" :disabled="true"/>
        </el-form-item>
        <el-form-item label="有无条码" prop="codeYesNo">
          <el-radio-group v-model="childrenTableInfoForm.codeYesNo" :disabled="true">
            <el-radio
              v-for="dict in wms_barcode_if"
              :key="dict.value"
              :value="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="已包数量" prop="printedNum">
          <el-input v-model="childrenTableInfoForm.printedNum" placeholder="" :disabled="true"/>
        </el-form-item>
        <el-form-item label="分包数量" prop="printNum">
          <el-input v-model="childrenTableInfoForm.printNum" placeholder="请输入分包数量"/>
        </el-form-item>
        <el-form-item label="打印数量" prop="barcodeNum">
          <el-input v-model="childrenTableInfoForm.barcodeNum" placeholder="请输入打印条码数量"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="childrenTableInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 添加物料信息对话框 -->
    <el-dialog title="选择物料信息" v-model="materialOpen" width='1200px' append-to-body>
      <MaterialSelectInWMS
        @selection="handleSelection"
        ref="materialSelectRef"
        v-if="materialOpen"
        :materialCategoryId="dialogForm.materialCategoryId"
      ></MaterialSelectInWMS>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMaterialForm">确 定</el-button>
        <el-button @click="materialOpen = false">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script setup name="Linkage" lang="ts">

import MaterialSelectInWMS from '@/views/wms/baseMaterialInfo/addMaterialInWMS.vue';

import {
  listWmsPurchaseOrder,
  getWmsPurchaseOrder,
  delWmsPurchaseOrder,
  addWmsPurchaseOrder,
  updateWmsPurchaseOrder
} from '@/api/wms/wmsPurchaseOrder';
import {WmsPurchaseOrderVO, WmsPurchaseOrderQuery, WmsPurchaseOrderForm} from '@/api/wms/wmsPurchaseOrder/types';
import {reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getBaseWarehouseList} from "@/api/wms/baseWarehouse";
import {UserVO} from "@/api/system/user/types";
import {listUser} from "@/api/system/user";
import {getBaseSupplierInfoList} from '@/api/wms/baseSupplierInfo'
import {
  listWmsPurchaseOrderDetail,
  getWmsPurchaseOrderDetail,
  delWmsPurchaseOrderDetail,
  addWmsPurchaseOrderDetail,
  updateWmsPurchaseOrderDetail
} from '@/api/wms/wmsPurchaseOrderDetail';
import {
  WmsPurchaseOrderDetailVO,
  WmsPurchaseOrderDetailQuery,
  WmsPurchaseOrderDetailForm
} from '@/api/wms/wmsPurchaseOrderDetail/types';
import {
  getMaterialList, getInstockMaterialList
} from '@/api/wms/linkage'
import {getBaseMaterialCategoryListInWMS} from '@/api/wms/baseMaterialCategory';
const showSearch = ref(true);
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {
  wms_barcode_if,
  wms_po_status,
  wms_po_type,
  wms_audit_status,


} = toRefs<any>(proxy?.useDict('wms_barcode_if', 'wms_po_status', 'wms_po_type', 'wms_audit_status'));


interface User {
  date: string
  name: string
  address: string
}

let supplierList = ref([])
const parentTableTotal = ref(0)
const dialogVisible = ref(false)
const parentTableInfoVisible = ref(false)
const childrenTableInfoVisible = ref(false)
// const childrenTableInfoSubmit = ref(false)
const updateDialog = ref(false)
const dialogTitle = ref('添加')
const dialogForm = ref({})
const parentTableInfoForm = ref({})
const childrenTableInfoForm = ref({})
const getListSelect = async () => {
  let res = await getBaseSupplierInfoList(null);
  supplierList.value = res.data;
}
const queryForm = ref({
  poNo: '',
  poStatus: '',
  poType: '',
  materialCategoryId: '',
  auditStatus: '',
  pageNum: 1,
  pageSize: 10
})
const parentTableRef = ref()
const parentTableData = ref([])
const ids = ref([])
const childrenTableData = ref([])
const dialogtable = ref([])
const baseStoreList = ref([]);
const userList = ref([]);
const materialList = ref([]);
const parentTableLoad = ref(false)
const childrenTableLoad = ref(false)
const isView = ref(false)
const partntTableSelectCell = ref({})

// 获取仓库
getBaseWarehouseList().then(e => {
  baseStoreList.value = e.data
})


const getUserList = () => {
  getMaterialCategorySelect();
  listUser().then(e => {
    userList.value = e.rows;
  })
}
/** 提交按钮 */
const submitForm = () => {
  updateWmsPurchaseOrderDetail(childrenTableInfoForm.value).finally(() => childrenTableInfoVisible.value = false);
  getChildrenTable({poNo: partntTableSelectCell.value.poNo})
}

//获取物料大类
let mategoryOptions = ref([]);
const getMaterialCategorySelect = async () => {
  const res = await getBaseMaterialCategoryListInWMS(null);
  mategoryOptions.value = res.data;
};


// 获取父表格数据
const getParentTable = async () => {

  await getMaterialCategorySelect();

  parentTableLoad.value = true
  await listWmsPurchaseOrder(queryForm.value).then(async (e) => {
    parentTableLoad.value = false
    parentTableData.value = e.rows
    console.log(e.total)
    parentTableTotal.value = e.total
    if (e.rows.length > 0) {
      parentTableRef.value.setCurrentRow(e.rows[0])

      await getChildrenTable({poNo: e.rows[0].poNo})
    } else {
      childrenTableData.value = []
    }
  })
}

// 获取子表格数据
const getChildrenTable = async (form) => {
  childrenTableLoad.value = true
  console.log(form)
  await listWmsPurchaseOrderDetail(form).then(e => {
    childrenTableLoad.value = false
    childrenTableData.value = e.rows
    // parentTableTotal.value = e.total
  })
}

getParentTable()
/** 打印按钮操作 */
// const handlePrint = async (row?: InstockDetailVO) => {
//   reset();
//   const _instockDetailId = row?.instockDetailId || ids.value[0]
//   const res = await getInstockDetail(_instockDetailId);
//   Object.assign(childrenTableInfoForm.value, res.data);


// }
// 查询
const query = async () => {
  ids.value = []
  parentTableRef.value?.clearSelection()
  await getParentTable()
}
const reset = () => {
  queryForm.value = {
    poNo: ''
  }
  getParentTable();
}

// 父表格行点击
const parentTableCellClick = async (e) => {
  partntTableSelectCell.value = e
  await getChildrenTable({poNo: e.poNo})
}

// 表格多选
const selectionChange = (e) => {
  ids.value = e.map(v => v.poId)
}
// 查看
const viewDetails = (e) => {
  isView.value = true
  dialogVisible.value = true
  viewAllocateOrder(e.aoId).then(v => {
    dialogForm.value = v.data
  })
}

// 父表格新增
const parentTableAdd = () => {
  getUserList();
  getListSelect();
  dialogVisible.value = true
  dialogForm.value = {}
  dialogtable.value = []
}

// 父表格修改
const parentTableUpdate = async (e) => {
  getListSelect();
  let id = ref(null)
  if (e) {
    id.value = e.poId
  } else {
    id.value = ids.value?.[0]
  }
  if (!id.value) return
  parentTableInfoForm.value = (await getWmsPurchaseOrder(id.value)).data
  parentTableInfoForm.value.createBy = ''
  parentTableInfoVisible.value = true
  updateDialog.value = true
}

// 父表格删除
const parentTableDelete = async (e) => {
  const delList = ref([])
  if (e) {
    delList.value = [e.poId]
  } else {
    delList.value = ids.value
  }
  ElMessageBox.confirm(
    '确定要删除这些数据吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await delWmsPurchaseOrder(delList.value.toString()).then(e => {
        ElMessage({
          type: 'success',
          message: '删除完成',
        })
        getParentTable()
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消',
      })
    })

}

// 获取物料列表
const setMaterialList = (materialCategoryId) => {
  getMaterialList({materialCategoryId}).then(e => {
    materialList.value = e.data
  })
}

// 添加子表格行
const addDialogTableCell = () => {
  // 验证现有行是否都已选择物料
  for (let i = 0; i < dialogtable.value.length; i++) {
    const row = dialogtable.value[i];
    if (!row.materialId || !row.materialCode) {
      ElMessage({
        type: 'warning',
        message: `第${i + 1}行必须先选择物料！`,
      });
      return;
    }
  }

  // 所有现有行都已选择物料，才允许新增
  dialogtable.value.push({});
}

// 新增提交
const dialogSubmit = () => {
  // 验证采购订单基本信息
  if (!dialogForm.value.supplierId) {
    ElMessage({
      type: 'warning',
      message: '请选择供应商！',
    });
    return;
  }

  // 验证是否有采购明细
  if (!dialogtable.value || dialogtable.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请至少添加一行采购明细！',
    });
    return;
  }

  // 验证每行采购明细是否都已选择物料并填写必要信息
  for (let i = 0; i < dialogtable.value.length; i++) {
    const row = dialogtable.value[i];

    // 验证物料是否选择
    if (!row.materialId || !row.materialCode) {
      ElMessage({
        type: 'warning',
        message: `第${i + 1}行必须选择物料！`,
      });
      return;
    }

    // 验证采购数量
    if (!row.purchaseQty || row.purchaseQty <= 0) {
      ElMessage({
        type: 'warning',
        message: `第${i + 1}行采购数量必须大于0！`,
      });
      return;
    }

    // 验证含税单价
    // if (!row.taxPrice || row.taxPrice <= 0) {
    //   ElMessage({
    //     type: 'warning',
    //     message: `第${i + 1}行含税单价必须大于0！`,
    //   });
    //   return;
    // }
  }

  // 所有验证通过，提交数据
  addWmsPurchaseOrder(dialogForm.value).then(e => {
    addWmsPurchaseOrderDetail(dialogtable.value.map(item => {
          return {...item, poNo: e.data.poNo}
        }
      )
    ).then(v => {
      ElMessage({
        type: 'success',
        message: '采购订单创建成功！',
      });
      dialogVisible.value = false
      getParentTable()
    }).catch(error => {
      ElMessage({
        type: 'error',
        message: '采购订单明细保存失败：' + (error.message || '未知错误'),
      });
    })
  }).catch(error => {
    ElMessage({
      type: 'error',
      message: '采购订单保存失败：' + (error.message || '未知错误'),
    });
  })
}

const parentTableInfoSubmit = () => {
  updateWmsPurchaseOrder(parentTableInfoForm.value).then(e => {
    ElMessage({
      type: 'success',
      message: '修改完成',
    })
    parentTableInfoVisible.value = false
    getParentTable()
  })
}

// 子表格修改
const childrenTableUpdate = async (e) => {
  childrenTableInfoForm.value = (await getInstockDetail(e.instockDetailId)).data
  childrenTableInfoVisible.value = true
}
// 子表格数据新增删除
const tableUDelete = (row) => {

  ElMessageBox.confirm(
    '确定要删除这些数据吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const index = dialogtable.value.indexOf(row);
      console.log(index)
      dialogtable.value.splice(index, 1)
    })

}

// 子表格删除
const childrenTableUDelete = (e) => {

  ElMessageBox.confirm(
    '确定要删除这些数据吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await delWmsPurchaseOrderDetail(e.poDId).then(async (e) => {
        ElMessage({
          type: 'success',
          message: '删除完成',
        })
        await getChildrenTable({poNo: partntTableSelectCell.value.poNo})
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消',
      })
    })
}

/*     以下为添加物料信息对话框相关方法   */
let materialSelectRef = ref();//物料选择对话框绑定
const materialOpen = ref(false);//物料选择对话框显示
const selectType = ref(''); // 用于标识当前选择的是哪个字段
const selectedMaterial = ref(null); // 存储选中的物料完整信息
const currentRowIndex = ref(-1); // 存储当前正在编辑的行索引

/** 处理从MaterialSelect组件接收到的选择 */
const handleSelection = (row) => {
  selectedMaterial.value = row;
};

/** 提交物料BOM信息按钮 */
const submitMaterialForm = () => {
  if (!selectedMaterial.value) {
    // 如果没有选中行，则尝试从表格中获取
    if (materialSelectRef.value && materialSelectRef.value.tableRef && materialSelectRef.value.tableRef.store.states.currentRow.value) {
      selectedMaterial.value = materialSelectRef.value.tableRef.store.states.currentRow.value;
    }
  }

  if (!selectedMaterial.value) {
    ElMessage({
      type: 'warning',
      message: '请选择一个物料！',
    });
    return;
  }

  // 验证必要的物料信息
  if (!selectedMaterial.value.materialId || !selectedMaterial.value.materialCode) {
    ElMessage({
      type: 'error',
      message: '选中的物料信息不完整，请重新选择！',
    });
    return;
  }

  if (selectedMaterial.value) {
    if (selectType.value === 'material') {
      // 验证当前行索引是否有效
      if (currentRowIndex.value < 0 || currentRowIndex.value >= dialogtable.value.length) {
        ElMessage({
          type: 'error',
          message: '无效的行索引！',
        });
        return;
      }

      // 检查物料是否已在其他行中使用
      for (let i = 0; i < dialogtable.value.length; i++) {
        if (i !== currentRowIndex.value && dialogtable.value[i].materialId === selectedMaterial.value.materialId) {
          ElMessage({
            type: 'warning',
            message: `该物料已在第${i + 1}行中使用，请选择其他物料！`,
          });
          return;
        }
      }

      // 更新当前正在编辑的行
      if (dialogtable.value[currentRowIndex.value]) {
        dialogtable.value[currentRowIndex.value].materialId = selectedMaterial.value.materialId;
        dialogtable.value[currentRowIndex.value].materialName = selectedMaterial.value.materialName;
        dialogtable.value[currentRowIndex.value].materialCode = selectedMaterial.value.materialCode;
        dialogtable.value[currentRowIndex.value].unitName = selectedMaterial.value.materialUnit;
        dialogtable.value[currentRowIndex.value].materialSpe = selectedMaterial.value.materialSpec;

        ElMessage({
          type: 'success',
          message: '物料选择成功！',
        });
      }
    }
  }

  // 重置选中的物料信息和关闭对话框
  selectedMaterial.value = null;
  currentRowIndex.value = -1;
  materialOpen.value = false;
};

/** 新增按钮操作 */
const handleMaterialAdd = (type, index) => {
  // 验证索引是否有效
  if (index < 0 || index >= dialogtable.value.length) {
    ElMessage({
      type: 'error',
      message: '行索引无效！',
    });
    return;
  }

  selectType.value = type;
  currentRowIndex.value = index; // 保存当前正在编辑的行索引
  materialOpen.value = true;
}

/*// 初始化dialogtable
onMounted(() => {
  // 其他初始化代码

  // 确保dialogtable初始化为空数组
  dialogtable.value = [];
});*/

</script>
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
