<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="110px">
            <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="warehouseName">
              <el-input v-model="queryParams.warehouseName" placeholder="请输入仓库名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="外包仓库名称" prop="outsourceWarehouseName">-->
            <!--              <el-input v-model="queryParams.outsourceWarehouseName" placeholder="请输入外包仓库名称" clearable @keyup.enter="handleQuery" />-->
            <!--            </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="创建时间" prop="bizCreateTime">-->
            <!--              <el-date-picker clearable v-model="queryParams.bizCreateTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择业务创建时间" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="状态文本描述" prop="statusText">-->
            <!--              <el-input v-model="queryParams.statusText" placeholder="请输入状态文本描述" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label="创建人姓名" prop="createRealname">
              <el-input v-model="queryParams.createRealname" placeholder="请输入创建人姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="PTP流水号" prop="ptpSn">-->
            <!--              <el-input v-model="queryParams.ptpSn" placeholder="请输入PTP流水号" 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="SKU" prop="sku">
              <el-input v-model="queryParams.sku" placeholder="请输入SKU" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="FNSKU编码" prop="fnsku">-->
            <!--              <el-input v-model="queryParams.fnsku" placeholder="请输入FNSKU编码" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="外包数量" prop="outsourceQuantity">-->
            <!--              <el-input v-model="queryParams.outsourceQuantity" placeholder="请输入外包数量" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="实收数量" prop="receiveQuantity">-->
            <!--              <el-input v-model="queryParams.receiveQuantity" placeholder="请输入实收数量" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="预计到达时间" prop="expectArriveTime">-->
            <!--              <el-input v-model="queryParams.expectArriveTime" placeholder="请输入预计到达时间" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="MSKU编码列表 (数组存储)" prop="msku">-->
            <!--              <el-input v-model="queryParams.msku" placeholder="请输入MSKU编码列表 (数组存储)" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="关联计划单号列表 (数组存储)" prop="planSn">-->
            <!--              <el-input v-model="queryParams.planSn" placeholder="请输入关联计划单号列表 (数组存储)" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label="店铺名称" prop="sellerName">
              <el-input v-model="queryParams.sellerName" placeholder="请输入店铺名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-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:purchaseOutOrder:add']"> 新增 </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['amz:purchaseOutOrder:edit']"-->
          <!--              >修改-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['amz:purchaseOutOrder:remove']"-->
          <!--              >删除-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['amz:purchaseOutOrder:export']">导出 </el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="purchaseOutOrderList" @selection-change="handleSelectionChange">
        <el-table-column type="expand">
          <template #default="props">
            <el-card 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="order.orderSn">
                  <template #default="scope">
                    <el-link type="primary" plain size="small" @click="goToOrderDetail(scope.row.item?.orderStatus, scope.row.order?.orderSn)">
                      {{ scope.row.order?.orderSn }}
                    </el-link>
                  </template>
                </el-table-column>
                <el-table-column label="供应商名称" align="center" prop="order.supplierName" />
                <el-table-column label="店铺名称" align="center" prop="order.storeName" />
                <el-table-column label="产品名称" align="center" prop="productName" />
                <el-table-column label="SKU" align="center" prop="sku" />
                <el-table-column width="150" label="转发详情" align="center">
                  <template #default="{ row }">
                    <el-tag v-if="props.row.supplierName === row.order?.supplierName" type="success">收货方</el-tag>
                    <el-tag v-else-if="!row.forwards || row.forwards.length === 0" type="warning">无转发信息</el-tag>
                    <el-button v-else type="primary" plain size="small" @click="openDetailDialog(row.forwards)"> 查看详情 </el-button>
                  </template>
                </el-table-column>
                <el-table-column label="下单时间" align="center" prop="order.orderTime" width="180">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.order?.orderTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column v-hasRoles="['superadmin', 'gengdan']" label="采购单状态" align="center" prop="status">
                  <template #default="scope">
                    <dict-tag :options="purchase_order_status" :value="scope.row.order?.status" />
                  </template>
                </el-table-column>
                <el-table-column label="转发完成数量" align="center" prop="quantityForward" />
                <el-table-column label="采购数量" align="center" prop="quantityReal" />
                <!--                <el-table-column label="已出货数量(最终仓库出货)" align="center" prop="quantityShipped" />-->
                <el-table-column align="center" prop="quantityShipped">
                  <!-- 使用 #header 插槽自定义表头 -->
                  <template #header>
                    <div class="custom-header">
                      <span>已出货数量</span>
                      <el-tooltip effect="dark" content="表示从最终仓库实际发出的货物数量，不包括订单内部的半成品转发" placement="top">
                        <!--                        <i class="el-icon-question header-icon"></i>-->
                        <!--                        <el-button type="danger" size="small" :icon="Delete" circle />-->
                        <el-icon color="#FB9700FF" style="font-size: 15px">
                          <Warning />
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>

                  <!-- 使用 #default 插槽自定义单元格内容 -->
                  <template #default="scope">
                    {{ scope.row.quantityShipped }}
                  </template>
                </el-table-column>
                <el-table-column label="剩余数量" align="center" prop="quantityLeft">
                  <template #header>
                    <div class="custom-header">
                      <span>剩余数量</span>
                      <el-tooltip effect="dark" content="表示从最终仓库实际的剩余货物数量，不包括订单内部的半成品转发" placement="top">
                        <!--                        <i class="el-icon-question header-icon"></i>-->
                        <!--                        <el-button type="danger" size="small" :icon="Delete" circle />-->
                        <el-icon color="#FB9700FF" style="font-size: 15px">
                          <Warning />
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>

                  <!-- 使用 #default 插槽自定义单元格内容 -->
                  <template #default="scope">
                    {{ scope.row.quantityLeft }}
                  </template>
                </el-table-column>
                <el-table-column label="订单状态" align="center" prop="item.orderStatus">
                  <template #default="scope">
                    <dict-tag :options="vendor_order_status" :value="scope.row.item?.orderStatus" />
                  </template>
                </el-table-column>
                <el-table-column label="备注" align="center" prop="order.remark" />
                <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.item, scope.row.order, scope.row, props.row)"
                      v-hasRoles="['superadmin', 'gengdan']"
                      v-hasPermi="['amz:purchaseOrder:remove']"
                      v-if="scope.row.forwardType == 'other'"
                    >
                      半成品转发
                    </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="orderSn">
          <template #default="scope">
            <el-tag>{{ scope.row.statusText }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="仓库" align="center" prop="warehouseName" />
        <!--        <el-table-column label="外包仓库名称" align="center" prop="outsourceWarehouseName" />-->
        <el-table-column label="供应商名称" align="center" prop="supplierName" />
        <el-table-column label="创建时间" align="center" prop="bizCreateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.bizCreateTime, '{y}-{m}-{d} {h}:{mm}:{ss}') }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="状态文本描述" align="center" prop="statusText" />-->
        <el-table-column label="创建人姓名" align="center" prop="createRealname" />
        <!--        <el-table-column label="PTP流水号" align="center" prop="ptpSn" />-->
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="SKU" align="center" prop="sku" />
        <!--        <el-table-column label="FNSKU" align="center" prop="fnsku" />-->
        <el-table-column label="外包数量" align="center" prop="outsourceQuantity" />
        <el-table-column label="已下单数量" align="center" prop="quantityShipped" />
        <el-table-column label="剩余数量" align="center" prop="quantityLeft" />
        <!--        <el-table-column label="实收数量" align="center" prop="receiveQuantity" />-->
        <el-table-column label="预计到达时间" align="center" prop="expectArriveTime" />
        <!--        <el-table-column label="MSKU编码列表 (数组存储)" align="center" prop="msku" />-->
        <!--        <el-table-column label="关联计划单号列表 (数组存储)" align="center" prop="planSn" />-->
        <el-table-column label="店铺名称" align="center" prop="sellerName" />
        <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="CircleCheck"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['amz:purchaseOutOrder:edit']"
              ></el-button>
            </el-tooltip>
            <!--            <el-tooltip content="删除" placement="top">-->
            <!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['amz:purchaseOutOrder: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="1500px" append-to-body>
      <el-form :inline="true" ref="purchaseOutOrderFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="委外订单号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入订单唯一编号" disabled />
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" disabled />
        </el-form-item>
        <!--        <el-form-item label="外包仓库名称" prop="outsourceWarehouseName">-->
        <!--          <el-input v-model="form.outsourceWarehouseName" placeholder="请输入外包仓库名称" />-->
        <!--        </el-form-item>-->
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请输入供应商名称" disabled />
        </el-form-item>
        <el-form-item label="创建时间" prop="bizCreateTime">
          <el-date-picker
            clearable
            v-model="form.bizCreateTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择业务创建时间"
            disabled
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="statusText">
          <el-input v-model="form.statusText" placeholder="请输入状态文本描述" disabled />
        </el-form-item>
        <el-form-item label="创建人姓名" prop="createRealname">
          <el-input v-model="form.createRealname" placeholder="请输入创建人姓名" disabled />
        </el-form-item>
        <!--        <el-form-item label="PTP流水号" prop="ptpSn">-->
        <!--          <el-input v-model="form.ptpSn" placeholder="请输入PTP流水号" />-->
        <!--        </el-form-item>-->
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="SKU" prop="sku">
          <el-input v-model="form.sku" placeholder="请输入标准SKU编码" disabled />
        </el-form-item>
        <!--        <el-form-item label="FNSKU" prop="fnsku">-->
        <!--          <el-input v-model="form.fnsku" placeholder="请输入FNSKU编码" disabled />-->
        <!--        </el-form-item>-->
        <el-form-item label="外包数量" prop="outsourceQuantity">
          <el-input-number
            :min="1"
            :max="quality"
            controls-position="right"
            v-model="form.outsourceQuantity"
            placeholder="请输入外包数量"
            @change="quantityAction(form.outsourceQuantity)"
          />
        </el-form-item>
        <!--        <el-form-item label="实收数量" prop="receiveQuantity">-->
        <!--          <el-input v-model="form.receiveQuantity" placeholder="请输入实收数量" disabled />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="预计到达时间" prop="expectArriveTime">-->
        <!--          <el-input v-model="form.expectArriveTime" placeholder="请输入预计到达时间" />-->
        <!--        </el-form-item>-->
        <el-form-item label="店铺名称" prop="sellerName">
          <el-input v-model="form.sellerName" placeholder="请输入店铺名称" disabled />
        </el-form-item>
      </el-form>
      <el-card shadow="never">
        <vxe-table
          ref="purchaseTable"
          v-loading="loading"
          :data="form.items"
          border
          size="mini"
          :header-cell-style="{ fontSize: '10px' }"
          :row-config="{ keyField: 'id' }"
          :scroll-y="{ enabled: true, gt: 100 }"
        >
          <!-- 采购单号 -->
          <vxe-column field="order.orderSn" title="采购单号" align="center" />

          <!-- 供应商名称 -->
          <vxe-column field="order.supplierName" title="供应商名称" align="center" />

          <!-- 店铺名称 -->
          <vxe-column field="order.storeName" title="店铺名称" align="center" />

          <vxe-column field="productName" title="产品名称" align="center" />

          <!-- 下单时间 (带格式化) -->
          <vxe-column field="order.orderTime" title="下单时间" width="180" align="center">
            <template #default="{ row }">
              <span>{{ parseTime(row.order.orderTime, '{y}-{m}-{d} {h}:{mm}:{ss}') }}</span>
            </template>
          </vxe-column>

          <!-- 采购单状态 (带权限控制) -->
          <vxe-column title="采购单状态" align="center">
            <template #default="{ row }">
              <dict-tag :options="purchase_order_status" :value="row.order.status" />
            </template>
          </vxe-column>

          <!-- 总金额 -->
          <!--          <vxe-column field="order.totalPrice" title="总金额" align="center" />-->

          <!-- 采购数量 -->
          <vxe-column field="order.quantityReal" title="采购数量" :edit-render="{ name: 'input' }" align="center" />

          <!-- 订单状态 -->
          <vxe-column title="订单状态" align="center">
            <template #default="{ row }">
              <dict-tag :options="vendor_order_status" :value="row.item.orderStatus" />
            </template>
          </vxe-column>

          <!-- 备注 -->
          <vxe-column field="order.remark" title="备注" align="center" />
        </vxe-table>
      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitSendOrderForm">提交订单</el-button>
          <el-button @click="cancel">取 消</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="quantityPlan" />
        <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="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 controls-position="right" v-model="forwardForm.quantityPlan" :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">-->
        <!--          &lt;!&ndash;          <el-input v-model="forwardForm.inSupplierName" placeholder="请输入收货供应商名称" />&ndash;&gt;-->
        <!--          <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">-->
        <!--              &lt;!&ndash; 自定义选项内容 &ndash;&gt;-->
        <!--              <span>{{ item.label }}</span>-->
        <!--              &lt;!&ndash;              <span style="float: right; color: #8492a6; font-size: 13px">&ndash;&gt;-->
        <!--              &lt;!&ndash;                {{ item.rawData.userName }}&ndash;&gt;-->
        <!--              &lt;!&ndash;              </span>&ndash;&gt;-->
        <!--            </el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="收货方" prop="inSupplierName">
          <el-input v-model="forwardForm.inSupplierName" placeholder="请输入收货方" disabled />
        </el-form-item>
        <el-form-item label="收货方采购单" prop="inOrderSn">
          <el-input v-model="forwardForm.inOrderSn" placeholder="请输入收货方采购单" />
        </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>
  </div>
</template>

<script setup name="PurchaseOutOrder" lang="ts">
import {
  listPurchaseOutOrder,
  getPurchaseOutOrder,
  delPurchaseOutOrder,
  addPurchaseOutOrder,
  updatePurchaseOutOrder,
  createSendOrderByBo
} from '@/api/amz/purchaseOutOrder';
import { PurchaseOutOrderVO, PurchaseOutOrderQuery, PurchaseOutOrderForm } from '@/api/amz/purchaseOutOrder/types';
import { VxeTable, VxeColumn } from 'vxe-table';
import type { VxeTablePropTypes } from 'vxe-table';

import 'vxe-table/lib/style.css';
import { ShipForwardForm, ShipForwardVO } from '@/api/amz/shipForward/types';
import { QuestionFilled } from '@element-plus/icons-vue';
import { roleSelectPost } from '@/api/system/user';
import { addShipForward, updateShipForward } from '@/api/amz/shipForward';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

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

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

const purchaseOutOrderList = ref<PurchaseOutOrderVO[]>([]);
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 router = useRouter();
const queryFormRef = ref<ElFormInstance>();
const purchaseOutOrderFormRef = ref<ElFormInstance>();

const shipForwardList = ref<ShipForwardVO[]>([]);

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

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

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

const editConfig: VxeTablePropTypes.EditConfig = {
  trigger: 'dblclick',
  mode: 'cell'
};

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 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 initFormData: PurchaseOutOrderForm = {
  orderSn: undefined,
  warehouseName: undefined,
  outsourceWarehouseName: undefined,
  supplierName: undefined,
  bizCreateTime: undefined,
  statusText: undefined,
  createRealname: undefined,
  ptpSn: undefined,
  productName: undefined,
  sku: undefined,
  fnsku: undefined,
  outsourceQuantity: undefined,
  receiveQuantity: undefined,
  expectArriveTime: undefined,
  msku: undefined,
  planSn: undefined,
  sellerName: undefined
};
const data = reactive<PageData<PurchaseOutOrderForm, PurchaseOutOrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderSn: undefined,
    warehouseName: undefined,
    outsourceWarehouseName: undefined,
    supplierName: undefined,
    bizCreateTime: undefined,
    statusText: undefined,
    createRealname: undefined,
    ptpSn: undefined,
    productName: undefined,
    sku: undefined,
    fnsku: undefined,
    outsourceQuantity: undefined,
    receiveQuantity: undefined,
    expectArriveTime: undefined,
    msku: undefined,
    planSn: undefined,
    sellerName: undefined,
    params: {}
  },
  rules: {
    orderSn: [{ required: true, message: '订单唯一编号不能为空', trigger: 'blur' }],
    warehouseName: [{ required: true, message: '仓库名称不能为空', trigger: 'blur' }],
    outsourceWarehouseName: [{ required: true, message: '外包仓库名称不能为空', trigger: 'blur' }],
    supplierName: [{ required: true, message: '供应商名称不能为空', trigger: 'blur' }],
    bizCreateTime: [
      {
        required: true,
        message: '业务创建时间 (Jackson格式: yyyy-MM-dd HH:mm:ss)不能为空',
        trigger: 'blur'
      }
    ],
    statusText: [{ required: true, message: '状态文本描述不能为空', trigger: 'blur' }],
    createRealname: [{ required: true, message: '创建人姓名不能为空', trigger: 'blur' }],
    ptpSn: [{ required: true, message: 'PTP流水号不能为空', trigger: 'blur' }],
    productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
    sku: [{ required: true, message: '标准SKU编码不能为空', trigger: 'blur' }],
    // fnsku: [{ required: true, message: 'FNSKU编码不能为空', trigger: 'blur' }],
    outsourceQuantity: [{ required: true, message: '外包数量不能为空', trigger: 'blur' }],
    receiveQuantity: [{ required: true, message: '实收数量不能为空', trigger: 'blur' }],
    expectArriveTime: [{ required: true, message: '预计到达时间不能为空', trigger: 'blur' }],
    // msku: [{ required: true, message: 'MSKU编码列表 (数组存储)不能为空', trigger: 'blur' }],
    // planSn: [{ required: true, message: '关联计划单号列表 (数组存储)不能为空', trigger: 'blur' }],
    sellerName: [{ required: true, message: '销售商名称不能为空', trigger: 'blur' }]
  },
  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' }],
    quantityPlan: [{ 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' }]
  }
});

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

