<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">
            <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="customOrderSn">
              <el-input v-model="queryParams.storeName" placeholder="请输入店铺名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="订单状态" prop="orderStatus">-->
            <!--              <el-select multiple collapse-tags collapse-tags-tooltip v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>-->
            <!--                <el-option v-for="dict in vendor_order_status" :key="dict.value" :label="dict.label" :value="dict.value" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <el-form-item label="供应商" prop="supplierName">
              <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="SKU" prop="customOrderSn">
              <el-input v-model="queryParams.sku" placeholder="请输入sku" 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-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:purchaseOrder:add']">新增 </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['amz:purchaseOrder:edit']"-->
          <!--              >修改-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['amz:purchaseOrder:remove']"-->
          <!--              >删除-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['amz:purchaseOrder:export']">导出 </el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="purchaseOrderList" @selection-change="handleSelectionChange">
        <el-table-column type="expand">
          <template #default="props">
            <el-card shadow="never">
              <!--              <template #header>-->
              <!--                <div class="card-header">-->
              <!--                  <span>产品明细</span>-->
              <!--                </div>-->
              <!--              </template>-->

              <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="orderSn" />-->
                <!--              <el-table-column label="仓库ID" align="center" prop="wid" />-->
                <el-table-column label="仓库名称" align="center" prop="wareHouseName" width="70px" />
                <!--              <el-table-column label="采购计划号" align="center" prop="planSn" />-->
                <!--              <el-table-column label="本地产品ID" align="center" prop="productId" />-->
                <el-table-column label="品名" align="center" prop="productName" width="200px" />
                <el-table-column label="SKU" align="center" prop="sku" width="200px" />
                <!--                <el-table-column label="FNSKU" align="center" prop="fnsku" width="90px" />-->
                <!--                <el-table-column label="店铺ID" align="center" prop="sid" width="70px" />-->
                <!--              <el-table-column label="型号" align="center" prop="model" />-->
                <el-table-column label="含税单价" align="center" prop="price" />
                <!--              <el-table-column label="价税合计" align="center" prop="amount" />-->
                <!--              <el-table-column label="计划采购量" align="center" prop="quantityPlan" />-->

                <!--                <el-table-column label="实际采购量" align="center" prop="quantityReal" width="90px" />-->
                <!--                <el-table-column label="已下单数量" align="center" prop="quantityShipped" />-->
                <!--                <el-table-column label="剩余数量" align="center" prop="quantityLeft" />-->
                <!--                <el-table-column label="转发数量" align="center" prop="quantityForward" />-->
                <!--                <el-table-column label="半成品可发货数量" align="center" prop="sfgAvlQty" width="100px" />-->

                <!--              <el-table-column label="到货入库量" align="center" prop="quantityEntry" />-->
                <!--              <el-table-column label="待到货量" align="center" prop="quantityReceive" />-->
                <!--              <el-table-column label="退货数" align="center" prop="quantityReturn" />-->
                <!--              <el-table-column label="换货量" align="center" prop="quantityExchange" />-->
                <!--              <el-table-column label="质检量" align="center" prop="quantityQc" />-->
                <!--              <el-table-column label="待质检量" align="center" prop="quantityQcPrepare" />-->
                <!--              <el-table-column label="期待到货时间" align="center" prop="expectArriveTime" width="180">-->
                <!--                <template #default="scope">-->
                <!--                  <span>{{ parseTime(scope.row.expectArriveTime, '{y}-{m}-{d}') }}</span>-->
                <!--                </template>-->
                <!--              </el-table-column>-->
                <el-table-column label="备注" align="center" prop="remark" />
                <el-table-column label="当前订单状态" align="center" prop="orderStatus">
                  <template #default="scope">
                    <dict-tag :options="vendor_order_status" :value="scope.row.orderStatus" />
                  </template>
                </el-table-column>
                <el-table-column label="订单状态时间线" align="center" prop="casesNum" width="200px">
                  <template #default="scope">
                    <el-timeline style="max-width: 600px; margin-top: 25px">
                      <el-timeline-item
                        v-for="(activity, index) in scope.row.sysStatusHistories"
                        :key="index"
                        :type="'success'"
                        :timestamp="activity.originalChangedAt"
                      >
                        <dict-tag :options="vendor_order_status" :value="activity.newStatus" />
                      </el-timeline-item>
                    </el-timeline>
                  </template>
                </el-table-column>
                <!--                <el-table-column label="是否有半成品转发" align="center" prop="hasForward">-->
                <!--                  <template #default="scope">-->
                <!--                    <dict-tag :options="sys_yes_no" :value="scope.row.hasForward" />-->
                <!--                  </template>-->
                <!--                </el-table-column>-->
                <!--                <el-table-column label="是否有成品发货" align="center" prop="hasSendOrder">-->
                <!--                  <template #default="scope">-->
                <!--                    <dict-tag :options="sys_yes_no" :value="scope.row.hasSendOrder" />-->
                <!--                  </template>-->
                <!--                </el-table-column>-->
                <!--              <el-table-column label="单箱数量" align="center" prop="quantityPerCase" />-->
                <!--              <el-table-column label="是否删除：0 否，1 是" align="center" prop="isDelete" />-->
                <!--              <el-table-column label="税率" align="center" prop="taxRate" />-->
                <!--              <el-table-column label="SPU" align="center" prop="spu" />-->
                <!--              <el-table-column label="款名" align="center" prop="spuName" />-->
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template #default="scope">
                    <!--                    <el-button-->
                    <!--                      size="small"-->
                    <!--                      link-->
                    <!--                      type="primary"-->
                    <!--                      @click="handleForward(scope.row, props.row)"-->
                    <!--                      v-hasRoles="['superadmin', 'gengdan']"-->
                    <!--                      v-hasPermi="['amz:purchaseOrder:remove']"-->
                    <!--                      v-if="props.row.type == 'com'"-->
                    <!--                    >-->
                    <!--                      半成品转发-->
                    <!--                    </el-button>-->
                    <!--                    <el-button-->
                    <!--                      size="small"-->
                    <!--                      link-->
                    <!--                      type="primary"-->
                    <!--                      @click="handleDetail(scope.row, props.row)"-->
                    <!--                      v-hasRoles="['superadmin', 'gongying']"-->
                    <!--                      v-hasPermi="['amz:purchaseOrder:remove']"-->
                    <!--                    >-->
                    <!--                      编辑-->
                    <!--                    </el-button>-->
                    <el-button
                      size="small"
                      link
                      type="primary"
                      @click="handleShip(scope.row, props.row)"
                      v-hasRoles="['superadmin', 'gengdan']"
                      v-hasPermi="['amz:purchaseOrder:remove']"
                      v-if="props.row.type == 'ord'"
                    >
                      成品发货
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </template>
        </el-table-column>
        <!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="采购单号" align="center" prop="orderSn" />

        <el-table-column label="订单类型" align="center" prop="sendStatus">
          <template #default="scope">
            <dict-tag :options="pur_order_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="自定义单号" align="center" prop="customOrderSn" />-->
        <!--        <el-table-column label="供应商ID" align="center" prop="supplierId" />-->
        <el-table-column label="供应商名称" align="center" prop="supplierName" />
        <el-table-column label="店铺名称" align="center" prop="storeName" />
        <el-table-column width="150" label="转发详情" align="center">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openDetailDialog(row.forwardList)"> 查看详情</el-button>
          </template>
        </el-table-column>
        <!--        <el-table-column label="采购员ID" align="center" prop="optUid" />-->
        <!--        <el-table-column label="审核人姓名" align="center" prop="auditorRealname" />-->
        <!--        <el-table-column label="操作人姓名" align="center" prop="optRealname" />-->
        <!--        <el-table-column label="最后操作人姓名" align="center" prop="lastRealname" />-->
        <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="应付货款" align="center" prop="payment" />-->
        <!--        <el-table-column label="审核人员ID" align="center" prop="auditorUid" />-->
        <!--        <el-table-column label="审核时间" align="center" prop="auditorTime" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ parseTime(scope.row.auditorTime, '{y}-{m}-{d}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="最后操作人员ID" align="center" prop="lastUid" />-->
        <!--        <el-table-column label="最后操作时间" align="center" prop="lastTime" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ parseTime(scope.row.lastTime, '{y}-{m}-{d}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="作废原因" align="center" prop="reason" />-->
        <!--        <el-table-column label="是否含税" align="center" prop="isTax" />-->
        <!--        <el-table-column label="采购单状态" align="center" prop="status" />-->
        <!--        <el-table-column label="状态说明" align="center" prop="statusText" />-->
        <!--        <el-table-column label="支付状态说明" align="center" prop="payStatusText" />-->
        <!--        <el-table-column label="到货状态" align="center" prop="statusShipped" />-->
        <!--        <el-table-column label="到货状态说明" align="center" prop="statusShippedText" />-->
        <!--        <el-table-column label="货物总价" align="center" prop="amountTotal" />-->
        <el-table-column label="总金额" align="center" prop="totalPrice" />
        <!--        <el-table-column label="币种符号" align="center" prop="icon" />-->
        <!--        <el-table-column label="付款状态" align="center" prop="payStatus" />-->

        <!--        <el-table-column label="其他费用" align="center" prop="otherFee" />-->
        <!--        <el-table-column label="其他费用币种" align="center" prop="otherCurrency" />-->
        <!--        <el-table-column label="费用分摊方式" align="center" prop="feePartType" />-->
        <!--        <el-table-column label="运费" align="center" prop="shippingPrice" />-->
        <!--        <el-table-column label="运费币种" align="center" prop="shippingCurrency" />-->
        <!--        <el-table-column label="采购币种" align="center" prop="purchaseCurrency" />-->
        <!--        <el-table-column label="采购汇率" align="center" prop="purchaseRate" />-->
        <!--        <el-table-column label="采购总量" align="center" prop="quantityTotal" />-->
        <!--        <el-table-column label="仓库ID" align="center" prop="wid" />-->
        <!--        <el-table-column label="仓库名称" align="center" prop="wareHouseName" />-->
        <!--        <el-table-column label="仓库名(备份)" align="center" prop="wareHouseBakName" />-->
        <!--        <el-table-column label="入库量" align="center" prop="quantityEntry" />-->
        <el-table-column label="实际采购量" align="center" prop="quantityReal" />
        <el-table-column label="剩余未交货" align="center" prop="remainingQuantity" width="90px" />

        <!--        <el-table-column label="待到货量" align="center" prop="quantityReceive" />-->
        <!--        <el-table-column label="采购方ID" align="center" prop="purchaserId" />-->
        <!--        <el-table-column label="联系人" align="center" prop="contactPerson" />-->
        <!--        <el-table-column label="联系方式" align="center" prop="contactNumber" />-->
        <!--        <el-table-column label="结算方式" align="center" prop="settlementMethod" />-->
        <!--        <el-table-column label="结算描述" align="center" prop="settlementDescription" />-->
        <!--        <el-table-column label="订单变动日期" align="center" prop="divTime" width="280px">-->
        <!--          <template #default="scope">-->
        <!--            <el-date-picker clearable v-model="scope.row.divTime" type="date" value-format="YYYY-MM-DD" placeholder="该订单没有延期" />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="采购单是否延期" align="center" prop="divTime" width="280px">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.divTime == null">采购单未延期</el-tag>
            <el-tag type="danger" v-else>已延期至:{{ parseTime(scope.row.divTime, '{y}-{m}-{d}') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="交货天数" align="center" prop="estDlvDays" />
        <!--        <el-table-column label="订单状态" align="center" prop="orderStatus">-->
        <!--          <template #default="scope">-->
        <!--            <dict-tag :options="vendor_order_status" :value="scope.row.orderStatus" />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <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="dlvTimeVar" />-->
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-hasRoles="['superadmin', 'gengdan', 'gongying']">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleUpdate(scope.row)" v-hasPermi="['amz:purchaseOrder:edit']">设置延期 </el-button>

            <!--            <el-button size="small" link type="primary" @click="handleConfirm(scope.row)" v-hasPermi="['amz:purchaseOrder:remove']"> 确认 </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-card>
    <!-- 添加或修改采购单主对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="purchaseOrderFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="采购单号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入采购单号" disabled />
        </el-form-item>
        <el-form-item label="交货天数" prop="estDlvDays">
          <!--          <el-input v-model="form.estDlvDays" placeholder="请输入交货天数" />-->
          <el-input-number v-model="form.estDlvDays" :min="0" :max="100" @change="delevAction()" disabled>
            <template #suffix>
              <span>天</span>
            </template>
          </el-input-number>
        </el-form-item>
        <!--        <el-form-item label="订单状态" prop="orderStatus">-->
        <!--          <el-select v-model="form.orderStatus" placeholder="请选择订单状态">-->
        <!--            <div v-for="dict in vendor_order_status" :key="dict.value">-->
        <!--              <el-option-->
        <!--                v-if="-->
        <!--                  dict.value == 'ord_confirmed' ||-->
        <!--                  dict.value == 'material_preparing' ||-->
        <!--                  dict.value == 'production_started' ||-->
        <!--                  dict.value == 'labeling_packaging'-->
        <!--                "-->
        <!--                :label="dict.label"-->
        <!--                :value="dict.value"-->
        <!--              ></el-option>-->
        <!--            </div>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="交货时间" prop="deliveryTime">
          <el-date-picker
            clearable
            v-model="form.deliveryTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择交货时间"
            disabled
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否延期" prop="divTime">
          <el-date-picker clearable v-model="form.divTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" 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>
    <el-dialog :title="detaildialog.title" v-model="detaildialog.visible" width="1000px" append-to-body>
      <el-form ref="purchaseOrderFormRef" :model="detailForm" label-width="160px">
        <el-form-item label="采购单号" prop="orderSn">
          <el-input v-model="detailForm.orderSn" placeholder="请输入采购单号" disabled />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="detailForm.productName" placeholder="请输入产品名称" disabled />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="detailForm.remark" placeholder="备注" disabled />
        </el-form-item>
        <el-form-item label="实际采购量" prop="quantityReal">
          <el-input v-model="detailForm.quantityReal" placeholder="实际采购量" disabled />
        </el-form-item>
        <!--        <el-form-item label="半成品可发货数量" prop="sfgAvlQty">-->
        <!--          &lt;!&ndash;          <el-input v-model="detailForm.sfgAvlQty" placeholder="请输入半成品可发货数量" />&ndash;&gt;-->
        <!--          <el-input-number v-model="detailForm.sfgAvlQty" :min="0" :max="detailForm.quantityReal">-->
        <!--            <template #suffix>-->
        <!--              <span>件</span>-->
        <!--            </template>-->
        <!--          </el-input-number>-->
        <!--        </el-form-item>-->

        <!--        <el-form-item label="交货天数" prop="estDlvDays">-->
        <!--          &lt;!&ndash;          <el-input v-model="form.estDlvDays" placeholder="请输入交货天数" />&ndash;&gt;-->
        <!--          <el-input-number v-model="detailForm.estDlvDays" :min="0" :max="100" @change="delevAction()" disabled>-->
        <!--            <template #suffix>-->
        <!--              <span>天</span>-->
        <!--            </template>-->
        <!--          </el-input-number>-->
        <!--        </el-form-item>-->
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="detailForm.orderStatus" placeholder="请选择订单状态">
            <div v-for="dict in vendor_order_status" :key="dict.value">
              <el-option
                v-if="
                  dict.value == 'ord_confirmed' ||
                  dict.value == 'material_preparing' ||
                  dict.value == 'production_started' ||
                  dict.value == 'labeling_packaging' ||
                  dict.value == 'order_prod_completed'
                "
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </div>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="交货时间" prop="deliveryTime">-->
        <!--          <el-date-picker-->
        <!--            clearable-->
        <!--            v-model="form.deliveryTime"-->
        <!--            type="datetime"-->
        <!--            value-format="YYYY-MM-DD HH:mm:ss"-->
        <!--            placeholder="请选择交货时间"-->
        <!--            disabled-->
        <!--          >-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="是否延期" prop="divTime">-->
        <!--          <el-date-picker clearable v-model="form.divTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="未延期" />-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitDetailForm">确 定</el-button>
          <el-button @click="detaildialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="forwardDialog.title" v-model="forwardDialog.visible" width="800px" append-to-body>
      <el-form ref="shipForwardFormRef" :model="forwardForm" :rules="rules2" label-width="130px">
        <el-form-item label="采购单号" prop="orderSn">
          <el-input v-model="forwardForm.orderSn" placeholder="请输入采购单号" disabled />
        </el-form-item>
        <el-form-item label="店铺名称" prop="storeName">
          <el-input v-model="forwardForm.storeName" placeholder="请输入采购店铺名称" disabled />
        </el-form-item>
        <el-form-item label="SKU" prop="sku">
          <el-input v-model="forwardForm.sku" placeholder="请输入产品唯一标识码" disabled />
        </el-form-item>
        <el-form-item label="产品全称" prop="productName">
          <el-input v-model="forwardForm.productName" placeholder="请输入产品全称" disabled />
        </el-form-item>
        <!--        <el-form-item label="半成品可发货数量" prop="sfgAvlQty">-->
        <!--          <el-input v-model="forwardForm.sfgAvlQty" placeholder="请输入半成品可发货数量" disabled />-->
        <!--        </el-form-item>-->
        <el-form-item label="发货数量" prop="quantitySend">
          <el-input-number v-model="forwardForm.quantitySend" :min="1" :max="maxQuality">
            <template #suffix>
              <span>个</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="发货方" prop="outSupplierName">
          <el-input v-model="forwardForm.outSupplierName" placeholder="请输入发货供应商名称" disabled />
        </el-form-item>

        <!--        <el-form-item label="发货方ID" prop="outSupplierId">-->
        <!--          <el-input v-model="forwardForm.outSupplierId" placeholder="请输入发货供应商系统ID" />-->
        <!--        </el-form-item>-->
        <el-form-item label="收货方" prop="inSupplierName">
          <!--          <el-input v-model="forwardForm.inSupplierName" placeholder="请输入收货供应商名称" />-->
          <el-select v-model="selectUser" placeholder="请选择供应商" @change="selectAction">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.rawData" :disabled="item.disabled">
              <!-- 自定义选项内容 -->
              <span>{{ item.label }}</span>
              <!--              <span style="float: right; color: #8492a6; font-size: 13px">-->
              <!--                {{ item.rawData.userName }}-->
              <!--              </span>-->
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收货方采购单" prop="inOrderSn">
          <el-input v-model="forwardForm.inOrderSn" placeholder="请输入收货方采购单" />
        </el-form-item>
        <!--        <el-form-item label="收货方ID" prop="inSupplierId">-->
        <!--          <el-input v-model="forwardForm.inSupplierId" placeholder="请输入收货供应商系统ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="发货区间" prop="shipmentStart">-->
        <!--          <el-date-picker-->
        <!--            v-model="intervalDate"-->
        <!--            type="daterange"-->
        <!--            range-separator="到"-->
        <!--            start-placeholder="开始日期"-->
        <!--            end-placeholder="结束日期"-->
        <!--            :size="'small'"-->
        <!--            @change="intervalAction"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="跟单人" prop="trackerName">-->
        <!--          <el-input v-model="forwardForm.trackerName" placeholder="请输入跟单人" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="跟单id" prop="trackerId">-->
        <!--          <el-input v-model="forwardForm.trackerId" placeholder="请输入跟单id" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="发货时间" prop="sendTime">-->
        <!--          <el-date-picker clearable v-model="forwardForm.sendTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发货时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="forwardSubmitForm">确 定</el-button>
          <el-button @click="forwardDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="forwardTableDialog.title" v-model="forwardTableDialog.visible" width="1800px" append-to-body>
      <el-table :data="shipForwardList">
        <!--        <el-table-column type="selection" width="55" align="center" />-->

        <el-table-column label="采购单号" align="center" prop="orderSn" />
        <el-table-column label="采购店铺名称" align="center" prop="storeName" />
        <el-table-column label="SKU" align="center" prop="sku" />
        <el-table-column label="产品全称" align="center" prop="productName" />
        <el-table-column label="实际发货数量" align="center" prop="quantitySend" />
        <el-table-column label="发货方" align="center" prop="outSupplierName" />
        <!--        <el-table-column label="发货供应商系统ID" align="center" prop="outSupplierId" />-->
        <el-table-column label="收货方" align="center" prop="inSupplierName" />
        <!--        <el-table-column label="收货供应商系统ID" align="center" prop="inSupplierId" />-->
        <!--        <el-table-column label="计划发货起始时间" align="center" prop="shipmentStart" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ parseTime(scope.row.shipmentStart, '{y}-{m}-{d}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="计划发货截止时间" align="center" prop="shipmentEnd" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ parseTime(scope.row.shipmentEnd, '{y}-{m}-{d}') }}</span-->
        <!--            >1-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="跟单人" align="center" prop="trackerName" />
        <!--        <el-table-column label="跟单id" align="center" prop="trackerId" />-->
        <el-table-column label="转发状态" align="center" prop="fwdStatus">
          <template #default="scope">
            <dict-tag :options="forward_status" :value="scope.row.fwdStatus" />
          </template>
        </el-table-column>
        <el-table-column label="发货时间" align="center" prop="sendTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
        <!--          <template #default="scope">-->
        <!--            <el-tooltip content="修改" placement="top">-->
        <!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['amz:shipForward:edit']"></el-button>-->
        <!--            </el-tooltip>-->
        <!--            <el-tooltip content="删除" placement="top">-->
        <!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['amz:shipForward:remove']"></el-button>-->
        <!--            </el-tooltip>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
      <!--      <template #footer>-->
      <!--        <div class="dialog-footer">-->
      <!--          <el-button :loading="buttonLoading" type="primary" @click="forwardSubmitForm">确 定</el-button>-->
      <!--          <el-button @click="cancel">取 消</el-button>-->
      <!--        </div>-->
      <!--      </template>-->
    </el-dialog>

    <el-dialog :title="shipDialog.title" v-model="shipDialog.visible" width="1000px" append-to-body>
      <el-form ref="sendOrderFormRef" :model="shipForm" :rules="rules3" label-width="120px">
        <el-form-item label="采购单号" prop="orderSn">
          <el-input v-model="shipForm.orderSn" placeholder="请输入采购单号" disabled />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="shipForm.productName" placeholder="请输入产品名称" disabled />
        </el-form-item>
        <el-form-item label="发货总数" prop="quantitySend">
          <el-input-number :min="1" :max="quantity" controls-position="right" v-model="shipForm.quantitySend" placeholder="发货总数" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="shipSubmitForm">提 交</el-button>
          <el-button @click="shipDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--    <el-dialog :title="shipDialog.title" v-model="shipDialog.visible" width="1000px" append-to-body>-->
    <!--      <el-form ref="sendOrderFormRef" :model="shipForm" :rules="rules3" label-width="120px">-->
    <!--        <el-form-item label="采购单号" prop="orderSn">-->
    <!--          <el-input v-model="shipForm.orderSn" placeholder="请输入采购单号" />-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="产品名称" prop="productName">-->
    <!--          <el-input v-model="shipForm.productName" placeholder="请输入产品名称" />-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="发货总数" prop="quantitySend">-->
    <!--          <el-input v-model="shipForm.quantitySend" placeholder="请输入发货数量" />-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="总箱数" prop="boxCount">-->
    <!--          <el-input v-model="shipForm.boxCount" placeholder="请输入总箱数" />-->
    <!--        </el-form-item>-->
    <!--        <el-form-item v-if="shipForm.quantitySend > 0 && shipForm.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].cartonCount"-->
    <!--                placeholder="箱子数量"-->
    <!--                type="number"-->
    <!--                min="0"-->
    <!--                class="flex-1"-->
    <!--                @input="validateInput(index, 'boxCount')"-->
    <!--              />-->
    <!--              X-->
    <!--              <el-input-->
    <!--                v-model.number="groups[index].piecesPerCarton"-->
    <!--                placeholder="每箱个数"-->
    <!--                type="number"-->
    <!--                min="0"-->
    <!--                class="flex-1"-->
    <!--                @input="validateInput(index, 'itemCount')"-->
    <!--              />-->
    <!--              <el-input v-model.number="groups[index].length" placeholder="长(cm)" type="number" min="0" class="flex-1" />-->
    <!--              <el-input v-model.number="groups[index].width" placeholder="宽(cm)" type="number" min="0" class="flex-1" />-->
    <!--              <el-input v-model.number="groups[index].height" placeholder="高(cm)" type="number" min="0" class="flex-1" />-->
    <!--              <el-input v-model.number="groups[index].weight" 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 }}/{{ shipForm.quantitySend }}-->
    <!--              </span>-->
    <!--              <el-button @click="addGroup" type="primary" :icon="Plus" :disabled="totalNum >= shipForm.quantitySend"> 添加一组 </el-button>-->
    <!--            </div>-->
    <!--          </div>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="总重量" prop="weightPerBox">-->
    <!--          &lt;!&ndash;          <el-input v-model="totalWeight" placeholder="请输入总重量" disabled />&ndash;&gt;-->
    <!--          <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>-->
    <!--      <template #footer>-->
    <!--        <div class="dialog-footer">-->
    <!--          <el-button :loading="buttonLoading" type="primary" @click="shipSubmitForm">提 交</el-button>-->
    <!--          <el-button @click="cancel">取 消</el-button>-->
    <!--        </div>-->
    <!--      </template>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script setup name="PurchaseOrder" lang="ts">
import { listPurchaseOrder, getPurchaseOrder, delPurchaseOrder, addPurchaseOrder, updatePurchaseOrder } from '@/api/amz/purchaseOrder';
import { PurchaseOrderVO, PurchaseOrderQuery, PurchaseOrderForm } from '@/api/amz/purchaseOrder/types';
import { ShipForwardForm, ShipForwardVO } from '@/api/amz/shipForward/types';
import { addShipForward, updateShipForward } from '@/api/amz/shipForward';
import { roleSelectPost } from '@/api/system/user';
import { updateOrderItemDetail } from '@/api/amz/purchaseOrderItem';
import { SendOrderForm } from '@/api/amz/sendOrder/types';
import { Close, Plus } from '@element-plus/icons-vue';
import { addSendOrder, updateSendOrder } from '@/api/amz/sendOrder';
import { PackingSpecsVO } from '@/api/amz/packingSpecs/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { vendor_order_status } = toRefs<any>(proxy?.useDict('vendor_order_status'));
const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'));
const { forward_status } = toRefs<any>(proxy?.useDict('forward_status'));

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

const route = useRoute();

const plength = ref<string | number>();
const pheight = ref<string | number>();
const pwidth = ref<string | number>();

const purchaseOrderList = ref<PurchaseOrderVO[]>([]);
const shipForwardList = ref<ShipForwardVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const forwardDataLoading = ref(false);

const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const maxQuality = ref(0);
const shipForwardFormRef = ref<ElFormInstance>();
const detailFormRef = ref<ElFormInstance>();
const sendOrderFormRef = ref<ElFormInstance>();

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

const statusClass = computed(() => ({
  'mr-8px': true,
  'text-green-500': totalNum.value === shipForm.value.quantitySend,
  'text-red-500': totalNum.value !== shipForm.value.quantitySend
}));

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

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

const detaildialog = reactive<DialogOption>({
  visible: false,
  title: '采购单详情'
});

const forwardTableDialog = reactive<DialogOption>({
  visible: false,
  title: '转发明细'
});

const initFormData: PurchaseOrderForm = {
  orderSn: undefined,
  customOrderSn: undefined,
  supplierId: undefined,
  supplierName: undefined,
  optUid: undefined,
  auditorRealname: undefined,
  optRealname: undefined,
  lastRealname: undefined,
  orderTime: undefined,
  payment: undefined,
  auditorUid: undefined,
  auditorTime: undefined,
  lastUid: undefined,
  lastTime: undefined,
  reason: undefined,
  isTax: undefined,
  status: undefined,
  statusText: undefined,
  payStatusText: undefined,
  statusShipped: undefined,
  statusShippedText: undefined,
  amountTotal: undefined,
  totalPrice: undefined,
  icon: undefined,
  payStatus: undefined,
  remark: undefined,
  otherFee: undefined,
  otherCurrency: undefined,
  feePartType: undefined,
  shippingPrice: undefined,
  shippingCurrency: undefined,
  purchaseCurrency: undefined,
  purchaseRate: undefined,
  quantityTotal: undefined,
  wid: undefined,
  wareHouseName: undefined,
  wareHouseBakName: undefined,
  quantityEntry: undefined,
  quantityReal: undefined,
  quantityReceive: undefined,
  purchaserId: undefined,
  contactPerson: undefined,
  contactNumber: undefined,
  settlementMethod: undefined,
  settlementDescription: undefined,
  paymentMethod: undefined,
  estDlvDays: undefined,
  orderStatus: undefined,
  deliveryTime: undefined,
  dlvTimeVar: undefined
};
const data = reactive<PageData<PurchaseOrderForm, PurchaseOrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderSn: undefined,
    customOrderSn: undefined,
    supplierId: undefined,
    supplierName: undefined,
    optUid: undefined,
    auditorRealname: undefined,
    optRealname: undefined,
    lastRealname: undefined,
    orderTime: undefined,
    payment: undefined,
    auditorUid: undefined,
    auditorTime: undefined,
    lastUid: undefined,
    lastTime: undefined,
    reason: undefined,
    isTax: undefined,
    status: undefined,
    statusText: undefined,
    payStatusText: undefined,
    statusShipped: undefined,
    statusShippedText: undefined,
    amountTotal: undefined,
    totalPrice: undefined,
    icon: undefined,
    payStatus: undefined,
    otherFee: undefined,
    otherCurrency: undefined,
    feePartType: undefined,
    shippingPrice: undefined,
    shippingCurrency: undefined,
    purchaseCurrency: undefined,
    purchaseRate: undefined,
    quantityTotal: undefined,
    wid: undefined,
    wareHouseName: undefined,
    wareHouseBakName: undefined,
    quantityEntry: undefined,
    quantityReal: undefined,
    quantityReceive: undefined,
    purchaserId: undefined,
    contactPerson: undefined,
    contactNumber: undefined,
    settlementMethod: undefined,
    settlementDescription: undefined,
    paymentMethod: undefined,
    estDlvDays: undefined,
    type: 'ord',
    orderStatus: [
      'ord_confirmed',
      'material_preparing',
      'production_started',
      'labeling_packaging',
      'semi_finished_outbound',
      'pending_outbound',
      'outbound_completed',
      'order_overdue'
    ],
    deliveryTime: undefined,
    // dlvTimeVar: undefined,
    params: {}
  },
  rules: {
    // orderSn: [{ required: true, message: '采购单号不能为空', trigger: 'blur' }],
    // customOrderSn: [{ required: true, message: '自定义单号不能为空', trigger: 'blur' }],
    // supplierId: [{ required: true, message: '供应商ID不能为空', trigger: 'blur' }],
    // supplierName: [{ required: true, message: '供应商名称不能为空', trigger: 'blur' }],
    // optUid: [{ required: true, message: '采购员ID不能为空', trigger: 'blur' }],
    // auditorRealname: [{ required: true, message: '审核人姓名不能为空', trigger: 'blur' }],
    // optRealname: [{ required: true, message: '操作人姓名不能为空', trigger: 'blur' }],
    // lastRealname: [{ required: true, message: '最后操作人姓名不能为空', trigger: 'blur' }],
    // orderTime: [{ required: true, message: '下单时间不能为空', trigger: 'blur' }],
    // payment: [{ required: true, message: '应付货款不能为空', trigger: 'blur' }],
    // auditorUid: [{ required: true, message: '审核人员ID不能为空', trigger: 'blur' }],
    // auditorTime: [{ required: true, message: '审核时间不能为空', trigger: 'blur' }],
    // lastUid: [{ required: true, message: '最后操作人员ID不能为空', trigger: 'blur' }],
    // lastTime: [{ required: true, message: '最后操作时间不能为空', trigger: 'blur' }],
    // reason: [{ required: true, message: '作废原因不能为空', trigger: 'blur' }],
    // isTax: [{ required: true, message: '是否含税：0 否，1 是不能为空', trigger: 'blur' }],
    // status: [
    //   {
    //     required: true,
    //     message: '采购单状态：-1 作废, 3 待提交, 1 待下单, 2 待签收, 9 完成, 121 待审核, 122 驳回, 124 作废不能为空',
    //     trigger: 'change'
    //   }
    // ],
    // statusText: [{ required: true, message: '状态说明不能为空', trigger: 'blur' }],
    // payStatusText: [{ required: true, message: '支付状态说明不能为空', trigger: 'blur' }],
    // statusShipped: [{ required: true, message: '到货状态：1 未到货, 2 部分到货, 3 全部到货不能为空', trigger: 'blur' }],
    // statusShippedText: [{ required: true, message: '到货状态说明不能为空', trigger: 'blur' }],
    // amountTotal: [{ required: true, message: '货物总价不能为空', trigger: 'blur' }],
    // totalPrice: [{ required: true, message: '总金额不能为空', trigger: 'blur' }],
    // icon: [{ required: true, message: '币种符号不能为空', trigger: 'blur' }],
    // payStatus: [
    //   {
    //     required: true,
    //     message: '付款状态：0 未申请, 1 已申请, 2 部分付款, 3 已付款不能为空',
    //     trigger: 'change'
    //   }
    // ],

    // remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
    // otherFee: [{ required: true, message: '其他费用不能为空', trigger: 'blur' }],
    // otherCurrency: [{ required: true, message: '其他费用币种不能为空', trigger: 'blur' }],
    // feePartType: [{ required: true, message: '费用分摊方式：0 不分摊, 1 按金额, 2 按数量不能为空', trigger: 'change' }],
    // shippingPrice: [{ required: true, message: '运费不能为空', trigger: 'blur' }],
    // shippingCurrency: [{ required: true, message: '运费币种不能为空', trigger: 'blur' }],
    // purchaseCurrency: [{ required: true, message: '采购币种不能为空', trigger: 'blur' }],
    // purchaseRate: [{ required: true, message: '采购汇率不能为空', trigger: 'blur' }],
    // quantityTotal: [{ required: true, message: '采购总量不能为空', trigger: 'blur' }],
    // wid: [{ required: true, message: '仓库ID不能为空', trigger: 'blur' }],
    // wareHouseName: [{ required: true, message: '仓库名称不能为空', trigger: 'blur' }],
    // wareHouseBakName: [{ required: true, message: '仓库名(备份)不能为空', trigger: 'blur' }],
    // quantityEntry: [{ required: true, message: '入库量不能为空', trigger: 'blur' }],
    // quantityReal: [{ required: true, message: '实际采购量不能为空', trigger: 'blur' }],
    // quantityReceive: [{ required: true, message: '待到货量不能为空', trigger: 'blur' }],
    // purchaserId: [{ required: true, message: '采购方ID不能为空', trigger: 'blur' }],
    // contactPerson: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
    // contactNumber: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }],
    // settlementMethod: [{ required: true, message: '结算方式：7 现结, 8 月结不能为空', trigger: 'blur' }],
    // settlementDescription: [{ required: true, message: '结算描述不能为空', trigger: 'blur' }],
    // paymentMethod: [{ required: true, message: '支付方式不能为空', trigger: 'blur' }],
    // dlvTimeVar: [{ required: true, message: '订单交付变动天数不能为空', trigger: 'blur' }]
    deliveryTime: [{ required: true, message: '交货时间不能为空', trigger: 'blur' }],
    estDlvDays: [{ required: true, message: '交货天数不能为空', trigger: 'blur' }],
    orderStatus: [{ required: true, message: '订单状态不能为空', trigger: 'change' }]
  },
  rules2: {
    id: [{ required: true, message: '$comment不能为空', trigger: 'blur' }],
    orderSn: [{ required: true, message: '采购单号不能为空', trigger: 'blur' }],
    inOrderSn: [{ required: true, message: '收货方采购单号不能为空', trigger: 'blur' }],
    storeName: [{ required: true, message: '采购店铺名称不能为空', trigger: 'blur' }],
    sku: [{ required: true, message: '产品唯一标识码不能为空', trigger: 'blur' }],
    productName: [{ required: true, message: '产品全称不能为空', trigger: 'blur' }],
    quantitySend: [{ required: true, message: '实际发货数量不能为空', trigger: 'blur' }],
    outSupplierName: [{ required: true, message: '发货供应商名称不能为空', trigger: 'blur' }],
    outSupplierId: [{ required: true, message: '发货供应商系统ID不能为空', trigger: 'blur' }],
    inSupplierName: [{ required: true, message: '收货供应商名称不能为空', trigger: 'blur' }],
    inSupplierId: [{ required: true, message: '收货供应商系统ID不能为空', trigger: 'blur' }],
    // shipmentStart: [{ required: true, message: '计划发货起始时间不能为空', trigger: 'blur' }],
    shipmentEnd: [{ required: true, message: '计划发货截止时间不能为空', trigger: 'blur' }],
    trackerName: [{ required: true, message: '跟单人不能为空', trigger: 'blur' }],
    trackerId: [{ required: true, message: '跟单id不能为空', trigger: 'blur' }],
    fwdStatus: [{ required: true, message: '转发状态不能为空', trigger: 'change' }],
    sendTime: [{ required: true, message: '发货时间不能为空', trigger: 'blur' }]
  },
  rules3: {
    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 != shipForm.value.boxCount) {
    //         console.log('totalBoxCount.value', totalBoxCount.value);
    //         console.log('form.value.boxCount', shipForm.value.boxCount);
    //         callback(new Error('明细箱数和总箱数不匹配，请调整'));
    //       }
    //       // 总量提示
    //       if (totalNum.value > shipForm.value.quantitySend) {
    //         const exceed = totalNum.value - shipForm.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, rules2, rules3 } = toRefs(data);

const forwardForm = ref<ShipForwardForm>({
  id: undefined,
  orderSn: undefined,
  storeName: undefined,
  sku: undefined,
  productName: undefined,
  quantitySend: undefined,
  outSupplierName: undefined,
  outSupplierId: undefined,
  inSupplierName: undefined,
  inSupplierId: undefined,
  shipmentStart: undefined,
  shipmentEnd: undefined,
  trackerName: undefined,
  trackerId: undefined,
  fwdStatus: undefined,
  sendTime: undefined,
  sfgAvlQty: 0
});

const shipForm = ref<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 detailForm = ref<any>({
  id: undefined,
  orderSn: undefined,
  sku: undefined,
  orderStatus: undefined,
  sfgAvlQty: undefined
});

const intervalDate = ref<any>();

const intervalAction = () => {
  console.log('intervalDate', intervalDate);
  forwardForm.value.shipmentStart = getDateToString(intervalDate.value[0]);
  forwardForm.value.shipmentEnd = getDateToString(intervalDate.value[1]);
};

const selectUser = ref<any>();
const selectAction = () => {
  console.log('selectUser', selectUser);

  forwardForm.value.inSupplierId = selectUser.value.userId;
  forwardForm.value.inSupplierName = selectUser.value.nickName;
  selectUser.value = selectUser.value.nickName;
};
const getDateToString = (date: Date): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需加 1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

/** 查询采购单主列表 */
const getList = async () => {
  loading.value = true;
  console.log('queryParams', queryParams);
  const copyParams = JSON.parse(JSON.stringify(queryParams.value)); // 仅适用简单数据类型[1,2](@ref)
  if (Array.isArray(copyParams.orderStatus)) {
    copyParams.orderStatus = copyParams.orderStatus.join(','); // 数组转字符串[6,7](@ref)
  }
  console.log('copyParams', copyParams);

  const res = await listPurchaseOrder(copyParams);
  purchaseOrderList.value = res.rows;
  // purchaseOrderList.value.map((item) => {
  //   if (item.forwardList) {
  //     item.remainingQuantity = item.quantityReal - item.forwardList.reduce((sum, item) => sum + item.quantitySend, 0);
  //   } else {
  //     item.remainingQuantity = item.quantityReal;
  //   }
  // });
  total.value = res.total;
  loading.value = false;
};
const options = ref([]);

const roleSelectAction = async () => {
  const res = await roleSelectPost([5]);
  console.log('res', res);

  options.value = res.data.map((user) => ({
    value: user.userId, // 选项值对应 userId
    label: user.nickName || '', // 显示文本用 nickName
    rawData: user // 保留原始数据（按需）
  }));
};

const openDetailDialog = (detail) => {
  shipForwardList.value = detail;
  forwardTableDialog.visible = true;
};

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

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

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

const delevAction = () => {
  form.value.deliveryTime = getDateAfterTwoDays(form.value.estDlvDays);
  console.log('form.value', form.value.deliveryTime);
};

const getDateAfterTwoDays = (dayNum: number): string => {
  const date = new Date(); // 获取当前时间
  date.setDate(date.getDate() + dayNum); // 增加 2 天

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需加 1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: PurchaseOrderVO[]) => {
  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?: PurchaseOrderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getPurchaseOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '设置延期';
};

const handleConfirm = async (row?: PurchaseOrderVO) => {
  // reset();
  // const _orderSn = row?.orderSn || ids.value[0];
  // const res = await getPurchaseOrder(_orderSn);
  // Object.assign(form.value, res.data);
  // dialog.visible = true;
  // dialog.title = '修改采购单主';

  // id: undefined,
  //   orderSn: undefined,
  //   storeName: undefined,
  //   sku: undefined,
  //   productName: undefined,
  //   quantitySend: undefined,
  //   outSupplierName: undefined,
  //   outSupplierId: undefined,
  //   inSupplierName: undefined,
  //   inSupplierId: undefined,
  //   shipmentStart: undefined,
  //   shipmentEnd: undefined,
  //   trackerName: undefined,
  //   trackerId: undefined,
  //   fwdStatus: undefined,
  //   sendTime: undefined

  console.log('row', row);
};
//row 明细数据
const handleForward = async (row?, rowM?) => {
  // reset();
  // const _orderSn = row?.orderSn || ids.value[0];
  // const res = await getPurchaseOrder(_orderSn);
  // Object.assign(form.value, res.data);
  // dialog.visible = true;
  // dialog.title = '修改采购单主';

  if (row?.orderStatus === 'order_prod_completed') {
    maxQuality.value = row?.quantityReal;
  } else {
    if (row?.sfgAvlQty) {
      maxQuality.value = row?.sfgAvlQty;
    } else {
      maxQuality.value = 0;
    }
  }

  if (maxQuality.value === 0 || maxQuality.value === undefined) {
    console.log('没有可以发的货！');
    proxy?.$modal.msgError('没有可以发的货！');
    return;
  }
  roleSelectAction();

  forwardForm.value.orderSn = row?.orderSn;
  forwardForm.value.storeName = rowM?.storeName;
  forwardForm.value.sku = row?.sku;
  forwardForm.value.productName = row?.productName;
  forwardForm.value.quantitySend = row?.quantitySend;
  forwardForm.value.outSupplierName = rowM?.supplierName;
  forwardForm.value.outSupplierId = rowM?.supplierId;
  forwardForm.value.orderDetailId = row?.id;
  forwardForm.value.sfgAvlQty = row?.sfgAvlQty;

  // forwardForm.value.inSupplierName = row?.inSupplierName;
  // forwardForm.value.inSupplierId = row?.inSupplierId;
  // forwardForm.value.shipmentStart = row?.shipmentStart;
  // forwardForm.value.shipmentEnd = row?.shipmentEnd;
  // forwardForm.value.trackerName = row?.trackerName;
  // forwardForm.value.trackerId = row?.trackerId;
  // forwardForm.value.fwdStatus = row?.fwdStatus;
  // forwardForm.value.sendTime = row?.sendTime;
  forwardForm.value.quantitySend = null;
  forwardForm.value.inSupplierName = null;
  forwardForm.value.inOrderSn = null;

  console.log('maxQuality', maxQuality.value);
  console.log('row', row);
  console.log('rowM', rowM);

  forwardDialog.visible = true;
  forwardDialog.title = '添加转发数据';
};

const quantity = ref(0);

const handleShip = async (row?, rowM?) => {
  let isExist = false;
  rowM.forwardList?.forEach((item) => {
    if (item.productName === row.productName) {
      isExist = true;
    }
  });

  if (isExist) {
    proxy?.$modal.msgError('该订单已有转发订单，无法进行成品发货！');
    return;
  }
  quantity.value = row?.quantityLeft;
  shipForm.value.orderSn = row?.orderSn;
  shipForm.value.productName = row?.productName;
  shipForm.value.quantitySend = row?.quantityReal;
  shipForm.value.storeName = rowM?.storeName;
  shipForm.value.orderDetailId = row?.id;
  shipForm.value.sendName = rowM?.supplierName;
  shipForm.value.sku = row?.sku;
  shipDialog.visible = true;
};

const handleDetail = (row?, rowM?) => {
  console.log('row', row);
  console.log('rowM', rowM);
  detailForm.value.id = row.id;
  detailForm.value.orderSn = row.orderSn;
  detailForm.value.orderStatus = row.orderStatus;
  detailForm.value.sfgAvlQty = row.sfgAvlQty;
  detailForm.value.remark = row.remark;
  detailForm.value.quantityReal = row.quantityReal;
  detailForm.value.productName = row.productName;

  detaildialog.visible = true;
  detaildialog.title = '编辑明细数据';
};

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

const forwardSubmitForm = () => {
  if (forwardForm.value.inSupplierName === forwardForm.value.outSupplierName) {
    proxy?.$modal.msgError('请不要选择相同的供应商');
    return;
  }
  shipForwardFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (forwardForm.value.id) {
        await updateShipForward(forwardForm.value).finally(() => (buttonLoading.value = false));
      } else {
        await addShipForward(forwardForm.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      forwardDialog.visible = false;
      await getList();
    }
  });
};

const submitDetailForm = async () => {
  // detailFormRef.value?.validate(async (valid: boolean) => {});

  const res = await updateOrderItemDetail(detailForm.value);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('操作成功');
  } else {
    proxy?.$modal.msgError(res.msg);
  }
  detaildialog.visible = false;
  await getList();
  console.log('res', res);
};

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

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

const groups = ref<PackingSpecsVO[]>([
  {
    id: undefined,
    sendOrderId: undefined,
    specName: undefined,
    cartonCount: undefined,
    piecesPerCarton: undefined,
    length: undefined,
    width: undefined,
    height: undefined,
    weight: undefined
  }
]);

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

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

// 计算所有输入值的总和
const totalBoxCount = computed(() => {
  return groups.value.reduce((sum, group) => {
    const box = Number(group.cartonCount) || 0;
    return sum + box;
  }, 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 addGroup = () => {
  if (totalNum.value >= shipForm.value.quantitySend) {
    ElMessage.error(`当前总量已达${shipForm.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 > shipForm.value.quantitySend) {
    ElMessage.warning('请调整剩余数值使总量不超过100');
  }
};

const shipSubmitForm = () => {
  shipForm.value.boxDimensions = `${pwidth.value} x ${pheight.value} x ${plength.value}`;

  shipForm.value.weightPerBox = totalWeight.value;
  const sendText = groups.value.reduce((sum, group, index) => {
    return (
      sum +
      '规格' +
      numberToLetter(index) +
      ': ' +
      group.cartonCount +
      '箱x' +
      group.piecesPerCarton +
      '件，长' +
      group.length +
      'cm宽' +
      group.width +
      'cm高' +
      group.height +
      'cm，' +
      '单箱重量' +
      group.weight +
      'kg' +
      '\n'
    );
  }, '');
  console.log('sendText: ', sendText);
  shipForm.value.sendDetail = null;
  shipForm.value.packingSpecsList = groups.value;
  console.log('shipForm', shipForm.value);
  sendOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (shipForm.value.id) {
        await updateSendOrder(shipForm.value).finally(() => (buttonLoading.value = false));
      } else {
        await addSendOrder(shipForm.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      shipDialog.visible = false;
      await getList();
    }
  });
};

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

watch(
  () => route.query.orderSn,
  (newOrderSn) => {
    if (typeof newOrderSn === 'string' && newOrderSn) {
      queryParams.value.orderSn = newOrderSn;
      getList();
    }
  },
  { immediate: true } // 立即执行一次
);

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