<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="出库单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入出库单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库ID" prop="warehouseId">
        <el-input
          v-model="queryParams.warehouseId"
          placeholder="请输入仓库ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户ID" prop="customerId">
        <el-input
          v-model="queryParams.customerId"
          placeholder="请输入客户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关联单号" prop="relatedOrderNo">
        <el-input
          v-model="queryParams.relatedOrderNo"
          placeholder="请输入关联单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="applicantId">
        <el-input
          v-model="queryParams.applicantId"
          placeholder="请输入申请人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="applyTime">
        <el-date-picker clearable
          v-model="queryParams.applyTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预计发货日期" prop="expectedDeliveryDate">
        <el-date-picker clearable
          v-model="queryParams.expectedDeliveryDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择预计发货日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="实际发货日期" prop="actualDeliveryDate">
        <el-date-picker clearable
          v-model="queryParams.actualDeliveryDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择实际发货日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="拣货员" prop="pickingPersonId">
        <el-input
          v-model="queryParams.pickingPersonId"
          placeholder="请输入拣货员"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="拣货时间" prop="pickingTime">
        <el-date-picker clearable
          v-model="queryParams.pickingTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择拣货时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="复核员" prop="checkerId">
        <el-input
          v-model="queryParams.checkerId"
          placeholder="请输入复核员"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="复核时间" prop="checkTime">
        <el-date-picker clearable
          v-model="queryParams.checkTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择复核时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="发货员" prop="deliveryPersonId">
        <el-input
          v-model="queryParams.deliveryPersonId"
          placeholder="请输入发货员"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发货时间" prop="deliveryTime">
        <el-date-picker clearable
          v-model="queryParams.deliveryTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择发货时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="出库策略" prop="outboundStrategy">
        <el-input
          v-model="queryParams.outboundStrategy"
          placeholder="请输入出库策略"
          clearable
          @keyup.enter="handleQuery"
        />
      </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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ware:wmsOutboundOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ware:wmsOutboundOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ware:wmsOutboundOrder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ware:wmsOutboundOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wmsOutboundOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="出库单号" align="center" prop="orderNo" width="180" fixed="left" />
      <el-table-column label="出库类型" align="center" prop="orderType" >
        <template #default="scope">
          <dict-tag :options="outbound_type" :value="scope.row.orderType" />
        </template>
      </el-table-column>
      <el-table-column label="仓库ID" align="center" prop="warehouseId" />
      <el-table-column label="客户ID" align="center" prop="customerId" />
      <el-table-column label="关联单号" align="center" prop="relatedOrderNo" />
      <el-table-column label="总数量" align="center" prop="totalQuantity" />
      <el-table-column label="总金额" align="center" prop="totalAmount" />
      <el-table-column label="单据状态" align="center" prop="orderStatus" />
      <el-table-column label="申请人" align="center" prop="applicantId" />
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计发货日期" align="center" prop="expectedDeliveryDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expectedDeliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际发货日期" align="center" prop="actualDeliveryDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.actualDeliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="拣货员" align="center" prop="pickingPersonId" />
      <el-table-column label="拣货时间" align="center" prop="pickingTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.pickingTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="复核员" align="center" prop="checkerId" />
      <el-table-column label="复核时间" align="center" prop="checkTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.checkTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发货员" align="center" prop="deliveryPersonId" />
      <el-table-column label="发货时间" align="center" prop="deliveryTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="approvalStatus" />
      <el-table-column label="出库策略" align="center" prop="outboundStrategy" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ware:wmsOutboundOrder:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ware:wmsOutboundOrder:remove']">删除</el-button>
          <el-button link type="primary" icon="Document" @click="handlePrint(scope.row)" v-hasPermi="['ware:wmsOutboundOrder:print']">打印</el-button>
        </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-dialog :title="title" v-model="open" width="1500px" append-to-body>
      <el-form ref="wmsOutboundOrderRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出库单号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入出库单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <el-row :gutter="10">
                <el-col :span="18">
                  <el-input v-model="form.warehouseId" placeholder="请选择仓库" readonly />
                </el-col>
                <el-col :span="6">
                  <el-button type="primary" @click="openWarehouseSelect">选择仓库</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户" prop="customerId">
              <el-row :gutter="10">
                <el-col :span="18">
                  <el-input v-model="form.customerId" placeholder="请选择客户" readonly />
                </el-col>
                <el-col :span="6">
                  <el-button type="primary" @click="openCustomerSelect">选择客户</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联单号" prop="relatedOrderNo">
              <el-input v-model="form.relatedOrderNo" placeholder="请输入关联单号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总数量" prop="totalQuantity">
              <el-input v-model="form.totalQuantity" placeholder="请输入总数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总金额" prop="totalAmount">
              <el-input v-model="form.totalAmount" placeholder="请输入总金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请人" prop="applicantId">
              <el-input v-model="form.applicantId" placeholder="请输入申请人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请时间" prop="applyTime">
              <el-date-picker clearable
                v-model="form.applyTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择申请时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预计发货日期" prop="expectedDeliveryDate">
              <el-date-picker clearable
                v-model="form.expectedDeliveryDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择预计发货日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际发货日期" prop="actualDeliveryDate">
              <el-date-picker clearable
                v-model="form.actualDeliveryDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择实际发货日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="拣货员" prop="pickingPersonId">
              <el-input v-model="form.pickingPersonId" placeholder="请输入拣货员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拣货时间" prop="pickingTime">
              <el-date-picker clearable
                v-model="form.pickingTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择拣货时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="复核员" prop="checkerId">
              <el-input v-model="form.checkerId" placeholder="请输入复核员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="复核时间" prop="checkTime">
              <el-date-picker clearable
                v-model="form.checkTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择复核时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发货员" prop="deliveryPersonId">
              <el-input v-model="form.deliveryPersonId" placeholder="请输入发货员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发货时间" prop="deliveryTime">
              <el-date-picker clearable
                v-model="form.deliveryTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择发货时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出库策略" prop="outboundStrategy">
              <el-input v-model="form.outboundStrategy" placeholder="请输入出库策略" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 出库单明细 -->
        <el-divider>出库单明细</el-divider>
        <el-row :gutter="20" style="margin-bottom: 10px;">
          <el-col :span="24" style="text-align: right;">
            <el-button type="primary" size="small" icon="Plus" @click="addDetail">添加明细</el-button>
          </el-col>
        </el-row>
        <el-table :data="form.details" border style="width: 100%">
          <el-table-column prop="materialName" label="物资名称" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.materialName" placeholder="请输入物资名称" size="small" disabled />
            </template>
          </el-table-column>
          <el-table-column prop="planQuantity" label="计划数量" width="100">
            <template #default="scope">
              <el-input v-model.number="scope.row.planQuantity" placeholder="请输入计划数量" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="actualQuantity" label="实际数量" width="100">
            <template #default="scope">
              <el-input v-model.number="scope.row.actualQuantity" placeholder="请输入实际数量" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单位" width="80">
            <template #default="scope">
              <el-input v-model="scope.row.unit" placeholder="请输入单位" size="small" disabled />
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="scope">
              <el-input v-model.number="scope.row.unitPrice" placeholder="请输入单价" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" width="100">
            <template #default="scope">
              <el-input v-model.number="scope.row.amount" placeholder="请输入金额" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="batchNo" label="批次号" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.batchNo" placeholder="请输入批次号" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="productionDate" label="生产日期" width="150">
            <template #default="scope">
              <el-date-picker clearable
                v-model="scope.row.productionDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择生产日期"
                size="small">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column prop="expirationDate" label="失效日期" width="150">
            <template #default="scope">
              <el-date-picker clearable
                v-model="scope.row.expirationDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择失效日期"
                size="small">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注">
            <template #default="scope">
              <el-input type="textarea" v-model="scope.row.remark" placeholder="请输入备注" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center" fixed="right">
            <template #default="scope">
              <el-button type="danger" size="small" icon="Delete" @click="deleteDetail(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 物资选择对话框组件 -->
    <MaterialSelectDialog
      ref="materialSelectDialogRef"
      v-model:visible="materialDialogVisible"
      title="选择物资"
      @confirm="handleMaterialConfirm"
    />
    
    <!-- 仓库选择对话框组件 -->
    <WarehouseSelectDialog
      ref="warehouseSelectDialogRef"
      v-model:visible="warehouseDialogVisible"
      title="选择仓库"
      @confirm="handleWarehouseConfirm"
    />
    
    <!-- 客户选择对话框组件 -->
    <CustomerSelectDialog
      ref="customerSelectDialogRef"
      v-model:visible="customerDialogVisible"
      title="选择客户"
      @confirm="handleCustomerConfirm"
    />
  </div>