const quality = ref(0);

const maxQuality = ref(0);

const selectUser = ref<any>();

const shipForwardFormRef = ref<ElFormInstance>();

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

  forwardForm.value.inSupplierId = selectUser.value.userId;
  forwardForm.value.inSupplierName = selectUser.value.nickName;
  selectUser.value = selectUser.value.nickName;
};

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

  console.log('row', row);
  console.log('rowM', rowM);
  console.log('rowA', rowA);
  if (row?.orderStatus === 'ord_unconfirmed') {
    proxy?.$modal.msgError('请先让供应商确认订单！');
    return;
  }

  maxQuality.value = Number(rowA?.quantityCanForward);
  console.log('maxQuality', maxQuality.value);
  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.quantityPlan = Number(maxQuality.value);
  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.inSupplierName = rowB?.supplierName;
  forwardForm.value.inSupplierId = rowB?.supplierId;
  forwardForm.value.inOrderSn = null;

  // console.log('row', row);
  // console.log('rowM', rowM);

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

/** 查询组合订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPurchaseOutOrder(queryParams.value);
  purchaseOutOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const quantityAction = (quantity: number) => {
  form.value.items.forEach((item) => {
    item.order.quantityReal = quantity * item.ratio;
  });
};

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加组合订单';
};

const goToOrderDetail = async (orderStatus?: string, orderSn?: string) => {
  if (orderStatus === 'ord_unconfirmed') {
    router.push({
      path: '/demand/purchaseOrder',
      query: {
        orderSn: orderSn
      }
    });
  } else {
    router.push({
      path: '/demand/purchaseOrderConfirm',
      query: {
        orderSn: orderSn
      }
    });
  }
};

const qualityMin = ref(0);

/** 修改按钮操作 */
const handleUpdate = async (row?: PurchaseOutOrderVO) => {
  reset();
  // const orderSn = row?.orderSn || ids.value[0];
  // const res = await getPurchaseOutOrder(orderSn);

  if (row.quantityLeft <= 0) {
    proxy?.$modal.msgError('该订单已全部发货');
    return;
  }
  if (row.items.every((item) => item.order.orderStatus === 'ord_unconfirmed')) {
    proxy?.$modal.msgError('有采购订单没有确认');
    return;
  }

  if (row.items.every((item) => item.fowardType === 'self' && item.quantityForward <= 0)) {
    proxy?.$modal.msgError('没有转发完成');
    return;
  }

  form.value = deepClone(row);

  form.value.items.forEach((item) => {
    // item.order.quantityReal = item.quantityLeft;
    let minQuantity2;
    if (item.forwardType === 'other') {
      minQuantity2 = Number(item.quantityForward) / Number(item.ratio);
      console.log('item', item);
      console.log('minQuantity2', minQuantity2);

      form.value.quantityLeft = Math.min(Number(row.quantityLeft), Number(minQuantity2));
    }
  });

  console.log('form.value.quantityLeft', form.value.quantityLeft);

  if (form.value.quantityLeft <= 0) {
    proxy?.$modal.msgError('该订单没有可发货数量');
    return;
  }
  console.log('form', form.value);

  form.value.outsourceQuantity = form.value.quantityLeft;
  quality.value = form.value.quantityLeft;
  console.log('quantity', quality.value);
  console.log('form.value.outsourceQuantity', form.value.outsourceQuantity);

  form.value.items.forEach((item) => {
    item.order.quantityReal = form.value.quantityLeft * item.ratio;
  });
  dialog.visible = true;
  dialog.title = '提交可发货订单';
};

function deepClone<T>(obj: T): T {
  return JSON.parse(JSON.stringify(obj));
}

/** 提交按钮 */
const submitForm = () => {
  purchaseOutOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.orderSn) {
        await updatePurchaseOutOrder(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addPurchaseOutOrder(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 submitSendOrderForm = () => {
  purchaseOutOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.orderSn) {
        await createSendOrderByBo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

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

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

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

onMounted(() => {
  getList();
});
onActivated(() => {
  getList();
});
</script>
<style scoped>
.custom-header {
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-icon {
  margin-left: 8px;
  color: #909399;
  cursor: pointer;
  transition: color 0.3s;
}

.header-icon:hover {
  color: #409eff;
}
</style>
