<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="120px">
            <el-form-item label="采购单号" prop="orderSn">
              <el-input v-model="queryParams.orderSn" placeholder="请输入采购单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="发货日期" prop="sendDate">
              <el-date-picker clearable v-model="queryParams.sendDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择发货日期" />
            </el-form-item>
            <el-form-item label="采购店铺" prop="storeName">
              <el-input v-model="queryParams.storeName" placeholder="请输入采购店铺" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="实际采购店铺" prop="realStoreName">
              <el-input v-model="queryParams.realStoreName" placeholder="请输入实际采购店铺" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="发货状态" prop="sendStatus">
              <el-select v-model="queryParams.sendStatus" placeholder="请选择发货状态" clearable>
                <el-option v-for="dict in send_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </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="['amz:sendOrder:add']">新增 </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['amz:sendOrder:edit']"-->
          <!--              >修改-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['amz:sendOrder:remove']"-->
          <!--              >删除-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['amz:sendOrder:export']"> 导出 </el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="sendOrderList" @selection-change="handleSelectionChange">
        <!--        <el-table-column type="selection" width="55" align="center" />-->

        <el-table-column type="expand">
          <template #default="props">
            <el-card v-if="props.row.bizLogisticsOrder != null" shadow="never">
              <!--              <el-table v-loading="loading" :data="props.row.items" :border="true" size="small" :header-cell-style="{ fontSize: '10px' }">-->
              <!--                <el-table-column label="产品名称" align="center" prop="productName" />-->
              <!--                <el-table-column label="发货数量" align="center" prop="quantitySend" />-->
              <!--                <el-table-column label="单箱产品数量" align="center" prop="quantityPerBox" />-->
              <!--              </el-table>-->
              <el-descriptions size="small" border title="物流订单详情">
                <el-descriptions-item label="物流订单号">{{ props.row.bizLogisticsOrder.orderId }} </el-descriptions-item>

                <el-descriptions-item label="渠道名称">{{ props.row.bizLogisticsOrder.channelName }} </el-descriptions-item>
                <el-descriptions-item label="目的地">{{ props.row.bizLogisticsOrder.destination }} </el-descriptions-item>
                <el-descriptions-item label="订单状态">
                  <dict-tag :options="logic_order_status" :value="props.row.bizLogisticsOrder.status" />
                </el-descriptions-item>
                <el-descriptions-item label="物流商名称">{{ props.row.logisticsProviderName }}</el-descriptions-item>
                <el-descriptions-item label="物流商地址">{{ props.row.address || '暂无地址' }}</el-descriptions-item>
                <el-descriptions-item label="物流明细">
                  <el-button link type="primary" size="small" @click="openDetailDialog(props.row.bizLogisticsOrder.details)"> 查看详情 </el-button>
                </el-descriptions-item>

                <!--                <el-descriptions-item label="入库计划ID">{{ props.row.staInboundPlanId }}</el-descriptions-item>-->

                <!--                <el-descriptions-item label="创建时间">{{ parseTime(props.row.gmtCreate, '{y}-{m}-{d}') }} </el-descriptions-item>-->
                <!--                <el-descriptions-item label="物流商">{{ props.row.bizLogisticsOrder.logisticsProviderName }} </el-descriptions-item>-->
                <!--              <el-descriptions-item label="预计到货开始日">{{ parseTime(props.row.staDeliveryStartDate, '{y}-{m}-{d}') }} </el-descriptions-item>-->
                <!--              <el-descriptions-item label="预计到货截止日">{{ parseTime(props.row.staDeliveryEndDate, '{y}-{m}-{d}') }} </el-descriptions-item>-->
              </el-descriptions>
            </el-card>
            <el-card v-else>
              <el-card shadow="never"> 暂无物流信息</el-card>
            </el-card>
          </template>
        </el-table-column>
        <el-table-column label="发货单号" align="center" prop="id" />
        <el-table-column label="采购单号" align="center" prop="orderSn" />
        <el-table-column label="创建日期" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发货日期" align="center" prop="sendDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.sendDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="采购店铺" align="center" prop="storeName" />
        <el-table-column label="供应商名称" align="center" prop="sendName" />
        <!--        <el-table-column label="物流商名称" align="center" prop="logisticsProviderName">-->
        <!--          <template #default="{ row }">-->
        <!--            <el-popover placement="top" title="物流商地址" :width="200" trigger="click">-->
        <!--              <template #reference>-->
        <!--                <el-button v-if="row.logisticsProviderName !== null" text size="small" type="primary">-->
        <!--                  {{ row.logisticsProviderName }}-->
        <!--                </el-button>-->
        <!--              </template>-->
        <!--              <div>{{ row.address || '暂无地址' }}</div>-->
        <!--            </el-popover>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="发货数量" align="center" prop="quantitySend" />
        <!--        <el-table-column label="单箱产品数量" align="center" prop="quantityPerBox" />-->
        <el-table-column label="箱数" align="center" prop="boxCount">
          <template #default="{ row }">
            <el-popover placement="top" title="装箱明细" :width="500" trigger="click">
              <template #reference>
                <el-button text size="small" type="primary"> {{ row.boxCount }}箱</el-button>
              </template>
              <div v-if="row.sendDetail !== null" v-html="formatText(row.sendDetail)"></div>
              <div v-else>暂无数据</div>
            </el-popover>
          </template>
        </el-table-column>
        <!--        <el-table-column label="箱子尺寸" align="center" prop="boxDimensions" />-->
        <el-table-column label="总重量" align="center" prop="weightPerBox" />
        <el-table-column label="实际发货店铺" align="center" prop="realStoreName" />
        <el-table-column label="发货状态" align="center" prop="sendStatus">
          <template #default="scope">
            <dict-tag :options="send_status" :value="scope.row.sendStatus" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
        <!--          <template #default="scope">-->
        <!--            <el-tooltip content="修改" placement="top" v-if="scope.row.sendStatus === 'pending'">-->
        <!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['amz:sendOrder:edit']"></el-button>-->
        <!--            </el-tooltip>-->
        <!--            <el-tooltip content="删除" placement="top">-->
        <!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['amz:sendOrder:remove']"></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>
    <!-- 添加或修改供应商创建的发货单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1000px" append-to-body>
      <el-form ref="sendOrderFormRef" :model="form" :rules="rules" label-width="120px">
        <!--        <el-form-item label="主键ID" prop="id">-->
        <!--          <el-input v-model="form.id" placeholder="请输入主键ID" />-->
        <!--        </el-form-item>-->
        <el-form-item label="采购单号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入采购单号" @blur="blurAction" />
        </el-form-item>
        <!--        <el-form-item label="发货日期" prop="sendDate">-->
        <!--          <el-date-picker clearable v-model="form.sendDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发货日期">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="采购店铺" prop="storeName">-->
        <!--          <el-input v-model="form.storeName" placeholder="请输入采购店铺" />-->
        <!--        </el-form-item>-->
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="发货总数" prop="quantitySend">
          <el-input v-model="form.quantitySend" placeholder="请输入发货数量" />
        </el-form-item>

        <el-form-item label="总箱数" prop="boxCount">
          <el-input v-model="form.boxCount" placeholder="请输入总箱数" />
        </el-form-item>
        <el-form-item v-if="form.quantitySend > 0 && form.boxCount > 0" label="箱子明细" prop="quantityPerBox">
          <div class="max-w-800px">
            <div v-for="(group, index) in groups" :key="index" class="flex gap-12px mb-16px items-center">
              <el-input
                v-model.number="groups[index].boxCount"
                placeholder="箱子数量"
                type="number"
                min="0"
                class="flex-1"
                @input="validateInput(index, 'boxCount')"
              />
              X
              <el-input
                v-model.number="groups[index].itemCount"
                placeholder="每箱个数"
                type="number"
                min="0"
                class="flex-1"
                @input="validateInput(index, 'itemCount')"
              />
              <el-input v-model.number="groups[index].lengthPerBox" placeholder="长(cm)" type="number" min="0" class="flex-1" />
              <el-input v-model.number="groups[index].widthPerBox" placeholder="宽(cm)" type="number" min="0" class="flex-1" />
              <el-input v-model.number="groups[index].heightPerBox" placeholder="高(cm)" type="number" min="0" class="flex-1" />
              <el-input v-model.number="groups[index].weightPerBox" placeholder="单箱重量(kg)" type="number" min="0" class="flex-1" />
              <el-button v-if="index > 0" @click="removeGroup(index)" type="danger" :icon="Close" circle size="small" />
              <div v-else class="w-8 h-8"></div>
            </div>

            <div class="mb-16px text-left">
              <span :class="['mr-8px', Number(totalNum) === Number(shipForm.quantitySend) ? 'text-green-500' : 'text-red-500']">
                当前总量：{{ totalNum }}/{{ form.quantitySend }}
              </span>
              <el-button @click="addGroup" type="primary" :icon="Plus" :disabled="totalNum >= form.quantitySend"> 添加一组 </el-button>
            </div>
          </div>
        </el-form-item>
        <!--        <el-form-item label="箱子尺寸" prop="boxDimensions">-->
        <!--          <el-input v-model="form.boxDimensions" placeholder="请输入箱子尺寸" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="箱子尺寸" prop="boxDimensions">-->
        <!--          <el-row>-->
        <!--            <el-col :span="8">-->
        <!--              <el-input v-model="plength" placeholder="请输入长" />-->
        <!--            </el-col>-->
        <!--            <el-col :span="8">-->
        <!--              <el-input v-model="pwidth" placeholder="请输入宽" />-->
        <!--            </el-col>-->
        <!--            <el-col :span="8">-->
        <!--              <el-input v-model="pheight" placeholder="请输入高" />-->
        <!--            </el-col>-->
        <!--          </el-row>-->
        <!--        </el-form-item>-->
        <el-form-item label="总重量" prop="weightPerBox">
          <!--          <el-input v-model="totalWeight" placeholder="请输入总重量" disabled />-->
          <el-input-number v-model="totalWeight" :min="0" :max="100000" disabled>
            <template #suffix>
              <span>kg</span>
            </template>
          </el-input-number>
        </el-form-item>
        <!--        <el-form-item label="实际采购店铺" prop="realStoreName">-->
        <!--          <el-input v-model="form.realStoreName" placeholder="请输入实际采购店铺" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="发货状态" prop="sendStatus">-->
        <!--          <el-select v-model="form.sendStatus" placeholder="请选择发货状态">-->
        <!--            <el-option v-for="dict in send_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>-->
        <!--          </el-select>-->
        <!--        </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>

    <el-dialog v-model="detailDialogVisible" title="货件明细" width="60%">
      <el-table :data="detailTableData">
        <el-table-column label="FBA货件编号" align="center" prop="fbaShipmentId" />
        <el-table-column label="FBA箱号" align="center" prop="fbaBoxNumber" />
        <el-table-column label="物流商名称" align="center" prop="logisticsProviderName" />
        <el-table-column label="物流渠道" align="center" prop="channelName" />
        <el-table-column label="预计到达时间" align="center" prop="estimatedDeliveryDate" />

        <!--        <el-table-column label="物流称重" align="center" prop="logisticsWeight">-->
        <!--          <template #default="scope">-->
        <!--            {{ scope.row.logisticsWeight != null ? `${scope.row.logisticsWeight} kg` : '' }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="物流追踪号" align="center" prop="trackingNumber">
          <template #default="scope">
            <el-link type="success" :href="`https://t.17track.net/zh-cn#nums=${scope.row.trackingNumber}`" target="_blank">
              {{ scope.row.trackingNumber }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column label="物流状态" align="center" prop="logisticsStatus">
          <template #default="scope">
            <dict-tag :options="biz_logistics_status" :value="scope.row.logisticsStatus" />
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="SendOrder" lang="ts">
import { listSendOrder, getSendOrder, delSendOrder, addSendOrder, updateSendOrder } from '@/api/amz/sendOrder';
import { SendOrderVO, SendOrderQuery, SendOrderForm } from '@/api/amz/sendOrder/types';
import { getPurchaseOrder } from '@/api/amz/purchaseOrder';
import { Close, Plus } from '@element-plus/icons-vue';
import { ElTable } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { send_status } = toRefs<any>(proxy?.useDict('send_status'));
const { logic_order_status } = toRefs<any>(proxy?.useDict('logic_order_status'));

const { biz_logistics_status } = toRefs<any>(proxy?.useDict('biz_logistics_status'));

const detailDialogVisible = ref(false);

const detailTableData = ref([]);
const sendOrderList = ref<SendOrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const plength = ref<string | number>();
const pheight = ref<string | number>();
const pwidth = ref<string | number>();

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

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

const initFormData: SendOrderForm = {
  id: undefined,
  orderSn: undefined,
  sendDate: undefined,
  storeName: undefined,
  productName: undefined,
  quantitySend: 0,
  quantityPerBox: undefined,
  boxCount: undefined,
  boxDimensions: undefined,
  weightPerBox: undefined,
  realStoreName: undefined,
  sendStatus: undefined,
  sendDetail: undefined
};
const data = reactive<PageData<SendOrderForm, SendOrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderSn: undefined,
    sendDate: undefined,
    storeName: undefined,
    productName: undefined,
    quantitySend: undefined,
    quantityPerBox: undefined,
    boxCount: undefined,
    boxDimensions: undefined,
    weightPerBox: undefined,
    realStoreName: undefined,
    sendStatus: undefined,
    params: {}
  },
  rules: {
    orderSn: [{ required: true, message: '采购单号不能为空', trigger: 'blur' }],
    // sendDate: [{ required: true, message: '发货日期不能为空', trigger: 'blur' }],
    storeName: [{ required: true, message: '采购店铺不能为空', trigger: 'blur' }],
    productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
    quantitySend: [{ required: true, message: '发货数量不能为空', trigger: 'blur' }],
    quantityPerBox: [
      {
        validator: (rule, value, callback) => {
          if (totalBoxCount.value != form.value.boxCount) {
            console.log('totalBoxCount.value', totalBoxCount.value);
            console.log('form.value.boxCount', form.value.boxCount);
            callback(new Error('明细箱数和总箱数不匹配，请调整'));
          }
          // 总量提示
          if (totalNum.value > form.value.quantitySend) {
            const exceed = totalNum.value - form.value.quantitySend;
            callback(new Error('总量超出 ' + exceed + '，请调整'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    boxCount: [{ required: true, message: '箱数不能为空', trigger: 'blur' }],
    // boxDimensions: [
    //   {
    //     required: true,
    //     message: '长宽高都不能为空',
    //     validator: (rule, value, callback) => {
    //       if (!plength.value || !pwidth.value || !pheight.value) {
    //         callback(new Error('长宽高都不能为空'));
    //       } else {
    //         callback();
    //       }
    //     },
    //     trigger: 'blur'
    //   }
    // ],
    weightPerBox: [{ required: true, message: '单箱重量不能为空', trigger: 'blur' }],
    realStoreName: [{ required: true, message: '实际采购店铺不能为空', trigger: 'blur' }],
    sendStatus: [{ required: true, message: '发货状态不能为空', trigger: 'change' }]
  }
});

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

const groups = ref([
  {
    boxCount: null,
    itemCount: null,
    lengthPerBox: null,
    widthPerBox: null,
    heightPerBox: null,
    weightPerBox: null
  }
]);

// 计算所有输入值的总和
const totalNum = computed(() => {
  return groups.value.reduce((sum, group) => {
    const box = Number(group.boxCount) || 0;
    const item = Number(group.itemCount) || 0;
    return sum + box * item;
  }, 0);
});

// 计算所有输入值的总和
const totalBoxCount = computed(() => {
  return groups.value.reduce((sum, group) => {
    const box = Number(group.boxCount) || 0;
    return sum + box;
  }, 0);
});

const totalWeight = computed(() => {
  return groups.value.reduce((sum, group) => {
    const box = Number(group.boxCount) || 0;
    return sum + box * group.weightPerBox;
  }, 0);
});

// 输入验证
const validateInput = (index, field) => {
  const value = groups.value[index][field];

  // 非数字或负数处理
  if (isNaN(value) || value < 0) {
    ElMessage.warning('请输入有效的非负数');
    groups.value[index][field] = null;
    return false;
  }

  // // 总量提示
  // if (totalNum.value > form.value.quantitySend) {
  //   const exceed = totalNum.value - form.value.quantitySend;
  //   ElMessage.warning(`总量超出 ${exceed}，请调整`);
  // }

  return true;
};

const openDetailDialog = (detail) => {
  detailTableData.value = detail;
  detailDialogVisible.value = true;
};

// 添加新组
const addGroup = () => {
  if (totalNum.value >= form.value.quantitySend) {
    ElMessage.error(`当前总量已达${form.value.quantitySend}，无法继续添加`);
    return;
  }

  groups.value.push({
    boxCount: null,
    itemCount: null,
    lengthPerBox: null,
    widthPerBox: null,
    heightPerBox: null,
    weightPerBox: null
  });
};

const formatText = (text) => {
  if (text === null) {
    return '';
  }
  return text.replace(/\n/g, '<br>');
};

// 删除组
const removeGroup = (index) => {
  groups.value.splice(index, 1);
  if (totalNum.value > form.value.quantitySend) {
    ElMessage.warning('请调整剩余数值使总量不超过100');
  }
};
/** 查询供应商创建的发货单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSendOrder(queryParams.value);
  sendOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

const blurAction = async () => {
  if (!isPOFormat(form.value.orderSn)) {
    return;
  }

  const res = await getPurchaseOrder(form.value.orderSn);
  Object.assign(form.value, res.data);
  form.value.quantitySend = res.data.quantityReal;
  console.log('res', res);
};

const isPOFormat = (input: string): boolean => {
  const poRegex = /^PO\d+$/;
  return poRegex.test(input);
};

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加供应商创建的发货单';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SendOrderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getSendOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改供应商创建的发货单';
};

/** 提交按钮 */
const submitForm = () => {
  form.value.weightPerBox = totalWeight.value;
  form.value.boxDimensions = `${pwidth.value} x ${pheight.value} x ${plength.value}`;
  const sendText = groups.value.reduce((sum, group, index) => {
    return (
      sum +
      '规格' +
      numberToLetter(index) +
      ': ' +
      group.boxCount +
      '箱' +
      group.itemCount +
      '件，长' +
      group.lengthPerBox +
      'cm宽' +
      group.widthPerBox +
      'cm高' +
      group.heightPerBox +
      'cm，' +
      '单箱重量' +
      group.weightPerBox +
      'kg' +
      '\n'
    );
  }, '');
  console.log('sendText: ', sendText);
  form.value.sendDetail = sendText;
  sendOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateSendOrder(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addSendOrder(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

function numberToLetter(num: number): string {
  if (num < 0 || num > 25) throw new Error('数字需在 0-25 范围内');
  return String.fromCharCode(num + 65);
}

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

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

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