</template>

<script setup name="WmsOutboundOrder">
import { listWmsOutboundOrder, getWmsOutboundOrder, delWmsOutboundOrder, addWmsOutboundOrder, updateWmsOutboundOrder } from "@/api/ware/wmsOutboundOrder"
import MaterialSelectDialog from "@/components/MaterialSelectDialog.vue"
import WarehouseSelectDialog from "@/components/WarehouseSelectDialog.vue"
import CustomerSelectDialog from "@/components/CustomerSelectDialog.vue"
import { listWmsMaterial } from "@/api/ware/wmsMaterial"

const { proxy } = getCurrentInstance()

const {outbound_type} = proxy.useDict('outbound_type')

const wmsOutboundOrderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 物资选择对话框状态
const materialDialogVisible = ref(false)
// 物资选择对话框实例引用
const materialSelectDialogRef = ref(null)

// 仓库选择对话框状态
const warehouseDialogVisible = ref(false)
// 仓库选择对话框实例引用
const warehouseSelectDialogRef = ref(null)

// 客户选择对话框状态
const customerDialogVisible = ref(false)
// 客户选择对话框实例引用
const customerSelectDialogRef = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    orderType: null,
    warehouseId: null,
    customerId: null,
    relatedOrderNo: null,
    totalQuantity: null,
    totalAmount: null,
    orderStatus: null,
    applicantId: null,
    applyTime: null,
    expectedDeliveryDate: null,
    actualDeliveryDate: null,
    pickingPersonId: null,
    pickingTime: null,
    checkerId: null,
    checkTime: null,
    deliveryPersonId: null,
    deliveryTime: null,
    approvalStatus: null,
    outboundStrategy: null,
  },
  rules: {
    orderNo: [
      { required: true, message: "出库单号不能为空", trigger: "blur" }
    ],
    orderType: [
      { required: true, message: "出库类型不能为空", trigger: "change" }
    ],
    warehouseId: [
      { required: true, message: "仓库ID不能为空", trigger: "blur" }
    ],
  }
})

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

