<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="90px">
            <el-form-item label="发货单号" prop="shippingCode">
              <el-input v-model="queryParams.shippingCode" placeholder="请输入发货单号" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="发货方式" prop="shippingMode">
              <el-select v-model="queryParams.shippingMode" placeholder="请选择发货方式" clearable style="width: 180px">
                <el-option v-for="dict in shipping_mode" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="发货类型" prop="shippingType">
              <el-select v-model="queryParams.shippingType" placeholder="请选择发货类型" clearable style="width: 180px">
                <el-option v-for="dict in shipping_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目编号" prop="projectCode">
              <el-input v-model="queryParams.projectCode" placeholder="请输入项目编号" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="合同编号" prop="contractCode">
              <el-input v-model="queryParams.contractCode" placeholder="请输入合同编号" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
<!--            <el-form-item label="需到货确认" prop="needArrivalConfirm">-->
<!--              <el-select v-model="queryParams.needArrivalConfirm" placeholder="请选择" clearable style="width: 180px">-->
<!--                <el-option v-for="dict in need_arrival_confirm" :key="dict.value" :label="dict.label" :value="dict.value" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="是否全部到货" prop="isAllReceiving">-->
<!--              <el-select v-model="queryParams.isAllReceiving" placeholder="请选择到货标识" clearable style="width: 180px">-->
<!--                <el-option v-for="dict in is_all_receiving" :key="dict.value" :label="dict.label" :value="dict.value" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="到货确认时间">-->
<!--              <el-date-picker-->
<!--                v-model="arrivalConfirmTimeRange"-->
<!--                type="daterange"-->
<!--                range-separator="至"-->
<!--                start-placeholder="开始时间"-->
<!--                end-placeholder="结束时间"-->
<!--                value-format="YYYY-MM-DD HH:mm:ss"-->
<!--                clearable-->
<!--              />-->
<!--            </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:wmsShippingBill:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-if="!hideBatchEditDeleteButtons"
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate()"
              v-hasPermi="['wms:wmsShippingBill:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-if="!hideBatchEditDeleteButtons"
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['wms:wmsShippingBill:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:wmsShippingBill:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="wmsShippingBillList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="发货单号" align="center" prop="shippingCode" min-width="140" v-if="columns[0].visible" />
        <el-table-column label="SAP订单号" align="center" prop="orderContractCode" min-width="140" show-overflow-tooltip v-if="columns[1].visible" />
        <el-table-column label="发货类型" align="center" prop="shippingType" width="100" v-if="columns[2].visible">
          <template #default="scope">
            <dict-tag :options="shipping_type" :value="scope.row.shippingType" />
          </template>
        </el-table-column>
        <el-table-column label="发货方式" align="center" prop="shippingMode" width="120" v-if="columns[3].visible">
          <template #default="scope">
            <dict-tag :options="shipping_mode" :value="scope.row.shippingMode" />
          </template>
        </el-table-column>
        <el-table-column label="项目名称" align="center" prop="projectName" min-width="160" show-overflow-tooltip v-if="columns[4].visible" />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="140" show-overflow-tooltip v-if="columns[5].visible" />
        <el-table-column label="供应商" align="center" prop="supplier" min-width="120" show-overflow-tooltip v-if="columns[6].visible" />
        <el-table-column label="发货单状态" align="center" prop="outStockBillStatus" width="110" v-if="columns[7].visible">
          <template #default="scope">
            <dict-tag :options="out_stock_bill_status" :value="scope.row.outStockBillStatus" />
          </template>
        </el-table-column>
        <el-table-column label="需到货确认" align="center" prop="needArrivalConfirm" width="100" v-if="columns[8].visible">
          <template #default="scope">
            <dict-tag :options="need_arrival_confirm" :value="scope.row.shippingType === '1' ? '1' : '0'" />
          </template>
        </el-table-column>
        <el-table-column label="到货标识" align="center" prop="isAllReceiving" width="100" v-if="columns[9].visible">
          <template #default="scope">
            <dict-tag :options="is_all_receiving" :value="scope.row.isAllReceiving" />
          </template>
        </el-table-column>
        <el-table-column label="到货确认时间" align="center" prop="arrivalConfirmTime" width="160" v-if="columns[10].visible">
          <template #default="scope">
            <span>{{ proxy?.parseTime(scope.row.arrivalConfirmTime, '{y}-{m}-{d} {h}:{i}:{s}') || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="到货确认人" align="center" prop="arrivalConfirmByName" width="110" show-overflow-tooltip v-if="columns[11].visible" />
        <el-table-column label="收货单附件" align="center" min-width="160" v-if="columns[12].visible">
          <template #default="scope">
            <template v-if="getArrivalReceiptOssIds(scope.row).length > 0">
              <el-button
                v-for="(ossId, index) in getArrivalReceiptOssIds(scope.row)"
                :key="`${scope.row.shippingBillId}-${ossId}`"
                link
                type="primary"
                icon="Download"
                @click="downloadArrivalReceipt(ossId)"
              >
                附件{{ index + 1 }}
              </el-button>
            </template>
            <span v-else style="color: #999">暂无附件</span>
          </template>
        </el-table-column>
        <el-table-column label="计划到货时间" align="center" prop="planArrivalTime" width="110" v-if="columns[13].visible">
          <template #default="scope">
            <span>{{ proxy?.parseTime(scope.row.planArrivalTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际发货时间" align="center" prop="shippingTime" width="110" v-if="columns[14].visible">
          <template #default="scope">
            <span>{{ proxy?.parseTime(scope.row.shippingTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="110" v-if="columns[15].visible">
          <template #default="scope">
            <span>{{ proxy?.parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="220" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip v-if="isEditableFlowStatus(scope.row)" content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wms:wmsShippingBill:edit']"></el-button>
            </el-tooltip>
            <el-tooltip v-if="shouldShowViewButton(scope.row)" content="查看" placement="top">
              <el-button
                link
                type="info"
                icon="DocumentChecked"
                @click="handleView(scope.row)"
                v-hasPermi="['wms:wmsShippingBill:query']"
              ></el-button>
            </el-tooltip>
            <el-tooltip v-if="isEditableFlowStatus(scope.row)" content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wms:wmsShippingBill:remove']"></el-button>
            </el-tooltip>
            <el-tooltip v-if="shouldShowApprovalRecord(scope.row)" content="审批记录" placement="top">
              <el-button link type="warning" icon="Histogram" @click="handleApprovalRecord(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="打印" placement="top">
              <el-button
                link
                type="primary"
                icon="Printer"
                @click="handleExportWord(scope.row)"
                v-hasPermi="['wms:wmsShippingBill:export']"
              ></el-button>
            </el-tooltip>
          </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>
    <ApprovalRecord ref="approvalRecordRef" />
    <!-- 添加或修改发货单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="wmsShippingBillFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="发货单号" prop="shippingCode">
          <el-input v-model="form.shippingCode" placeholder="请输入发货单号" />
        </el-form-item>
        <el-form-item label="发货方式：1公司仓库发货 2供应商代发货" prop="shippingMode">
          <el-input v-model="form.shippingMode" placeholder="请输入发货方式：1公司仓库发货 2供应商代发货" />
        </el-form-item>
        <el-form-item label="项目ID" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目ID" />
        </el-form-item>
        <el-form-item label="项目编号" prop="projectCode">
          <el-input v-model="form.projectCode" placeholder="请输入项目编号" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="客户ID" prop="customerId">
          <el-input v-model="form.customerId" placeholder="请输入客户ID" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="收货地址" prop="shippingAddress">
          <el-input v-model="form.shippingAddress" placeholder="请输入收货地址" />
        </el-form-item>
        <el-form-item label="关联单号" prop="inventoryAmount">
          <el-input v-model="form.inventoryAmount" placeholder="请输入关联单号" />
        </el-form-item>
        <el-form-item label="来源单据ID" prop="sourceBillId">
          <el-input v-model="form.sourceBillId" placeholder="请输入来源单据ID" />
        </el-form-item>
        <el-form-item label="来源单据编号" prop="sourceBillCode">
          <el-input v-model="form.sourceBillCode" placeholder="请输入来源单据编号" />
        </el-form-item>
        <el-form-item label="合同ID" prop="contractId">
          <el-input v-model="form.contractId" placeholder="请输入合同ID" />
        </el-form-item>
        <el-form-item label="合同编号" prop="contractCode">
          <el-input v-model="form.contractCode" placeholder="请输入合同编号" />
        </el-form-item>
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="form.contractName" placeholder="请输入合同名称" />
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="form.supplier" placeholder="请输入供应商" />
        </el-form-item>
        <el-form-item label="供应商ID" prop="supplierId">
          <el-input v-model="form.supplierId" placeholder="请输入供应商ID" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactUser">
          <el-input v-model="form.contactUser" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactNumber">
          <el-input v-model="form.contactNumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="收货联系人" prop="receiverName">
          <el-input v-model="form.receiverName" placeholder="请输入收货联系人" />
        </el-form-item>
        <el-form-item label="收货联系电话" prop="receiverPhone">
          <el-input v-model="form.receiverPhone" placeholder="请输入收货联系电话" />
        </el-form-item>
        <el-form-item label="物流公司" prop="logisticsCompany">
          <el-input v-model="form.logisticsCompany" placeholder="请输入物流公司" />
        </el-form-item>
        <el-form-item label="运单号" prop="trackingNo">
          <el-input v-model="form.trackingNo" placeholder="请输入运单号" />
        </el-form-item>
        <el-form-item label="物流联系电话" prop="logisticsPhone">
          <el-input v-model="form.logisticsPhone" placeholder="请输入物流联系电话" />
        </el-form-item>
        <el-form-item label="发货说明" prop="directions">
          <el-input v-model="form.directions" placeholder="请输入发货说明" />
        </el-form-item>
        <el-form-item label="计划到货时间" prop="planArrivalTime">
          <el-date-picker
            clearable
            v-model="form.planArrivalTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择计划到货时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际发货时间" prop="shippingTime">
          <el-date-picker clearable v-model="form.shippingTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择实际发货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户收货时间" prop="receivedTime">
          <el-date-picker clearable v-model="form.receivedTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择客户收货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="业务完成时间" prop="completedTime">
          <el-date-picker clearable v-model="form.completedTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择业务完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="仓库ID" prop="warehouseId">
          <el-input v-model="form.warehouseId" placeholder="请输入仓库ID" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="WmsShippingBill" lang="ts">
import {
  addWmsShippingBill,
  delWmsShippingBill,
  exportShippingBillWord,
  listWmsShippingBill,
  updateWmsShippingBill
} from '@/api/wms/wmsShippingBill';
import { WmsShippingBillForm, WmsShippingBillQuery, WmsShippingBillVO } from '@/api/wms/wmsShippingBill/types';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 字典定义
const { shipping_mode, shipping_type, need_arrival_confirm, is_all_receiving, out_stock_bill_status } = toRefs<any>(
  proxy?.useDict('shipping_mode', 'shipping_type', 'need_arrival_confirm', 'is_all_receiving', 'out_stock_bill_status')
);

const wmsShippingBillList = ref<WmsShippingBillVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const selectedRows = ref<WmsShippingBillVO[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const wmsShippingBillFormRef = ref<ElFormInstance>();

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

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: '发货单号', visible: true },
  { key: 1, label: 'SAP订单号', visible: false },
  { key: 2, label: '发货类型', visible: true },
  { key: 3, label: '发货方式', visible: true },
  { key: 4, label: '项目名称', visible: false },
  { key: 5, label: '客户名称', visible: true },
  { key: 6, label: '供应商', visible: true },
  { key: 7, label: '发货单状态', visible: true },
  { key: 8, label: '需到货确认', visible: true },
  { key: 9, label: '到货标识', visible: true },
  { key: 10, label: '到货确认时间', visible: true },
  { key: 11, label: '到货确认人', visible: false },
  { key: 12, label: '收货单附件', visible: true },
  { key: 13, label: '计划到货时间', visible: true },
  { key: 14, label: '实际发货时间', visible: true },
  { key: 15, label: '创建时间', visible: false }
]);

const initFormData: WmsShippingBillForm = {
  shippingBillId: undefined,
  shippingCode: undefined,
  shippingType: undefined,
  shippingMode: undefined,
  projectId: undefined,
  projectCode: undefined,
  projectName: undefined,
  customerId: undefined,
  customerName: undefined,
  shippingAddress: undefined,
  inventoryAmount: undefined,
  sourceBillType: undefined,
  sourceBillId: undefined,
  sourceBillCode: undefined,
  contractId: undefined,
  contractCode: undefined,
  contractName: undefined,
  supplier: undefined,
  supplierId: undefined,
  contactUser: undefined,
  contactNumber: undefined,
  receiverName: undefined,
  receiverPhone: undefined,
  logisticsCompany: undefined,
  trackingNo: undefined,
  logisticsPhone: undefined,
  directions: undefined,
  planArrivalTime: undefined,
  shippingTime: undefined,
  receivedTime: undefined,
  completedTime: undefined,
  outStockBillStatus: undefined,
  flowStatus: undefined,
  warehouseId: undefined,
  warehouseName: undefined,
  remark: undefined
};
const data = reactive<PageData<WmsShippingBillForm, WmsShippingBillQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shippingCode: undefined,
    shippingType: undefined,
    shippingMode: undefined,
    projectId: undefined,
    projectCode: undefined,
    projectName: undefined,
    customerId: undefined,
    customerName: undefined,
    shippingAddress: undefined,
    inventoryAmount: undefined,
    sourceBillType: undefined,
    sourceBillId: undefined,
    sourceBillCode: undefined,
    contractId: undefined,
    contractCode: undefined,
    contractName: undefined,
    supplier: undefined,
    supplierId: undefined,
    contactUser: undefined,
    contactNumber: undefined,
    receiverName: undefined,
    receiverPhone: undefined,
    logisticsCompany: undefined,
    trackingNo: undefined,
    logisticsPhone: undefined,
    directions: undefined,
    planArrivalTime: undefined,
    shippingTime: undefined,
    receivedTime: undefined,
    completedTime: undefined,
    outStockBillStatus: undefined,
    flowStatus: undefined,
    needArrivalConfirm: undefined,
    isAllReceiving: undefined,
    warehouseId: undefined,
    warehouseName: undefined,
    params: {}
  },
  rules: {
    shippingBillId: [{ required: true, message: '发货单ID不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const arrivalConfirmTimeRange = ref<string[]>();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

const isEditableFlowStatus = (row?: WmsShippingBillVO) => {
  const flowStatus = String(row?.flowStatus || '').trim();
  return !flowStatus || flowStatus === 'draft' || flowStatus === 'back' || flowStatus === 'cancel';
};

const shouldShowViewButton = (row?: WmsShippingBillVO) => !isEditableFlowStatus(row);

const shouldShowApprovalRecord = (row?: WmsShippingBillVO) => {
  const flowStatus = String(row?.flowStatus || '').trim();
  return !!flowStatus && flowStatus !== 'draft';
};

const getArrivalReceiptOssIds = (row?: WmsShippingBillVO) => {
  const ossIds = String(row?.arrivalReceiptOssId || '')
    .split(',')
    .map((item) => item.trim())
    .filter((item) => item.length > 0);
  return Array.from(new Set(ossIds));
};

const downloadArrivalReceipt = (ossId: string) => {
  proxy?.$download.oss(ossId as any);
};

const hideBatchEditDeleteButtons = computed(() => selectedRows.value.some((item) => !isEditableFlowStatus(item)));

/** 查询发货单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listWmsShippingBill(queryParams.value);
  wmsShippingBillList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  wmsShippingBillFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  if (!queryParams.value.params) {
    queryParams.value.params = {};
  }
  if (arrivalConfirmTimeRange.value && arrivalConfirmTimeRange.value.length === 2) {
    queryParams.value.params.beginArrivalConfirmTime = arrivalConfirmTimeRange.value[0];
    queryParams.value.params.endArrivalConfirmTime = arrivalConfirmTimeRange.value[1];
  } else {
    queryParams.value.params.beginArrivalConfirmTime = undefined;
    queryParams.value.params.endArrivalConfirmTime = undefined;
  }
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  arrivalConfirmTimeRange.value = undefined;
  handleQuery();
};

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

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({ path: '/shipping/wmsShippingBill/edit', query: { type: 'add' } });
};

/** 查看按钮操作 */
const handleView = (row: WmsShippingBillVO) => {
  router.push({ path: '/shipping/wmsShippingBill/edit', query: { type: 'view', id: row.shippingBillId } });
};

/** 审批记录 */
const handleApprovalRecord = (row: WmsShippingBillVO) => {
  // 审批记录只依赖业务单ID，列表页直接打开记录弹窗能减少用户在详情页来回跳转
  approvalRecordRef.value?.init(row.shippingBillId);
};

/** 修改按钮操作 */
const handleUpdate = async (row?: WmsShippingBillVO) => {
  const _shippingBillId = row?.shippingBillId || ids.value[0];
  router.push({ path: '/shipping/wmsShippingBill/edit', query: { type: 'update', id: _shippingBillId } });
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: WmsShippingBillVO) => {
  const _shippingBillIds = row?.shippingBillId || ids.value;
  await proxy?.$modal.confirm('是否确认删除发货单编号为"' + _shippingBillIds + '"的数据项？').finally(() => (loading.value = false));
  await delWmsShippingBill(_shippingBillIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'wms/wmsShippingBill/export',
    {
      ...queryParams.value
    },
    `wmsShippingBill_${new Date().getTime()}.xlsx`
  );
};

/** 导出发货单Word文档 */
const handleExportWord = async (row: WmsShippingBillVO) => {
  try {
    const res = await exportShippingBillWord(row.shippingBillId);
    // 创建Blob对象并下载
    const blob = new Blob([res as any], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `发货单_${row.shippingCode || row.shippingBillId}.docx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    proxy?.$modal.msgSuccess('导出成功');
  } catch (error) {
    proxy?.$modal.msgError('导出失败，请检查模板配置');
  }
};

onMounted(() => {
  getList();
});
</script>