/** 查询出库单主列表 */
function getList() {
  loading.value = true
  listWmsOutboundOrder(queryParams.value).then(response => {
    wmsOutboundOrderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderNo: null,
    orderType: '0',
    warehouseId: null,
    customerId: null,
    relatedOrderNo: null,
    totalQuantity: null,
    totalAmount: null,
    orderStatus: null,
    applicantId: null,
    applyTime: null,
    expectedDeliveryDate: null,
    actualDeliveryDate: null,
    pickingPersonId: null,
    pickingTime: null,
    checkerId: null,
    checkTime: null,
    deliveryPersonId: null,
    deliveryTime: null,
    approvalStatus: null,
    outboundStrategy: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    details: []
  }
  proxy.resetForm("wmsOutboundOrderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加出库单主"
}

/** 打开仓库选择对话框 */
function openWarehouseSelect() {
  warehouseDialogVisible.value = true
  if (warehouseSelectDialogRef.value) {
    warehouseSelectDialogRef.value.handleQuery()
  }
}

/** 处理仓库选择结果 */
function handleWarehouseConfirm(selectedWarehouses) {
  if (selectedWarehouses.length > 0) {
    const warehouse = selectedWarehouses[0]
    form.value.warehouseId = warehouse.warehouseId
    // 可以根据需要添加更多仓库信息字段
  }
}

/** 打开客户选择对话框 */
function openCustomerSelect() {
  customerDialogVisible.value = true
  if (customerSelectDialogRef.value) {
    customerSelectDialogRef.value.handleQuery()
  }
}

/** 处理客户选择结果 */
function handleCustomerConfirm(selectedCustomers) {
  if (selectedCustomers.length > 0) {
    const customer = selectedCustomers[0]
    form.value.customerId = customer.customerId
    // 可以根据需要添加更多客户信息字段
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _orderId = row.orderId || ids.value
  getWmsOutboundOrder(_orderId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改出库单主"
  })
}

/** 提交按钮 */
function submitForm() {
  // 表单基础验证
  proxy.$refs["wmsOutboundOrderRef"].validate(valid => {
    if (valid) {
      // 验证出库单明细
      if (!form.value.details || form.value.details.length === 0) {
        proxy.$modal.msgError("请至少添加一条出库单明细")
        return
      }
      
      // 验证每条明细的必填字段
      for (let i = 0; i < form.value.details.length; i++) {
        const detail = form.value.details[i]
        if (!detail.materialId) {
          proxy.$modal.msgError(`第${i + 1}条明细的物资ID不能为空`)
          return
        }
        if (!detail.planQuantity) {
          proxy.$modal.msgError(`第${i + 1}条明细的计划数量不能为空`)
          return
        }
        // 确保数量为正数
        if (detail.planQuantity <= 0) {
          proxy.$modal.msgError(`第${i + 1}条明细的计划数量必须大于0`)
          return
        }
      }
      
      // 提交数据
      if (form.value.orderId != null) {
        updateWmsOutboundOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addWmsOutboundOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 添加明细 */
function addDetail() {
  if (!form.value.details) {
    form.value.details = []
  }
  // 打开物资选择对话框
  materialDialogVisible.value = true
  // 调用组件方法加载物资分类和列表
  materialSelectDialogRef.value.getTreeselect()
  materialSelectDialogRef.value.handleQuery()
}

/** 处理物资选择确认 */
function handleMaterialConfirm(selectedMaterials) {
  if (selectedMaterials.length === 0) {
    proxy.$modal.msgWarning("请至少选择一个物资")
    return
  }
  
  // 将选中的物资添加到明细列表
  selectedMaterials.forEach(material => {
    form.value.details.push({
      materialId: material.materialId,
      materialName: material.materialName,
      planQuantity: null,
      actualQuantity: null,
      unit: material.unit,
      unitPrice: null,
      amount: null,
      batchNo: null,
      productionDate: null,
      expirationDate: null,
      remark: null
    })
  })
}

/** 删除明细 */
function deleteDetail(index) {
  form.value.details.splice(index, 1)
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value
  proxy.$modal.confirm('是否确认删除出库单主编号为"' + _orderIds + '"的数据项？').then(function() {
    return delWmsOutboundOrder(_orderIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('ware/wmsOutboundOrder/export', {
    ...queryParams.value
  }, `wmsOutboundOrder_${new Date().getTime()}.xlsx`)
}

/** 打印按钮操作 */
function handlePrint(row) {
  // 获取完整的出库单数据，包括明细
  getWmsOutboundOrder(row.orderId).then(response => {
    const orderData = response.data
    // 创建打印窗口
    const printWindow = window.open('', '_blank')
    
    // 构建打印内容
    let printContent = `
      <!DOCTYPE html>
      <html lang="zh-CN">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>出库单打印</title>
        <style>
          body {
            font-family: Arial, sans-serif;
            margin: 20px;
            padding: 20px;
            border: 1px solid #ccc;
          }
          h1 {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
          }
          .order-info {
            margin-bottom: 20px;
            padding: 10px;
            border: 1px solid #eee;
          }
          .info-row {
            display: flex;
            margin-bottom: 10px;
          }
          .info-label {
            width: 120px;
            font-weight: bold;
            margin-right: 10px;
          }
          .table-container {
            margin-top: 20px;
          }
          table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
          }
          th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
          }
          th {
            background-color: #f2f2f2;
          }
          .footer {
            margin-top: 30px;
            text-align: right;
          }
        </style>
      </head>
      <body>
        <h1>出库单</h1>
        <div class="order-info">
          <div class="info-row">
            <span class="info-label">出库单号：</span>
            <span>${orderData.orderNo}</span>
          </div>
          <div class="info-row">
            <span class="info-label">仓库：</span>
            <span>${orderData.warehouseId}</span>
          </div>
          <div class="info-row">
            <span class="info-label">客户：</span>
            <span>${orderData.customerId}</span>
          </div>
          <div class="info-row">
            <span class="info-label">总数量：</span>
            <span>${orderData.totalQuantity}</span>
          </div>
          <div class="info-row">
            <span class="info-label">总金额：</span>
            <span>${orderData.totalAmount}</span>
          </div>
          <div class="info-row">
            <span class="info-label">申请人：</span>
            <span>${orderData.applicantId}</span>
          </div>
          <div class="info-row">
            <span class="info-label">申请时间：</span>
            <span>${orderData.applyTime ? new Date(orderData.applyTime).toLocaleDateString() : ''}</span>
          </div>
          <div class="info-row">
            <span class="info-label">备注：</span>
            <span>${orderData.remark || ''}</span>
          </div>
        </div>
        
        <div class="table-container">
          <h3>出库单明细</h3>
          <table>
            <thead>
              <tr>
                <th>物资名称</th>
                <th>计划数量</th>
                <th>实际数量</th>
                <th>单位</th>
                <th>单价</th>
                <th>金额</th>
                <th>批次号</th>
                <th>生产日期</th>
                <th>失效日期</th>
                <th>备注</th>
              </tr>
            </thead>
            <tbody>
    `
    
    // 添加明细数据
    if (orderData.details && orderData.details.length > 0) {
      orderData.details.forEach(detail => {
        printContent += `
          <tr>
            <td>${detail.materialName}</td>
            <td>${detail.planQuantity}</td>
            <td>${detail.actualQuantity}</td>
            <td>${detail.unit}</td>
            <td>${detail.unitPrice}</td>
            <td>${detail.amount}</td>
            <td>${detail.batchNo || ''}</td>
            <td>${detail.productionDate ? new Date(detail.productionDate).toLocaleDateString() : ''}</td>
            <td>${detail.expirationDate ? new Date(detail.expirationDate).toLocaleDateString() : ''}</td>
            <td>${detail.remark || ''}</td>
          </tr>
        `
      })
    } else {
      printContent += `
        <tr>
          <td colspan="10">无明细数据</td>
        </tr>
      `
    }
    
    // 完成打印内容
    printContent += `
            </tbody>
          </table>
        </div>
        
        <div class="footer">
          <p>打印时间：${new Date().toLocaleString()}</p>
        </div>
      </body>
      </html>
    `
    
    // 写入打印窗口
    printWindow.document.write(printContent)
    printWindow.document.close()
    
    // 执行打印
    printWindow.print()
    
    // 关闭打印窗口
    printWindow.close()
  })
}

getList()
</script>
