<template>
  <div class="card flex-column h-100 overflow-hidden">
    <div class="header-filter-form">
      <ElForm :model="searchForm" size="default" inline>
        <!-- <div> -->
        <ElFormItem label="仓库">
          <ElSelect
            v-model="searchForm.warehouseId"
            clearable
            filterable
            placeholder="请输入"
            style="width: 150px"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="平台">
          <ElSelect
            v-model="searchForm.platform"
            value-key=""
            placeholder="请选择"
            clearable
            filterable
            popper-class="customize-select-style"
            style="width: 150px"
          >
            <ElOption
              v-for="(item, index) in platformJson"
              :key="index"
              :label="item.type"
              :value="item.type"
              style="width: 160px"
            >
              <img
                :src="`/images/icon/${item.icon.split('/').pop()}`"
                style="height: 20px; margin: 5px 10px 0 0"
              />
              <span :title="item.type">{{ item.type }}</span>
            </ElOption>
          </ElSelect>
        </ElFormItem>

        <ElFormItem label="工艺">
          <ElSelect
            v-model="searchForm.craftCode"
            clearable
            filterable
            placeholder="请输入工艺"
            style="width: 150px"
          >
            <el-option
              v-for="item in craftList"
              :key="item.craftCode"
              :label="item.craftName"
              :value="item.craftCode"
            ></el-option>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="库存SKU">
          <ElInput
            v-model.trim="searchForm.thirdSkuCode"
            placeholder="库存SKU"
            clearable
            style="width: 150px"
          ></ElInput>
        </ElFormItem>
        <ElFormItem label="款号">
          <ElInput
            v-model="searchForm.supplierProductNo"
            placeholder="款号"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <ElFormItem label="批次号">
          <ElInput
            v-model="searchForm.batchArrangeNumber"
            placeholder="批次号"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <ElFormItem label="生产单号">
          <ElInput
            v-model="searchForm.factorySubOrderNumber"
            placeholder="生产单号"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <ElFormItem label="店铺单号">
          <ElInput
            v-model="searchForm.shopNumber"
            placeholder="店铺单号"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <!-- </div> -->
        <ElFormItem label="类型">
          <el-radio-group v-model="searchForm.customizedQuantity">
            <el-radio-button label="single">单面</el-radio-button>
            <el-radio-button label="multiple">多面</el-radio-button>
          </el-radio-group>
        </ElFormItem>
        <ElFormItem label="数量">
          <el-radio-group v-model="searchForm.multi">
            <el-radio-button :label="false">单件</el-radio-button>
            <el-radio-button :label="true">多件</el-radio-button>
          </el-radio-group>
        </ElFormItem>
        <ElFormItem>
          <ElPopover placement="bottom" width="600" trigger="click">
            <ElForm
              :model="searchForm"
              size="default"
              inline
              label-width="100px"
            >
              <ElFormItem style="width: 100%; padding-right: 40px">
                <div style="width: 100%; display: flex; flex-wrap: nowrap">
                  <el-select
                    v-model="searchForm.timeType"
                    clearable
                    :teleported="false"
                    placeholder="时间类型"
                    style="flex: 1; margin-right: 10px"
                  >
                    <el-option :value="1" label="创建时间"></el-option>
                    <el-option :value="2" label="确认时间"></el-option>
                    <el-option :value="3" label="完成时间"></el-option>
                  </el-select>
                  <el-date-picker
                    v-model="timeRange"
                    :teleported="false"
                    :default-time="[
                      new Date(0, 0, 0, 0, 0, 0),
                      new Date(0, 0, 0, 23, 59, 59),
                    ]"
                    placeholder="收货人"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetimerange"
                    style="width: 280px"
                    :shortcuts="pickerOptions.shortcuts"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    clearable
                  >
                  </el-date-picker>
                </div>
              </ElFormItem>
              <ElFormItem label="订单号">
                <ElInput
                  v-model="searchForm.factoryOrderNumber"
                  placeholder="订单号"
                  clearable
                  style="width: 150px"
                />
              </ElFormItem>

              <ElFormItem label="客户">
                <el-select
                  v-model="searchForm.userMark"
                  clearable
                  filterable
                  :teleported="false"
                  style="width: 150px"
                  placeholder="客户"
                >
                  <el-option
                    v-for="item in userMarkList"
                    :key="item"
                    :value="item"
                    :label="item"
                  ></el-option>
                </el-select>
              </ElFormItem>

              <ElFormItem label="生产端">
                <ElSelect
                  v-model="searchForm.productionClient"
                  placeholder="生产端"
                  clearable
                  :teleported="false"
                  style="width: 150px"
                >
                  <ElOption
                    v-for="(item, index) in productionClient"
                    :key="index"
                    :value="item.code || ''"
                    :label="`${item.remark}(${item.code})`"
                  ></ElOption>
                </ElSelect>
              </ElFormItem>
              <ElFormItem label="Variant SKU">
                <ElInput
                  v-model.trim="searchForm.sku"
                  placeholder="Variant SKU"
                  clearable
                  style="width: 150px"
                ></ElInput>
              </ElFormItem>
              <!-- <ElFormItem label="Base SKU">
                <ElInput
                  v-model.trim="searchForm.baseSku"
                  placeholder=" Base SKU"
                  clearable
                  style="width: 150px"
                ></ElInput>
              </ElFormItem> -->
              <ElFormItem label="物流跟踪号">
                <ElInput
                  v-model.trim="searchForm.trackingNumber"
                  placeholder="物流跟踪号"
                  clearable
                  style="width: 150px"
                ></ElInput>
              </ElFormItem>
              <ElFormItem label="物流类型">
                <ElSelect
                  v-model="searchForm.shipmentType"
                  placeholder="物流类型"
                  clearable
                  :teleported="false"
                  style="width: 150px"
                >
                  <ElOption
                    v-for="(item, index) in ['自有物流', '工厂物流']"
                    :key="index"
                    :value="index"
                    :label="item"
                  ></ElOption>
                </ElSelect>
              </ElFormItem>
            </ElForm>
            <template #reference>
              <el-button type="warning" @click="searchVisible = !searchVisible">
                <el-icon v-if="searchVisible">
                  <CaretTop />
                </el-icon>
                <el-icon v-else>
                  <CaretBottom />
                </el-icon>
              </el-button>
            </template>
          </ElPopover>
        </ElFormItem>
        <ElFormItem>
          <span>
            <ElButton link @click="resetSearchForm" style="font-size: 12px"
              ><span title="重置查询条件">重置</span></ElButton
            >
          </span>
        </ElFormItem>
        <ElFormItem>
          <span>
            <ElButton type="primary" @click="search">查询</ElButton>
          </span>
        </ElFormItem>

        <ElFormItem
          v-if="
            status === 'PICKING' ||
            status === 'TO_BE_REPLENISHMENT' ||
            status === 'IN_PRODUCTION'
          "
        >
          <span class="item">
            <ElButton
              :loading="tifDownloadLoading"
              type="warning"
              @click="downloadTif('tiff')"
            >
              TIF排版
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="
            status === 'PICKING' ||
            status === 'TO_BE_REPLENISHMENT' ||
            status === 'IN_PRODUCTION'
          "
        >
          <span class="item">
            <ElButton
              :loading="pngDownloadLoading"
              type="warning"
              @click="downloadTif('png')"
            >
              PNG排版
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'TO_BE_CONFIRMED'">
          <span class="item">
            <ElButton type="success" @click="confirmProduct">
              确认生产
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'EXCEPTION_ORDER'">
          <span class="item">
            <ElButton type="success" @click="updateOrder">
              转至待确认
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="status === 'EXCEPTION_ORDER' && exceptionStatus === 3"
        >
          <span class="item">
            <ElButton type="warning" @click="asyncOrderAddress">
              同步收货地址
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="status === 'EXCEPTION_ORDER' && exceptionStatus === 1"
        >
          <span class="item">
            <ElButton type="warning" @click="assignOrder"> 分派 </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="
            status === 'PICKING' ||
            status === 'TO_BE_REPLENISHMENT' ||
            status === 'IN_PRODUCTION'
          "
        >
          <!-- <span
          v-if="status === 'EXCEPTION_ORDER' && exceptionStatus === 2"
          class="item"
        >
          <ElButton type="warning" @click="handleExceptionOrder">
            处理异常
          </ElButton>
        </span> -->
          <span class="item">
            <ElButton type="primary" @click="printProductionOrder">
              打印生产单
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'TO_BE_REPLENISHMENT'">
          <span class="item">
            <ElButton type="success" @click="replenishmentSuccess">
              补胚完成
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'PICKING'">
          <span class="item">
            <ElButton type="success" @click="printPickingOrder">
              打印拣货单
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'PICKING'">
          <span class="item">
            <ElButton type="warning" @click="pickingComplete">
              拣胚完成
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'PICKING'">
          <span class="item">
            <ElButton type="success" @click="toOutOfStock"> 转至缺货 </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'TO_BE_CONFIRMED'">
          <span class="item">
            <ElButton type="warning" @click="changeExceptionOrder">
              转为异常单
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="status === 'TO_BE_CONFIRMED' && isPermissionBtn('RIIN')"
        >
          <span class="item">
            <ElButton type="success" @click="confirmProductToRiin">
              转至锐印生产
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="status === 'TO_BE_CONFIRMED' || status === 'EXCEPTION_ORDER'"
        >
          <span class="item">
            <ElButton type="danger" @click="cancelOrder">取消</ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'IN_PRODUCTION'">
          <!-- <span v-if="status !== 'IN_PRODUCTION'" class="item">
          <ElButton type="success" @click="handleUpdateRemark">
            添加内部标签
          </ElButton>
        </span> -->
          <span class="item">
            <ElButton type="warning" @click="onFastProduction">
              快捷生产
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'IN_PRODUCTION'">
          <span class="item">
            <ElButton type="success" @click="applyForReplenishment(undefined)">
              申请补胚
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'IN_PRODUCTION'">
          <span class="item">
            <ElButton type="success" @click="productioncompleted">
              生产完成
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'WAIT_SHIPMENT'">
          <span class="item">
            <ElButton type="warning" @click="printPodOrder">
              播种墙配货
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'CREATE_LOGISTICS'">
          <!-- <span v-if="status === 'WAIT_SHIPMENT'" class="item">
            <ElButton type="warning" @click="inspPackagOrder">
              质检包装
            </ElButton>
          </span> -->
          <span class="item">
            <ElButton type="warning" @click="logisticsToPicking">
              转至待排单
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'WAIT_SHIPMENT'">
          <span class="item">
            <ElButton type="primary" @click="completeDelivery()"
              >完成发货</ElButton
            >
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="status === 'WAIT_SHIPMENT' || status === 'CREATE_LOGISTICS'"
        >
          <span class="item">
            <ElDropdown>
              <el-button type="success">
                物流接口<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <ElDropdownMenu>
                  <ElDropdownItem
                    :disabled="
                      (selection.length === 0 && cardSelection.length === 0) ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('createLogisticsOrder')"
                    >创建物流订单</ElDropdownItem
                  >
                  <ElDropdownItem
                    :disabled="
                      (selection.length === 0 && cardSelection.length === 0) ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('getTrackingNumber')"
                    >获取跟踪号</ElDropdownItem
                  >
                  <ElDropdownItem
                    :disabled="
                      (selection.length === 0 && cardSelection.length === 0) ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('getPrintOrder')"
                    >获取打印面单</ElDropdownItem
                  >
                  <ElDropdownItem
                    :disabled="
                      (selection.length === 0 && cardSelection.length === 0) ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('cancelLogisticsOrder')"
                    >取消物流订单</ElDropdownItem
                  >
                  <!-- <ElDropdownItem
                    :disabled="
                      selection.length === 0 ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('batchChangeLogistics')"
                    >更换物流</ElDropdownItem
                  > -->
                </ElDropdownMenu>
              </template>
            </ElDropdown>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'STOCK_OUT'">
          <span class="item">
            <ElButton type="warning" @click="stockOutCheck">
              补货校验
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'STOCK_OUT'">
          <span class="item">
            <ElButton type="success" @click="toBePicking"> 转至生产 </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'TO_BE_ARRANGE'">
          <span class="item">
            <ElButton type="warning" @click="arrangeFinish">排单完成</ElButton>
          </span>
        </ElFormItem>

        <ElFormItem
          v-if="status !== 'BATCH_DOWNLOAD' && status !== 'WAIT_SHIPMENT'"
        >
          <span class="item">
            <ElButton type="primary" @click="downloadMaterial"
              >下载素材</ElButton
            >
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="
            status === 'INTERCEPTED' &&
            (interceptCurrent === 1 || interceptCurrent === 4)
          "
        >
          <span class="item">
            <ElButton type="success" @click="interceptChange(true)">
              拦截成功
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="
            status === 'INTERCEPTED' &&
            (interceptCurrent === 1 || interceptCurrent === 4)
          "
        >
          <span class="item">
            <ElButton type="danger" @click="interceptChange(false)">
              拦截失败
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="
            [
              'TO_BE_CONFIRMED',
              'PICKING',
              'STOCK_OUT',
              'EXCEPTION_ORDER',
              'TO_BE_REPLENISHMENT',
              'IN_PRODUCTION',
              'TO_BE_ARRANGE',
              'WAIT_SHIPMENT',
            ].includes(status)
          "
        >
          <span class="item">
            <ElButton type="success" @click="refreshMaterial">
              刷新商品信息
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="
            [
              'STOCK_OUT',
              'CREATE_LOGISTICS',
              'TO_BE_ARRANGE',
              'PICKING',
              'IN_PRODUCTION',
            ].includes(status)
          "
        >
          <span class="item">
            <ElDropdown>
              <el-button type="warning">
                驳回至<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <ElDropdownMenu>
                  <ElDropdownItem
                    :disabled="
                      selection.length === 0 && cardSelection.length === 0
                    "
                    @click="rejectOrder('TO_BE_CONFIRMED')"
                    >待确认</ElDropdownItem
                  >
                  <ElDropdownItem
                    v-if="
                      status === 'IN_PRODUCTION' ||
                      status === 'TO_BE_ARRANGE' ||
                      status === 'PICKING'
                    "
                    :disabled="
                      selection.length === 0 && cardSelection.length === 0
                    "
                    @click="rejectOrder('CREATE_LOGISTICS')"
                    >待创建物流</ElDropdownItem
                  >
                  <ElDropdownItem
                    v-if="status === 'PICKING' || status === 'IN_PRODUCTION'"
                    :disabled="
                      selection.length === 0 && cardSelection.length === 0
                    "
                    @click="rejectOrder('TO_BE_ARRANGE')"
                    >待排单</ElDropdownItem
                  >
                  <ElDropdownItem
                    v-if="status === 'IN_PRODUCTION'"
                    :disabled="
                      selection.length === 0 && cardSelection.length === 0
                    "
                    @click="rejectOrder('PICKING')"
                    >待拣胚</ElDropdownItem
                  >
                </ElDropdownMenu>
              </template>
            </ElDropdown>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'COMPLETE'">
          <span class="item">
            <ElButton type="warning" @click="statusPush">状态推送</ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'COMPLETE'">
          <span class="item">
            <ElButton type="success" @click="exportData">导出</ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'BATCH_DOWNLOAD'">
          <span class="item">
            <ElButton type="danger" @click="handleBatchDelete('batch')"
              >批量删除</ElButton
            >
          </span>
        </ElFormItem>
      </ElForm>
    </div>
    <div class="header-filter-tab">
      <div class="tabs">
        <div
          v-for="item in tabsNav"
          :key="item.status"
          class="tabs-node"
          :class="item.status === status ? 'tabs-node_active' : ''"
          @click="changeTab(item)"
        >
          <span class="tabs-node_label">{{ item.statusName }}</span>
          <span
            v-if="item.quantity"
            class="tabs-node_count"
            :class="{
              blue: item.quantity && item.quantity > 0,
              red: item.status === 'EXCEPTION_ORDER',
            }"
            >{{ item.quantity }}</span
          >
        </div>
        <!-- <div
            v-if="item.status === 'EXCEPTION_ORDER'"
            :key="item.status"
            class="tabs-node"
          >
            <el-dropdown @command="handleExceptionCommand">
              <div>
                <span
                  class="tabs-node_label"
                  style="color: #000; font-weight: 500"
                >
                  异常单
                </span>
                <span
                  class="tabs-node_count"
                  :class="{
                    blue: item.quantity && item.quantity > 0,
                    red: item.status === 'EXCEPTION_ORDER',
                  }"
                  >{{ item.quantity }}</span
                >
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </div>

              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="1">待分派</el-dropdown-item>
                  <el-dropdown-item command="2">待处理</el-dropdown-item>
                  <el-dropdown-item command="3">已处理</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div> -->
      </div>
    </div>
    <div class="order-content flex-1 flex-column overflow-hidden mt-10">
      <div v-if="status === 'EXCEPTION_ORDER'" class="sub-status mb-10">
        <div
          class="sub-status-item"
          :class="exceptionStatus === 1 ? 'sub-active' : ''"
          @click="handleExceptionCommand(1)"
        >
          <span class="sub-status-item-label">待分派</span>
        </div>
        <div
          class="sub-status-item"
          :class="exceptionStatus === 2 ? 'sub-active' : ''"
          @click="handleExceptionCommand(2)"
        >
          <span class="sub-status-item-label">待处理</span>
        </div>
        <div
          class="sub-status-item"
          :class="exceptionStatus === 3 ? 'sub-active' : ''"
          @click="handleExceptionCommand(3)"
        >
          <span class="sub-status-item-label">待同步</span>
        </div>
      </div>
      <div v-if="status === 'INTERCEPTED'" class="sub-status mb-10">
        <div
          class="sub-status-item"
          :class="interceptCurrent === 1 ? 'sub-active' : ''"
          @click="handleInterceptionCommand(1, 0)"
        >
          <span class="sub-status-item-label">生产拦截申请</span>
          <span
            v-if="interceptionStatus.production['0']"
            class="tabs-node_count blue"
            >{{ interceptionStatus.production['0'] }}</span
          >
        </div>
        <div
          class="sub-status-item"
          :class="interceptCurrent === 2 ? 'sub-active' : ''"
          @click="handleInterceptionCommand(2, 1)"
        >
          <span class="sub-status-item-label">生产拦截成功</span>
          <span
            v-if="interceptionStatus.production['1']"
            class="tabs-node_count blue"
            >{{ interceptionStatus.production['1'] }}</span
          >
        </div>
        <div
          class="sub-status-item"
          :class="interceptCurrent === 3 ? 'sub-active' : ''"
          @click="handleInterceptionCommand(3, 2)"
        >
          <span class="sub-status-item-label">生产拦截失败</span>
          <span
            v-if="interceptionStatus.production['2']"
            class="tabs-node_count red"
            >{{ interceptionStatus.production['2'] }}</span
          >
        </div>
        <div
          class="sub-status-item"
          :class="interceptCurrent === 4 ? 'sub-active' : ''"
          @click="handleInterceptionCommand(4, 2)"
        >
          <span class="sub-status-item-label">发货拦截申请</span>
          <span
            v-if="interceptionStatus.shipment['0']"
            class="tabs-node_count blue"
            >{{ interceptionStatus.shipment['0'] }}</span
          >
        </div>
        <div
          class="sub-status-item"
          :class="interceptCurrent === 5 ? 'sub-active' : ''"
          @click="handleInterceptionCommand(5, 3)"
        >
          <span class="sub-status-item-label">发货拦截成功</span>
          <span
            v-if="interceptionStatus.shipment['1']"
            class="tabs-node_count blue"
            >{{ interceptionStatus.shipment['1'] }}</span
          >
        </div>
        <div
          class="sub-status-item"
          :class="interceptCurrent === 6 ? 'sub-active' : ''"
          @click="handleInterceptionCommand(6, 4)"
        >
          <span class="sub-status-item-label">发货拦截失败</span>
          <span
            v-if="interceptionStatus.shipment['2']"
            class="tabs-node_count red"
            >{{ interceptionStatus.shipment['2'] }}</span
          >
        </div>
      </div>
      <div
        v-if="
          status !== 'IN_PRODUCTION' &&
          status !== 'PICKING' &&
          status !== 'TO_BE_REPLENISHMENT' &&
          status !== 'TO_BE_ARRANGE'
        "
        v-loading="loading"
        element-loading-text="加载中..."
        class="table-wrapper flex-1 flex-column overflow-hidden"
        @contextmenu.prevent="(v) => rightClick(v)"
      >
        <TableView
          ref="tableRef"
          :columns="tableColumns"
          :selectionable="true"
          :paginated-data="tableData"
          :cell-style="onCellStyle"
          :cell-class-name="onCellClassName"
          :row-style="getRowStyle"
          @selection-change="handleSelectionChange"
        >
          <template #serialNumber="{ row, index }">
            <div>
              <el-tooltip
                v-if="
                  status !== 'INTERCEPTED' &&
                  (row.interceptStatus == 0 || row.interceptStatus == 2)
                "
                effect="light"
                :content="
                  row.interceptStatus == 0
                    ? '订单已提交至生产拦截申请'
                    : '订单已提交至发货拦截申请'
                "
                placement="bottom"
              >
                <el-icon color="#E6A23C"><InfoFilled /></el-icon>
              </el-tooltip>
              <span class="serial-number">{{ index + 1 }}</span>
            </div>
          </template>
          <template #goods="{ row }">
            <div class="goods-info-box">
              <div class="goods-list">
                <div
                  v-for="item in row.productList"
                  :key="item"
                  class="goods-item"
                >
                  <div
                    class="goods-item-img"
                    style="display: flex; flex-direction: column"
                  >
                    <div
                      v-for="img in item.previewImgs"
                      :key="img"
                      style="text-align: center"
                    >
                      <img
                        :src="img.url"
                        alt="商品图片"
                        style="cursor: pointer"
                        @click="handlePictureCardPreview(img.url)"
                      />
                      <div
                        v-if="item.customizedQuantity"
                        class="triangle-box"
                        :title="`类型:${getQuantityText(
                          item.customizedQuantity,
                        )}面`"
                      >
                        <div class="multi-text">
                          {{ getQuantityText(item.customizedQuantity) }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="goods-item-info">
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">商品名称:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.productName }}
                      </span>
                    </div>
                    <!-- <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">Base SKU:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.baseSku }}
                      </span>
                      <el-icon class="icon" @click="copy(item.baseSku || '')">
                        <DocumentCopy />
                      </el-icon>
                    </div> -->
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">变体SKU:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.variantSku }}
                      </span>
                      <el-icon
                        class="icon"
                        @click="copy(item.variantSku || '')"
                      >
                        <DocumentCopy />
                      </el-icon>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">库存SKU:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.thirdSkuCode }}
                      </span>
                      <el-icon
                        class="icon"
                        @click="copy(item.thirdSkuCode || '')"
                      >
                        <DocumentCopy />
                      </el-icon>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">货号:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.thirdStockSku }}
                      </span>
                      <el-icon
                        class="icon"
                        @click="copy(item.thirdStockSku || '')"
                      >
                        <DocumentCopy />
                      </el-icon>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">工艺:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.craftName }}
                      </span>
                    </div>

                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">备注:</span>
                      <span
                        class="goods-item-info-item-value"
                        :title="item.remark"
                      >
                        {{ item.remark }}
                      </span>
                      <el-icon
                        class="icon"
                        style="color: #e6a23c"
                        @click="handleUpdateRemark(item)"
                      >
                        <EditPen />
                      </el-icon>
                    </div>
                  </div>
                  <div class="goods-item-info">
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">生产单号:</span>
                      <span
                        class="goods-item-info-item-value"
                        :title="item.factorySubOrderNumber"
                      >
                        {{ item.factorySubOrderNumber }}
                      </span>
                      <el-icon
                        class="icon"
                        @click.stop="copy(item.factorySubOrderNumber || '')"
                      >
                        <DocumentCopy />
                      </el-icon>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label"
                        >第三方生产单号:</span
                      >
                      <span
                        class="goods-item-info-item-value"
                        :title="item.thirdSubOrderNumber"
                      >
                        {{ item.thirdSubOrderNumber }}
                      </span>
                      <el-icon
                        class="icon"
                        @click.stop="copy(item.thirdSubOrderNumber || '')"
                      >
                        <DocumentCopy />
                      </el-icon>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">工厂:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.factoryCode }}
                      </span>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">款号:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.supplierProductNo }}
                      </span>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">克重:</span>
                      <span
                        v-if="item.weight"
                        class="goods-item-info-item-value"
                      >
                        {{ item.weight }}g
                      </span>
                    </div>
                    <div
                      v-if="item.isReplenishment"
                      class="goods-item-info-item"
                    >
                      <!-- <span class="goods-item-info-item-label">补胚状态:</span> -->
                      <el-tag size="small" effect="dark" type="danger"
                        >补胚中
                      </el-tag>
                    </div>
                  </div>
                  <div class="goods-item-info">
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label"
                        >商品单价($):</span
                      >
                      <span class="goods-item-info-item-value">
                        {{ item.productPrice }}
                      </span>
                    </div>
                    <!-- <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">模板金额:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.templatePrice }}($)
                      </span>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">工艺金额:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.craftPrice }}($)
                      </span>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">付款金额:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.payAmount }}($)
                      </span>
                    </div> -->

                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">{{
                        status === 'EXCEPTION_ORDER' ||
                        status === 'PICKING' ||
                        status === 'TO_BE_CONFIRMED' ||
                        status === 'STOCK_OUT' ||
                        status === 'CREATE_LOGISTICS'
                          ? '数量:'
                          : '已生产数量:'
                      }}</span>
                      <span class="goods-item-info-item-value">
                        {{
                          status === 'EXCEPTION_ORDER' ||
                          status === 'PICKING' ||
                          status === 'TO_BE_CONFIRMED' ||
                          status === 'STOCK_OUT' ||
                          status === 'CREATE_LOGISTICS'
                            ? item.num
                            : item.passNum
                        }}
                      </span>
                    </div>
                    <div
                      v-if="status === 'WAIT_SHIPMENT' || status === 'COMPLETE'"
                      class="goods-item-info-item"
                      style="align-items: start"
                    >
                      <span class="goods-item-info-item-label">补胚数量:</span>
                      <span
                        class="goods-item-info-item-value"
                        :title="item.replenishmentSumNum"
                      >
                        {{ item.replenishmentSumNum || 0 }}
                      </span>
                      <!-- <ElDropdown
                        v-if="status === 'WAIT_SHIPMENT'"
                        style="height: 23px"
                        size="small"
                      >
                        <span class="el-dropdown-link"
                          >素材接口<el-icon class="el-icon--right"
                            ><ArrowDown /></el-icon
                        ></span>

                        <template #dropdown>
                          <ElDropdownMenu>
                            <ElDropdownItem @click="applyForReplenishment(item)"
                              >申请补胚</ElDropdownItem
                            >
                            <ElDropdownItem @click="downloadMaterialItem(item)"
                              >下载素材</ElDropdownItem
                            >
                            <ElDropdownItem
                              @click="downloadTifItem('tiff', item.id)"
                              >TIF排版</ElDropdownItem
                            >
                            <ElDropdownItem
                              @click="downloadTifItem('png', item.id)"
                              >PNG排版</ElDropdownItem
                            >
                          </ElDropdownMenu>
                        </template>
                      </ElDropdown> -->
                      <div
                        v-if="status === 'WAIT_SHIPMENT'"
                        style="
                          display: flex;
                          flex-direction: column;
                          align-items: center;
                        "
                      >
                        <el-button
                          link
                          size="small"
                          type="success"
                          style="height: 23px"
                          @click="applyForReplenishment(item)"
                          >申请补胚
                        </el-button>
                      </div>

                      <!-- f -->
                    </div>
                    <div
                      v-if="status === 'WAIT_SHIPMENT'"
                      style="display: flex; justify-content: space-between"
                    >
                      <el-button
                        link
                        size="small"
                        type="primary"
                        style="height: 23px; padding: 0"
                        @click="downloadMaterialItem(item)"
                        >下载素材
                      </el-button>
                      <el-button
                        link
                        size="small"
                        type="warning"
                        style="height: 23px; margin: 0"
                        @click="downloadTifItem('tiff', item.id)"
                        >TIF排版
                      </el-button>
                      <el-button
                        link
                        size="small"
                        type="warning"
                        style="height: 23px; margin: 0"
                        @click="downloadTifItem('png', item.id)"
                        >PNG排版
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <template #orderDetail="{ row }">
            <div class="order-detail-box">
              <div class="order-detail-item">
                <span class="order-detail-item-label">订单号:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.factoryOrderNumber"
                >
                  {{ row.factoryOrderNumber }}
                </span>
                <el-icon
                  class="icon"
                  @click="copy(row.factoryOrderNumber || '')"
                >
                  <DocumentCopy />
                </el-icon>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">第三方订单号:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.thirdOrderNumber"
                >
                  {{ row.thirdOrderNumber }}
                </span>
                <el-icon class="icon" @click="copy(row.thirdOrderNumber || '')">
                  <DocumentCopy />
                </el-icon>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">店铺单号:</span>
                <span class="order-detail-item-value" :title="row.shopNumber">
                  {{ row.shopNumber }}
                </span>
                <el-icon class="icon" @click="copy(row.shopNumber || '')">
                  <DocumentCopy />
                </el-icon>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">物流类型:</span>
                <span
                  style="color: red; font-weight: 500"
                  class="order-detail-item-value"
                >
                  {{ ['自有物流', '工厂物流'][row.shipmentType] }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">物流跟踪号:</span>
                <span class="order-detail-item-value">
                  <el-button
                    type="primary"
                    :title="row.trackingNumber"
                    link
                    :disabled="!row.expressSheet"
                    @click="downloadFacebook(row.expressSheet)"
                  >
                    {{ row.trackingNumber }}</el-button
                  >
                </span>
                <el-icon class="icon" @click="copy(row.trackingNumber || '')">
                  <DocumentCopy />
                </el-icon>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">总克重:</span>
                <span v-if="row.weight" class="order-detail-item-value">
                  {{ row.weight }}g
                </span>
              </div>
              <div
                v-if="row.status !== 'TO_BE_CONFIRMED'"
                class="order-detail-item"
              >
                <span class="order-detail-item-label">生产端:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.productionClient"
                >
                  {{ row.productionClient }}
                </span>
              </div>
              <div
                v-if="
                  row.productionClient === 'JOMALL' &&
                  row.status !== 'TO_BE_CONFIRMED'
                "
                class="order-detail-item"
              >
                <span class="order-detail-item-label">发货仓库:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.warehouseName"
                >
                  {{ row.warehouseName }}
                </span>
              </div>
              <div
                v-if="
                  row.productionClient === 'JOMALL' &&
                  row.status !== 'TO_BE_CONFIRMED'
                "
                class="order-detail-item"
              >
                <span class="order-detail-item-label">物流方式:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.logisticsWayName"
                >
                  {{ row.logisticsWayName }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">收货人:</span>
                <span class="order-detail-item-value" :title="row.receiverName">
                  {{ row.receiverName }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">收货人电话:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.receiverPhone"
                >
                  {{ row.receiverPhone }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">收货人邮编:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.receiverPostCode"
                >
                  {{ row.receiverPostCode }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">收货地址:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.lanshouAddress"
                >
                  {{ row.lanshouAddress }}
                </span>
              </div>
            </div>
          </template>
          <template #price="{ row }">
            <div class="order-price-box">
              <div class="order-price-item">
                <div class="order-price-item-label">商品总价</div>
                <div class="order-price-item-value">
                  {{ row.totalAmount }}
                </div>
              </div>

              <div
                v-if="
                  row.status !== 'TO_BE_CONFIRMED' &&
                  row.status !== 'EXCEPTION_ORDER'
                "
                class="order-price-item"
              >
                <div class="order-price-item-label">物流运费</div>
                <div class="order-price-item-value">
                  {{ row.payFreight }}
                </div>
              </div>
            </div>
          </template>
          <template #time="{ row }">
            <el-timeline>
              <el-timeline-item
                :color="row.createTime ? '#409EFF' : ''"
                :timestamp="row.createTime"
                >创建时间
              </el-timeline-item>
              <el-timeline-item
                :color="row.startStockingTime ? '#E6A23C' : ''"
                :timestamp="row.startStockingTime"
                >确认时间
              </el-timeline-item>
              <el-timeline-item
                :color="row.finishTime ? '#67C23A' : ''"
                :timestamp="row.finishTime"
                >完成时间
              </el-timeline-item>
            </el-timeline>
            <!-- <div class="order-time-box">
              <div class="order-time-item">
                <span class="order-time-item-label">创建时间：</span>
                <span class="order-time-item-value">
                  {{ row.createTime }}
                </span>
              </div>
              <div class="order-time-item">
                <span class="order-time-item-label">确认时间：</span>
                <span class="order-time-item-value">
                  {{ row.startStockingTime }}
                </span>
              </div>

              <div class="order-time-item">
                <span class="order-time-item-label">完成时间：</span>
                <span class="order-time-item-value">
                  {{ row.finishTime }}
                </span>
              </div>
            </div> -->
          </template>
          <template #exceptionReason="{ row }">
            <div style="white-space: pre-line">{{ row.exceptionReason }}</div>
          </template>
          <template #innerLabel="{ row }">
            <div v-if="row.internalMemoList" class="inner-label-box">
              <div
                v-for="(item, index) in row.internalMemoList"
                :key="index"
                class="inner-label-item"
              >
                <span class="inner-label-item-value">
                  {{
                    `${item.operatorTime} ${item.operatorEmployeeName}:  ${item.content}`
                  }}
                </span>
              </div>
            </div>
          </template>
          <template #downloadStatus="{ row }">
            <div style="white-space: pre-line">
              <el-tag v-if="row.downloadStatus" type="success">已下载</el-tag>
              <el-tag v-else type="danger">未下载</el-tag>
            </div>
          </template>
          <template #createTime="{ row }">
            <div style="white-space: pre-line">
              {{ row.createTime.replace('T', ' ') }}
            </div>
          </template>
          <template #finishTime="{ row }">
            <div style="white-space: pre-line">
              {{ row.finishTime?.replace('T', ' ') }}
            </div>
          </template>
          <template #failTime="{ row }">
            <div style="white-space: pre-line">
              {{ row.failTime?.replace('T', ' ') }}
            </div>
          </template>
          <template #failReason="{ row }">
            <span v-html="row.failReason" style="white-space: pre-line"></span>
          </template>
          <template #operate="{ row }">
            <div
              v-if="status === 'BATCH_DOWNLOAD'"
              class="operate-box-vertical"
            >
              <span class="operate-item">
                <ElButton
                  :disabled="!row.url"
                  link
                  type="primary"
                  @click="handleDownload(row, 'png')"
                >
                  PNG下载
                </ElButton>
              </span>
              <span class="operate-item">
                <ElButton
                  disabled
                  link
                  type="primary"
                  @click="handleDownload(row, 'tiff')"
                >
                  TIF下载
                </ElButton>
              </span>
              <span class="operate-item">
                <ElButton
                  link
                  type="warning"
                  :loading="reComposingLoadingMap[row.id]"
                  @click="handleReComposingDesign(row)"
                >
                  重新排版
                </ElButton>
              </span>
              <span class="operate-item">
                <ElButton
                  link
                  type="danger"
                  @click="handleBatchDelete('single', row.id)"
                >
                  删除
                </ElButton>
              </span>
            </div>
            <div v-else class="operate-box">
              <span v-if="status !== 'BATCH_DOWNLOAD'" class="operate-item">
                <ElButton
                  link
                  type="primary"
                  @click="operationLog(row.id, null)"
                >
                  操作日志
                </ElButton>
              </span>

              <!-- <span
                v-if="!row.expressSheet && row.status === 'TO_BE_CONFIRMED'"
                class="operate-item"
              >
                <ElButton link type="primary" @click="confirm(row)">
                  确认
                </ElButton>
              </span> -->
              <span
                v-if="
                  row.shipmentType === 0 &&
                  ['CREATE_LOGISTICS', 'WAIT_SHIPMENT'].includes(status)
                "
                class="operate-item"
              >
                <ElButton link type="primary" @click="showLogistics(row)">
                  更新物流
                </ElButton>
              </span>
              <span
                v-if="
                  row.shipmentType === 1 &&
                  ['CREATE_LOGISTICS', 'WAIT_SHIPMENT'].includes(status)
                "
                class="operate-item"
              >
                <ElButton link type="primary" @click="handleUpdateAddress(row)">
                  修改地址
                </ElButton>
              </span>
              <span
                v-if="
                  (status === 'WAIT_SHIPMENT' ||
                    status === 'CREATE_LOGISTICS') &&
                  row.shipmentType === 1
                "
                class="operate-item"
              >
                <ElButton link type="primary" @click="handleStockOut(row)">
                  更换物流
                </ElButton>
              </span>
              <span
                v-if="
                  row.shipmentType === 0 &&
                  ['CREATE_LOGISTICS', 'WAIT_SHIPMENT'].includes(status)
                "
                class="operate-item"
              >
                <ElButton
                  link
                  type="primary"
                  @click="handleRefreshAddress(row)"
                >
                  刷新地址
                </ElButton>
              </span>
              <span
                v-if="
                  (status === 'IN_TRANSIT' || status === 'COMPLETE') &&
                  isPermissionBtn('TRACK')
                "
                class="operate-item"
              >
                <ElButton link type="primary" @click="logTrajectory(row)"
                  >物流轨迹</ElButton
                >
              </span>
            </div>
          </template>
        </TableView>
      </div>
      <div
        v-else
        v-loading="loading"
        element-loading-text="加载中..."
        class="card-wrapper flex-1 flex-column overflow-hidden"
      >
        <div v-if="tableData.length > 0" class="card-list">
          <div
            v-for="cardItem in tableData as ProductList[]"
            :key="cardItem.id"
            class="card-list-item"
            @click="cardClick(cardItem)"
            @mouseleave="handleChangeImages(null, cardItem)"
          >
            <CommonCard
              :card-item="cardItem"
              :active="isSelectStatused(cardItem)"
              :show-sku="false"
              :show-product-info="false"
              :image-field="'variantImage'"
              @contextmenu.prevent="(v: MouseEvent) => rightClick(v)"
            >
              <template #top_left>
                <el-tooltip
                  v-if="
                    cardItem.interceptStatus == 0 ||
                    cardItem.interceptStatus == 2
                  "
                  effect="light"
                  :content="
                    cardItem.interceptStatus == 0
                      ? '订单已提交至生产拦截申请'
                      : '订单已提交至发货拦截申请'
                  "
                  placement="bottom"
                >
                  <el-icon color="#E6A23C"><InfoFilled /></el-icon>
                </el-tooltip>
              </template>
              <template
                v-if="['ZPZY', 'CXZY', 'THZY'].includes(cardItem.craftCode as string)"
                #top_right
              >
                <img
                  :src="`/images/pic/${cardItem.craftCode}.png`"
                  width="100px;"
                  height="100px"
                  alt=""
                />
              </template>
              <template #bottom_left>
                <span
                  v-if="cardItem?.factorySubOrderNumber"
                  :title="`生产单号:${cardItem?.factorySubOrderNumber || ''}`"
                  class="factory-sub-order-number"
                  @click.stop="
                    copy(String(cardItem?.factorySubOrderNumber || ''))
                  "
                >
                  {{ cardItem?.factorySubOrderNumber }}
                </span>
              </template>
              <template #operations>
                <div
                  v-if="cardItem?.customizedQuantity"
                  class="customizedQuantity"
                  :title="`类型:${getQuantityText(
                    cardItem?.customizedQuantity,
                  )}面`"
                >
                  {{ getQuantityText(cardItem?.customizedQuantity) }}
                </div>
                <Icon
                  name="caozuorizhi"
                  @click="(e: MouseEvent) => operationLog(cardItem.podJomallOrderUsId, e)"
                  style="width: 28px; height: 28px"
                >
                  <template #title>
                    <title>操作日志</title>
                  </template>
                </Icon>
                <Icon name="chakanxiangqing" @click="openDetail(cardItem.id)">
                  <template #title>
                    <title>查看详情</title>
                  </template>
                </Icon>
              </template>
              <template #images>
                <div class="flex-between">
                  <div v-if="cardItem.imageAry" class="images-position">
                    <div
                      v-for="(item, index) in filteredImages(cardItem.imageAry)"
                      :key="index"
                      :title="item.title"
                      class="item-image"
                      @mousemove="handleChangeImages(item, cardItem)"
                    >
                      <img
                        :src="item?.url"
                        height="28"
                        @click="handlePictureCardPreview(item?.url)"
                      />
                    </div>
                  </div>
                  <div v-if="cardItem.platform">
                    <img
                      :src="`/images/icon/${getPlatformImg(cardItem.platform)}`"
                      style="height: 30px"
                    />
                  </div>
                </div>
              </template>
              <template #info>
                <div class="grid-container">
                  <div
                    class="grid-item"
                    :title="`商品名称:${cardItem?.productName || ''}`"
                  >
                    <span class="grid-item-value"
                      >{{ cardItem?.productName }}
                    </span>
                  </div>
                  <div
                    :style="{
                      visibility:
                        status === 'IN_PRODUCTION' ||
                        status === 'PICKING' ||
                        status === 'TO_BE_ARRANGE'
                          ? 'visible'
                          : 'hidden',
                    }"
                    class="grid-item"
                    :title="status === 'PICKING' ? '数量' : '未生产数量'"
                  >
                    <span class="grid-item-label">数量：</span>
                    <span class="grid-item-value">
                      {{
                        status === 'PICKING'
                          ? cardItem.num || 0
                          : cardItem?.notPassNum || 0
                      }}
                    </span>
                  </div>
                  <div
                    class="grid-item"
                    @click="copy(cardItem?.variantSku || '')"
                  >
                    <div
                      :title="`variant SKU: ${cardItem?.variantSku || ''}`"
                      class="grid-item-value"
                    >
                      <div class="orderNumber">{{ cardItem?.variantSku }}</div>
                    </div>
                  </div>
                  <div v-if="status !== 'TO_BE_ARRANGE'" class="grid-item">
                    <span class="grid-item-label">补胚数量：</span>
                    <span class="grid-item-value">
                      {{ cardItem?.replenishmentNum || 0 }}
                    </span>
                  </div>
                  <div
                    class="grid-item"
                    @click="copy(cardItem?.thirdSkuCode || '')"
                  >
                    <div
                      :title="`库存SKU:${cardItem?.thirdSkuCode || ''}`"
                      class="grid-item-value"
                    >
                      <div class="orderNumber">
                        {{ cardItem?.thirdSkuCode }}
                      </div>
                    </div>
                  </div>
                  <div
                    class="grid-item"
                    :title="`工艺:${cardItem?.craftName || ''}`"
                  >
                    <span class="grid-item-label">工艺：</span>
                    <span class="grid-item-value">
                      {{ cardItem?.craftName }}
                    </span>
                  </div>
                  <div
                    class="grid-item"
                    :title="`店铺单号:${cardItem?.shopNumber || ''}`"
                    @click="copy(cardItem?.shopNumber || '')"
                  >
                    <div class="grid-item-value">
                      <div class="orderNumber">
                        {{ cardItem?.shopNumber }}
                      </div>
                    </div>
                  </div>
                  <div class="grid-item">
                    <span class="grid-item-label">款号：</span>
                    <span
                      :title="`款号: ${cardItem?.supplierProductNo}`"
                      class="grid-item-value"
                    >
                      {{ cardItem?.supplierProductNo }}
                    </span>
                  </div>
                  <div
                    class="grid-item"
                    @click="copy(cardItem?.factoryOrderNumber || '')"
                  >
                    <div
                      :title="`订单号:${cardItem?.factoryOrderNumber}`"
                      class="grid-item-value orderNumber"
                    >
                      {{ cardItem?.factoryOrderNumber }}
                    </div>
                  </div>
                  <div class="grid-item">
                    <span class="grid-item-label">货号：</span>
                    <span
                      :title="`货号: ${cardItem?.thirdStockSku}`"
                      class="grid-item-value"
                    >
                      {{ cardItem?.thirdStockSku }}
                    </span>
                  </div>

                  <!-- <div class="grid-item" title="订单号">
                    <span
                      class="grid-item-value"
                      @click="copy(cardItem?.factoryOrderNumber || '')"
                    >
                      {{ cardItem?.factoryOrderNumber }}
                    </span>
                  </div> -->

                  <div
                    v-if="cardItem.batchArrangeNumber"
                    class="grid-item"
                    :title="`批次号:${cardItem?.batchArrangeNumber || ''}`"
                    @click="copy(cardItem?.batchArrangeNumber || '')"
                  >
                    <div class="grid-item-value">
                      <div class="orderNumber">
                        {{ cardItem?.batchArrangeNumber }}
                      </div>
                    </div>
                  </div>
                  <div v-if="cardItem.isReplenishment" class="grid-item">
                    <el-tag size="small" type="danger" effect="dark"
                      >补胚中
                    </el-tag>
                  </div>
                </div>
              </template>
            </CommonCard>
          </div>
        </div>
        <div v-else class="empty">暂无数据</div>
      </div>
      <div class="pagination">
        <div class="total">
          <span
            >已选择
            <span style="color: red">{{
              selection.length || cardSelection.length
            }}</span>
            条数据</span
          >
        </div>
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[50, 100, 200, 300, 400, 500]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin: 10px auto 0; text-align: right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></ElPagination>
        <div class="pageSize">
          <span
            >自定义条数
            <span
              ><el-input
                v-model="pageSize"
                type="number"
                style="width: 100px"
                clearable
                @blur="inputBlur"
              ></el-input
            ></span>
            条/页</span
          >
        </div>
      </div>
    </div>
  </div>
  <RightClickMenu
    ref="rightMenuRef"
    :show-copy-count="false"
    :show-copy-sub-shop-number="false"
    @on-change="rightChange"
  >
    <template #default>
      <div class="menu-item" @click="rightChange('order-number')">
        复制订单号
      </div>
    </template>
  </RightClickMenu>
  <el-dialog
    v-model="confirmDialogShow"
    :close-on-click-modal="false"
    title="确认"
  >
    <div
      class="production-client"
      style="margin-bottom: 10px; display: flex; align-items: center; gap: 8px"
    >
      <label style="white-space: nowrap" for="">生产端：</label>
      <ElSelect
        v-model="productionClientValue"
        clearable
        placeholder="请选择生产端"
        @change="handleProductionClientChange"
      >
        <ElOption
          v-for="(item, index) in productionClient"
          :key="index"
          :value="item.code"
          :label="`${item.remark}(${item.code})`"
        ></ElOption>
      </ElSelect>
    </div>
    <el-table
      v-if="productionClientValue === 'JOMALL'"
      height="400px"
      class="production-client-table"
      :data="confirmData"
      border
      highlight-current-row
      @current-change="currentChange"
    >
      <el-table-column
        label="序号"
        width="60"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column
        label="物流名称"
        align="center"
        prop="logisticsWayName"
      ></el-table-column>
      <el-table-column
        label="发货仓库"
        align="center"
        prop="warehouseName"
      ></el-table-column>
      <el-table-column
        label="物流编码"
        align="center"
        prop="logisticsWayCode"
      ></el-table-column>
      <el-table-column
        label="所在分区"
        align="center"
        prop="partition"
      ></el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="{ row }">
          <b v-if="row.status" style="color: green">成功</b>
          <b v-else-if="!row.status" style="color: red">失败</b>
        </template>
      </el-table-column>
      <el-table-column label="预计运费（$）" align="center" prop="payFreight">
        <!--        <template #default="{row}">-->
        <!--          {{row.payFreight || '0.00'}}-->
        <!--        </template>-->
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="confirmDialogShow = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
  <el-dialog
    v-model="logVisible"
    title="操作日志"
    width="1000px"
    :close-on-click-modal="false"
  >
    <template #header="{ titleId, titleClass }">
      <div style="display: flex" class="my-header">
        <div :id="titleId" :class="titleClass">操作日志</div>
        <div style="margin-left: 15px">
          <el-button
            :type="timeType === 'Asia/Shanghai' ? 'primary' : ''"
            size="small"
            link
            style="margin-left: 10px"
            @click="changeChinaTime('Asia/Shanghai')"
            >北京时间</el-button
          >
          <el-button
            :type="timeType === 'America/New_York' ? 'primary' : ''"
            size="small"
            link
            style="margin-left: 10px"
            @click="changeChinaTime('America/New_York')"
            >新泽西时间</el-button
          >
          <el-button
            :type="timeType === 'America/Los_Angeles' ? 'primary' : ''"
            size="small"
            link
            style="margin-left: 10px"
            @click="changeChinaTime('America/Los_Angeles')"
            >洛杉矶时间</el-button
          >
        </div>
      </div>
    </template>
    <LogList :log-list="logList" />
  </el-dialog>
  <FastProduction
    v-model:detail-visible="detailVisible"
    :current-status="status"
    :detail-data="detailData"
    :fast-key="fastKey"
    @on-success="handleSuccess"
    @close="fastClose"
  ></FastProduction>
  <PodMakeOrder
    v-model="podOrderVisible"
    :print-order="printOrder"
    :warehouse-list="warehouseList"
    @set-printer="handlePrinterChange"
    @set-warehouseId="handleWarehouseIdChange"
    @refresh="onFastRefresh"
  />
  <InspPackagOrder
    ref="InspPackagOrderRef"
    @refresh="onFastRefresh"
  ></InspPackagOrder>
  <ElDialog
    v-model="productionClientVisible"
    title="生产端"
    width="600px"
    :close-on-click-modal="false"
  >
    <template #header>
      <div class="dialog-header">
        <span style="margin-right: 8px; font-size: 18px">确认</span>
        <el-tooltip content="默认最低运费分派">
          <el-icon color="red">
            <WarningFilled />
          </el-icon>
        </el-tooltip>
      </div>
    </template>
    <div
      class="production-client"
      style="display: flex; align-items: center; gap: 8px"
    >
      <label style="white-space: nowrap" for="">生产端：</label>
      <ElSelect
        v-model="productionClientValue"
        clearable
        placeholder="请选择生产端"
      >
        <ElOption
          v-for="(item, index) in productionClient"
          :key="index"
          :value="item.code || ''"
          :label="`${item.remark}(${item.code})`"
        ></ElOption>
      </ElSelect>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="productionClientVisible = false">取消</ElButton>
        <ElButton type="primary" @click="submitConfirm">确认</ElButton>
      </div>
    </template>
  </ElDialog>

  <ResultInfo
    ref="resultRefs"
    :list="resultInfo"
    @confirm="resultConfirm"
  ></ResultInfo>

  <el-dialog
    v-model="isChangeWay"
    :close-on-click-modal="false"
    :title="wayDialogTitle"
  >
    <el-table
      ref="changeWayRef"
      v-loading="isChangeWayLoading"
      height="400px"
      class="production-client-table"
      :data="logisticsWayData"
      border
      highlight-current-row
      @row-click="(v:LogisticsData) =>rowClick(v, wayDialogTitle)"
    >
      <el-table-column
        label="序号"
        width="60"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column
        label="物流名称"
        align="center"
        prop="logisticsWayName"
      ></el-table-column>
      <el-table-column
        label="发货仓库"
        align="center"
        prop="warehouseName"
      ></el-table-column>
      <el-table-column
        label="物流编码"
        align="center"
        prop="logisticsWayCode"
      ></el-table-column>
      <el-table-column
        label="所在分区"
        align="center"
        prop="partition"
      ></el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="{ row }">
          <b v-if="row.status" style="color: green">成功</b>
          <b v-else-if="!row.status" style="color: red">失败</b>
        </template>
      </el-table-column>
      <el-table-column label="预计运费（$）" align="center" prop="payFreight">
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button :disabled="isChangeWayLoading" @click="cancelWayDialog">
        取消
      </el-button>
      <el-button
        :loading="isChangeWayLoading"
        type="primary"
        @click="changeWaySubmit(wayDialogTitle)"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
  <UpdateAddress
    v-if="updateAddVisible"
    v-model:form="currentRow"
    v-model:visible="updateAddVisible"
    :country-list="countryList"
    @success="search"
  ></UpdateAddress>
  <ElDialog
    v-model="exceptionDialogVisible"
    title="转为异常单"
    width="500px"
    :close-on-click-modal="false"
    @open="handleExceptionDialogOpen"
  >
    <ElForm ref="exceptionFormRef" :model="exceptionForm" label-width="100px">
      <ElFormItem
        label="异常类型"
        prop="exceptionType"
        :rules="
          status === 'EXCEPTION_ORDER'
            ? { required: true, message: '请选择异常类型' }
            : {}
        "
      >
        <ElSelect
          v-model="exceptionForm.exceptionType"
          style="width: 100%"
          placeholder="请选择异常类型"
          clearable
        >
          <ElOption
            v-for="type in exceptionTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem
        label="异常原因"
        prop="exceptionReason"
        :rules="
          status !== 'EXCEPTION_ORDER'
            ? { required: true, message: '请输入异常原因' }
            : {}
        "
      >
        <ElInput
          v-model="exceptionForm.exceptionReason"
          style="width: 100%"
          type="textarea"
          :rows="3"
          placeholder="请输入异常原因"
        />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="exceptionDialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleExceptionConfirm">
          确定
        </ElButton>
      </span>
    </template>
  </ElDialog>
  <el-dialog
    v-model="logisticsVisible"
    :close-on-click-modal="false"
    width="700px"
    title="更新物流信息"
  >
    <el-form
      v-if="logisticsVisible"
      ref="logisticsFormRef"
      label-width="100px"
      label-position="left"
      :model="logisticsForm"
    >
      <el-form-item prop="processNumber" label="物流处理号">
        <el-input
          v-model="logisticsForm.processNumber"
          placeholder="请输入物流处理号"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="trackingNumber" label="物流跟踪号">
        <el-input
          v-model="logisticsForm.trackingNumber"
          placeholder="请输入物流跟踪号"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="logisticsForm.trackingNumber"
        prop="expressSheetUrl"
        label="物流面单"
      >
        <el-upload accept=".pdf" action="" :before-upload="expressSheetUpload">
          <el-button type="primary">点击上传</el-button>
        </el-upload>
        <div v-if="logisticsForm.expressSheet" class="file">
          <span>{{ logisticsForm.expressSheet.name }}</span>
          <el-icon
            class="expressSheetClose"
            @click="logisticsForm.expressSheet = null"
          >
            <Close></Close>
          </el-icon>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="logisticsVisible = false">取消</el-button>
      <el-button type="primary" @click="logisticsSubmit"> 确定</el-button>
    </template>
  </el-dialog>
  <!-- 导出 -->
  <ElDialog
    v-model="exportVisible"
    title="导出选项"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form :model="exportForm" label-width="80px">
      <el-form-item label="" prop="resource">
        <el-radio-group v-model="exportForm.resource">
          <el-radio :label="0">导出本页</el-radio>
          <el-radio :label="1">导出选中</el-radio>
          <el-radio :label="2">全部</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportVisible = false">取消</el-button>
        <el-button
          :loading="exportLoading"
          type="primary"
          @click="submitExportForm"
          >确认</el-button
        >
      </span>
    </template>
  </ElDialog>
  <el-dialog v-model="dialogVisible" width="35%">
    <img :src="dialogImageUrl" alt="商品预览图片" />
  </el-dialog>
  <el-dialog title="物流轨迹" v-model="timeLineVisible" width="1000px">
    <el-timeline>
      <el-timeline-item
        v-for="(item, index) in timeLine"
        :key="index"
        :timestamp="item.time_utc"
        placement="top"
        :type="index == 0 ? 'primary' : ''"
      >
        <el-card>
          {{ item.description }}
        </el-card>
      </el-timeline-item>
    </el-timeline>
  </el-dialog>
</template>
<script setup lang="ts">
import { getUserMarkList } from '@/api/common'
// import { AnyObject } from '@/types/api/warehouse'
import { convertToChinaTime } from '@/utils/index'
import {
  InfoFilled,
  ArrowDown,
  CaretBottom,
  CaretTop,
  // Edit,
  Close,
  WarningFilled,
} from '@element-plus/icons-vue'
import {
  getCardOrderList,
  getOrderList,
  getOrderTabData,
  confirmOrderApi,
  changeExceptionOrderApi,
  cancelOrderApi,
  getOperationLogApi,
  downloadMaterialApi,
  updateExceptionOrderApi,
  printProductionOrderApi,
  getOrderDetailById,
  updateRemarkApi,
  getProductionClientApi,
  printPickingOrderApi,
  printPrintOrderApi,
  stockOutCheckApi,
  toBePickingApi,
  loadWarehouseListApi,
  getLogisticsCalculation,
  refreshMaterialApi,
  getTrackingNumberApi,
  getfaceSimplexFileApi,
  cancelLogisticsOrderApi,
  composingDesignImages,
  changeLogisticsApi,
  createLogisticsOrderApi,
  // updateLogisticsToPickingApi,
  updateLogisticsToArrangeApi,
  createLogisticsOrdersApi,
  syncReceiverAddress,
  refreshAddressApi,
  confirmProductApi,
  confirmProductToRiinApi,
  updateSelfLogistics,
  uploadExpressSheet,
  // handleExceptionOrderApi,
  applyForReplenishmentApi,
  replenishmentSuccessApi,
  toOutOfStockApi,
  arrangeFinishApi,
  getListCraftApi,
  batchDownloadApi,
  batchDownloadDownloadApi,
  batchDownloadDeleteApi,
  batchDownloadRecomposingApi,
  updateToWaitShipmentApi,
  exportPodUSInfo,
  getgetInterceptStateGroupList,
  interceptUpdateApi,
  rejectToApi,
  statusPushApi,
  completeDeliveryApi,
  get17TrackInfoApi,
  getAccountCodeByFactoryIdApi,
} from '@/api/podUsOrder'
import { BaseRespData } from '@/types/api'

import UpdateAddress from './components/updateAddress.vue'

import { getAllCountryApi } from '@/api/logistics.ts'

import TableView from '@/components/TableView.vue'
import {
  LogListData,
  PodUsOrderListData,
  ProductList,
  ProductionClient,
  SearchForm,
  Tab,
  WarehouseListData,
  cardImages,
  AddressInfo,
  LogisticsData,
  LogisticsFormData,
  CraftListData,
  ExportParams,
  InterceptStateGroupData,
} from '@/types/api/podUsOrder'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from '@/utils/hooks/useValue'
import { showConfirm } from '@/utils/ui'
import { DocumentCopy, EditPen } from '@element-plus/icons-vue'
import { Column, ElFormItem } from 'element-plus'
import { computed, onMounted, ref, nextTick, reactive } from 'vue'
import FastProduction from './FastProduction.vue'
import { filePath } from '@/api/axios'
import PodMakeOrder from './PodMakeOrder.vue'
import InspPackagOrder from './InspPackagOrder.vue'
import { OrderData } from '@/types/api/podMakeOrder'
import useLodop, { LODOPObject } from '@/utils/hooks/useLodop'
import dayjs from 'dayjs'
import RightClickMenu from '@/components/RightClickMenu.vue'
import ResultInfo from './components/ResultInfo.vue'
import { isArray, isString } from '@/utils/validate'
import platformJson from '../../../json/platform.json'
import { getToken } from '@/api/axios'
import usePermissionBtnStore from '@/store/permission'
const permissionBtns = usePermissionBtnStore()
import {
  useRouter,
  type NavigationGuardNext,
  type RouteLocationNormalized,
} from 'vue-router'
declare global {
  interface Window {
    ActiveXObject: {
      new (type: string): XMLHttpRequest
    }
    VBS_BinaryToArray: {
      (data: unknown): { toArray(): number[] }
    }
  }

  interface XMLHttpRequest {
    responseBody?: unknown
  }
}
const tabsNav = ref<Tab[]>()

const countryList = ref([])
const currentRow = ref<AddressInfo>({
  receiverName: '',
  receiverPhone: '',
  receiverCountry: '',
  receiverProvince: '',
  receiverCity: '',
  receiverDistrict: '',
  receiverAddress1: '',
  receiverAddress2: '',
  receiverPostCode: '',
})
const exportLoading = ref(false)
const exportVisible = ref(false)
const exportForm = ref({
  resource: '',
})

const exportData = () => {
  exportVisible.value = true
}
const submitExportForm = async () => {
  if (exportForm.value.resource === '') {
    return ElMessage.error('请选择导出类型')
  }
  exportLoading.value = true
  const resourceType = Number(exportForm.value.resource)
  const params: ExportParams = {
    exportAll: false,
    idList: [],
    status: status.value,
  }
  // 使用函数封装映射逻辑
  const mapIds = (items: PodUsOrderListData[]) =>
    items.map((el) => Number(el.id))
  switch (resourceType) {
    case 0:
      params.idList = mapIds(tableData.value as PodUsOrderListData[])
      break
    case 1:
      params.idList = mapIds(selection.value)
      break
    case 2:
      params.exportAll = true
      params.idList = undefined
      break
    default:
      console.error('未知的资源类型:', resourceType)
  }
  try {
    const res = await exportPodUSInfo({
      ...params,
      ...(resourceType === 2 ? searchForm.value : {}),
    })
    window.open(filePath + res.message, '_blank')
    exportVisible.value = false
    exportLoading.value = false
  } catch (e) {
    exportVisible.value = false
    exportLoading.value = false
  }
}
const updateAddVisible = ref(false)
const initPageSize = ref(50)
const logisticsVisible = ref(false)
const logisticsFormRef = ref()
const logistics = {
  processNumber: '',
  trackingNumber: '',
  expressSheetUrl: '',
  expressSheet: null,
}
const logisticsForm = ref<LogisticsFormData>(logistics)
const resultRefs = ref<InstanceType<typeof ResultInfo> | null>(null)
const confirmDialogShow = ref(false)
const tifDownloadLoading = ref(false)
const pngDownloadLoading = ref(false)
const isChangeWay = ref(false)
const confirmData = ref([])
const logisticsWayData = ref([])
const searchVisible = ref(false)
const confirmSelectionData = ref<LogisticsData[]>([])
const confirmRowData = ref<ProductList | null>(null)
const status = ref(localStorage.getItem('podUsStatus') || 'TO_BE_CONFIRMED')
const interceptionStatus = ref<{
  shipment: Record<string, number>
  production: Record<string, number>
}>({
  shipment: {},
  production: {},
})

const detailData = ref({})
const [searchForm, resetSearchForm] = useValue<SearchForm>({
  timeType: 1,
  shopNumber: '',
  shipmentType: '',
  userMark: '',
  processNumber: '',
  baseSku: '',
  factoryOrderNumber: '',
  sku: '',
  factorySubOrderNumber: '',
  status: '',
  customizedQuantity: '',
  multi: null,
  startTime: null,
  endTime: null,
  exceptionHandling: undefined,
  platform: '',
  productionClient: '',
  warehouseId: '',
  thirdSkuCode: '',
  supplierProductNo: '',
  batchArrangeNumber: '',
  craftCode: '',
  thirdStockSku: '',
})
const exceptionStatus = ref(1)
const interceptCurrent = ref(1)
const interceptStatus = ref(0)
const userMarkList = ref<string[]>([])
const selection = ref<PodUsOrderListData[]>([])
const currentItem = ref<PodUsOrderListData | null>(null)
const pickerOptions = {
  shortcuts: [
    {
      text: '今日',
      value: () => getDateRange(0),
    },
    {
      text: '昨天',
      value: () => getDateRange(1),
    },
    {
      text: '最近7天',
      value: () => getDateRange(6),
    },
    {
      text: '最近14天',
      value: () => getDateRange(13),
    },
    {
      text: '最近30天',
      value: () => getDateRange(29),
    },
    {
      text: '本周',
      value: () => getWeekRange(0),
    },
    {
      text: '上周',
      value: () => getWeekRange(1),
    },
    {
      text: '本月',
      value: () => getMonthRange(0),
    },
    {
      text: '上月',
      value: () => getMonthRange(1),
    },
    {
      text: '历史',
      value: () => {
        const end = dayjs().endOf('day').toDate()
        const start = dayjs('2000-01-01').startOf('day').toDate()
        return [start, end]
      },
    },
    {
      text: '转换中国时间',
      value: () => {
        console.log(3469, timeRange.value)
        if (timeRange.value?.length) {
          const end = timeRange.value[1] ?? ''
          const start = timeRange.value[0] ?? ''
          return [convertToChinaTime(start), convertToChinaTime(end)]
        } else {
          return getDateRange(0)
        }
      },
    },
  ],
}
const filteredImages = (imageAry: string | null) => {
  if (!imageAry) return []
  try {
    const parsed = JSON.parse(imageAry)
    return Array.isArray(parsed)
      ? parsed.filter((el: { title: string }) => el.title)
      : []
  } catch {
    return []
  }
}
const timeRange = ref<string[]>([])
const getDateRange = (days = 0, type: 'past' | 'future' = 'past') => {
  const end = dayjs()
  const start =
    type === 'past' ? end.subtract(days, 'day') : end.add(days, 'day')
  return [start.startOf('day').toDate(), end.endOf('day').toDate()]
}

const getMonthRange = (months = 0, type: 'past' | 'future' = 'past') => {
  const now = dayjs()
  const start =
    type === 'past' ? now.subtract(months, 'month') : now.add(months, 'month')
  return [start.startOf('month').toDate(), start.endOf('month').toDate()]
}

const getWeekRange = (weeks = 0, type: 'past' | 'future' = 'past') => {
  const now = dayjs()
  const start =
    type === 'past' ? now.subtract(weeks, 'week') : now.add(weeks, 'week')
  return [start.startOf('week').toDate(), start.endOf('week').toDate()]
}
const handleRefreshAddress = async (row: PodUsOrderListData) => {
  try {
    await showConfirm('确定刷新地址吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  await refreshAddressApi([row.id])
  await ElMessageBox.alert(
    '请修改/刷新地址后取消物流或者更换物流在重新创建物流订单、获取跟踪号、获取打印面单',
    '提示',
    {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      showCancelButton: true,
    },
  )
}
const handleUpdateAddress = async (row: PodUsOrderListData) => {
  const { data } = await getAllCountryApi()
  countryList.value = data
  currentRow.value = JSON.parse(JSON.stringify(row))
  updateAddVisible.value = true
}
// 批量下载 下载
const handleDownload = async (row: PodUsOrderListData, type: string) => {
  try {
    await showConfirm('确定下载吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const url =
      type === 'png'
        ? filePath + row.url
        : `https://ps.jomalls.com/tiff/` + row.tiffUrl

    if (type === 'tiff') {
      window.open(url, '_blank')
      tifDownloadLoading.value = false
    } else {
      const response = await fetch(url)
      if (!response.ok) {
        throw new Error('网络响应错误')
      }
      const blob = await response.blob()
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = url ? url.split('/').pop() || 'download' : 'download'
      link.click()
    }

    await batchDownloadDownloadApi({ id: row.id, type })
    ElMessage.success('操作成功')
    search()
    loadTabData()
  } catch (e) {
    ElMessage.error('下载失败')
    console.error(e)
  } finally {
    loading.close()
  }
}
// 批量下载 删除
const handleBatchDelete = async (type: string, id?: string) => {
  if (type === 'batch' && selection.value.length === 0) {
    ElMessage.error('请选择要删除的数据')
    return
  }
  try {
    await showConfirm('确定删除吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await batchDownloadDeleteApi({
      ids:
        type === 'batch'
          ? selection.value.map((item) => item.id).join(',')
          : id,
    })
    if (res.code !== 200) return
    ElMessage.success(res.message)
    search()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
// 批量下载 重新排版
const handleReComposingDesign = async (row: PodUsOrderListData) => {
  try {
    await showConfirm('确定重新排版吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  reComposingLoadingMap[row.id] = true

  try {
    const res = await batchDownloadRecomposingApi({ id: row.id })
    if (res.code !== 200) return
    ElMessage.success(res.message)
    search()
    loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    reComposingLoadingMap[row.id] = false
  }
}
const tableColumns = computed(() => {
  if (status.value === 'BATCH_DOWNLOAD') {
    return [
      {
        label: '批次号',
        prop: 'batchArrangeNum',
        width: 150,
        align: 'center',
      },
      {
        label: '下载状态',
        slot: 'downloadStatus',
        width: 100,
        prop: 'downloadStatus',
        align: 'center',
      },
      {
        label: '订单数量',
        prop: 'productNum',
        width: 100,
        align: 'center',
      },
      {
        label: '素材数量',
        width: 120,
        prop: 'materialNum',
        align: 'center',
      },
      {
        label: '创建人',
        width: 100,
        prop: 'employeeAccount',
        align: 'center',
      },
      {
        label: '失败原因',
        minWidth: 300,
        prop: 'failReason',
        slot: 'failReason',
        align: 'left',
      },
      {
        label: '创建时间',
        width: 200,
        prop: 'createTime',
        slot: 'createTime',
        align: 'center',
      },
      {
        label: '完成时间',
        width: 200,
        prop: 'finishTime',
        slot: 'finishTime',
        align: 'center',
      },
      // {
      //   label: '失败时间',
      //   width: 250,
      //   prop: 'failTime',
      //   slot: 'failTime',
      //   align: 'center',
      // },
      {
        label: '操作',
        slot: 'operate',
        width: 300,
        align: 'center',
        fixed: 'right',
        prop: 'operate',
      },
    ]
  }
  return [
    {
      label: '序号',
      prop: 'serialNumber',
      slot: 'serialNumber',
      width: 60,
      align: 'center',
    },
    {
      label: '商品',
      prop: 'goods',
      slot: 'goods',
      minWidth: 800,
    },
    {
      label: '订单详情',
      prop: 'orderDetail',
      slot: 'orderDetail',
      width: 300,
    },
    {
      label: '订单金额($)',
      slot: 'price',
      width: 110,
      prop: 'price',
      align: 'left',
    },
    {
      label: '时间',
      slot: 'time',
      width: 170,
      prop: 'time',
      align: 'left',
    },
    // {
    //   label: '内部便签',
    //   slot: 'innerLabel',
    //   width: 300,
    //   prop: 'innerLabel',
    // },
    {
      label: '异常原因',
      width: 250,
      prop: 'exceptionReason',
      slot: 'exceptionReason',
      align: 'left',
    },
    {
      label: '操作',
      slot: 'operate',
      width: 80,
      align: 'center',
      fixed: 'right',
      prop: 'operate',
    },
  ]
})
const rightMenuRef = ref()
const rightClick = (e: MouseEvent) => {
  rightMenuRef.value.setPosition({
    x: e.clientX,
    y: e.clientY,
  })
}

const handleSelectionChange = (val: PodUsOrderListData[]) => {
  selection.value = val
  // 当清空选择时，清除补货校验成功的状态
  if (val.length === 0) {
    stockOutSuccessIds.value = []
  }
}

const asyncOrderAddress = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  try {
    await showConfirm('确定同步收货地址吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  const ids = selection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await syncReceiverAddress(ids)
    if (res.code !== 200) return
    await ElMessageBox.alert('同步收货地址成功，请刷新查看。', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      showCancelButton: true,
    })
    search()
    await loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

const changeTab = (item: Tab) => {
  status.value = item.status || ''
  localStorage.setItem('podUsStatus', item.status as string)

  // 如果切换到INTERCEPTED状态，设置默认的exceptionStatus
  if (item.status === 'INTERCEPTED' && !interceptCurrent.value) {
    interceptCurrent.value = 1
  }

  selection.value = []
  cardSelection.value = []
  stockOutSuccessIds.value = []
  search()
}
const onCellStyle = ({ column }: { column: Column }) => {
  if (
    column.property === 'orderDetail' ||
    column.property === 'price' ||
    column.property === 'time' ||
    column.property === 'innerLabel' ||
    column.property === 'goods' ||
    column.property === 'exceptionReason'
  ) {
    return { verticalAlign: 'top' }
  }
}
const onCellClassName = ({ column }: { column: Column }) => {
  if (column.property === 'exceptionReason') {
    return 'exception-reason'
  }
}

// 获取Tab信息
const loadTabData = async () => {
  try {
    const res = await getOrderTabData()
    tabsNav.value = res.data

    // 获取拦截数量
    const statusRes = await getgetInterceptStateGroupList()
    // const statusRes = { data: {} }
    interceptionStatus.value = statusRes.data as {
      shipment: Record<string, number>
      production: Record<string, number>
    }

    // 在 已完成 后面添加 拦截 标签页
    const completeIndex = tabsNav.value.findIndex(
      (item) => item.status === 'COMPLETE',
    )

    // 发货拦截数量
    const shipmentCount = (statusRes.data as InterceptStateGroupData)?.shipment
      ? Object.values(
          (statusRes.data as InterceptStateGroupData).shipment,
        ).reduce((sum: number, value: unknown) => sum + (Number(value) || 0), 0)
      : 0

    // 生产拦截数量
    const productionCount = (statusRes.data as InterceptStateGroupData)
      ?.production
      ? Object.values(
          (statusRes.data as InterceptStateGroupData).production,
        ).reduce((sum: number, value: unknown) => sum + (Number(value) || 0), 0)
      : 0

    tabsNav.value.splice(completeIndex + 1, 0, {
      status: 'INTERCEPTED',
      statusName: '拦截',
      quantity: shipmentCount + productionCount,
    })
  } catch (error) {
    // showError(error)
  }
}
const getUserMark = async () => {
  try {
    const res = await getUserMarkList()
    userMarkList.value = res.data
  } catch (error) {
    //showError(error)
  }
}

const {
  loading,
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  initPageSize: initPageSize.value,
  query: (page, pageSize) => {
    // 批量下载
    if (status.value === 'BATCH_DOWNLOAD') {
      return batchDownloadApi(page, pageSize).then((res) => {
        return res.data
      }) as never
    } else if (
      status.value !== 'IN_PRODUCTION' &&
      status.value !== 'PICKING' &&
      status.value !== 'TO_BE_REPLENISHMENT' &&
      status.value !== 'TO_BE_ARRANGE'
    ) {
      return getOrderList(
        {
          ...searchForm.value,
          startTime:
            timeRange.value && timeRange.value.length > 0
              ? timeRange.value[0]
              : null,
          endTime:
            timeRange.value && timeRange.value.length > 0
              ? timeRange.value[1]
              : null,
          status: status.value === 'INTERCEPTED' ? '' : status.value,
          exceptionHandling:
            status.value === 'EXCEPTION_ORDER'
              ? exceptionStatus.value || undefined
              : undefined,
          interceptStatus:
            status.value === 'INTERCEPTED' ? interceptStatus.value : '',
        },
        page,
        pageSize,
      ).then((res) => res.data) as never
    } else {
      return getCardOrderList(
        {
          ...searchForm.value,
          startTime:
            timeRange.value && timeRange.value.length > 0
              ? timeRange.value[0]
              : null,
          endTime:
            timeRange.value && timeRange.value.length > 0
              ? timeRange.value[1]
              : null,
          status: status.value,
          interceptStatus: '',
        },
        page,
        pageSize,
      ).then((res) => res.data) as never
    }
  },
})

watch(
  () => [...(tableData.value as PodUsOrderListData[])], // 创建新数组避免直接修改原始数据
  (newData) => {
    if (!newData?.length) return

    newData.forEach((order) => {
      // 使用可选链和空值合并简化判断
      order.productList?.forEach((product) => {
        if (!product.previewImgs && product.imageAry) {
          try {
            product.previewImgs =
              JSON.parse(product.imageAry)?.filter(
                (el: { title: string }) => el.title,
              ) || []
          } catch (error) {
            console.error('JSON解析失败:', error)
            product.previewImgs = []
          }
        }
      })
    })
  },
  { deep: true, immediate: true }, // 添加immediate确保初始化时执行
)

const search = () => {
  selection.value = []
  cardSelection.value = []
  refresh()
}
const currentChange = (row: LogisticsData) => {
  if (row) {
    confirmSelectionData.value = [row]
  }
}
const handleProductionClientChange = async (v: string) => {
  if (v !== 'RIIN') {
    if (confirmRowData.value) {
      const { data } = await getLogisticsCalculation(confirmRowData.value?.id)
      confirmData.value = data
    }
  }
}
const downloadFacebook = async (row: string) => {
  window.open(filePath + row, '_blank')
}

//确认生产
async function confirmProduct() {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }

  try {
    await showConfirm('确定生产吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const ids = selection.value.map((el) => el.id)
    const { code, data } = await confirmProductApi([...ids])
    if (code === 200) {
      resultInfo.value = data || []
      resultInfo.value =
        (data as {
          id: string | number
          status: boolean
          factoryOrderNumber?: string
          message: string
        }[]) || []
      if (
        Array.isArray(data) &&
        (data as { status: boolean }[]).some((item) => !item.status)
      ) {
        resultRefs.value?.showDialog()
      } else {
        search()
        loadTabData()
      }
    }
    ElMessage.success('操作成功')

    // search()
    // await loadTabData()
  } catch {
    resultInfo.value = []
    return
  }
}

//转至锐印
async function confirmProductToRiin() {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  try {
    await showConfirm('确认转至锐印(Riin)生产吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const ids = selection.value.map((el) => el.id)
    const { code, data } = await confirmProductToRiinApi([...ids])
    if (code === 200) {
      resultInfo.value = data || []
      resultInfo.value =
        (data as {
          id: string | number
          status: boolean
          factoryOrderNumber?: string
          message: string
        }[]) || []
      if (
        Array.isArray(data) &&
        (data as { status: boolean }[]).some((item) => !item.status)
      ) {
        resultRefs.value?.showDialog()
      } else {
        search()
        loadTabData()
      }
    }
    ElMessage.success('操作成功')

    // search()
    // await loadTabData()
  } catch {
    resultInfo.value = []
    return
  }
}

const handleConfirm = async () => {
  if (!productionClientValue.value) {
    return ElMessage.warning('请选择生产端')
  }
  if (productionClientValue.value !== 'RIIN') {
    if (confirmSelectionData.value.length !== 1) {
      return ElMessage.warning('请选择一条物流方式')
    }
    if (confirmSelectionData.value.some((el) => !el.status)) {
      return ElMessage.warning('请选择状态为成功的物流方式')
    }
  }

  const id = confirmRowData.value?.id
  const res = await confirmOrderApi(
    [Number(id)],
    productionClientValue.value,
    'customize',
    confirmSelectionData.value[0] || null,
  )
  if (res.code !== 200) return
  ElMessage.success('操作成功')
  confirmDialogShow.value = false
  search()
  await loadTabData()
}
const copy = (text: string) => {
  try {
    navigator.clipboard.writeText(text)
    ElMessage.success('复制成功')
  } catch (err) {
    console.error('复制失败:', err)
  }
}
const handleUpdateRemark = async (item: ProductList) => {
  ElMessageBox.prompt('请输入备注', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern: /^.{1,2000}$/,
    inputErrorMessage: '请输入备注',
  }).then(async ({ value }) => {
    const loading = ElLoading.service({
      fullscreen: true,
      text: '操作中...',
      background: 'rgba(0, 0, 0, 0.3)',
    })
    try {
      const res = await updateRemarkApi(item.id, value)
      if (res.code !== 200) return
      ElMessage.success('操作成功')
      search()
    } catch (e) {
      console.error(e)
    } finally {
      loading.close()
    }
  })
}
const productionClientValue = ref('')
const productionClient = ref<ProductionClient[]>()
const productionClientVisible = ref(false)
// const confirmOrder = async () => {
//   if (selection.value.length === 0) {
//     return ElMessage.warning('请选择数据')
//   }
//   productionClientValue.value = ''
//   productionClientVisible.value = true
// }

const downloadTif = async (type: string) => {
  if (!cardSelection.value.length) {
    return ElMessage.warning('请选择数据')
  }
  if (type === 'tiff') {
    tifDownloadLoading.value = true
  } else {
    pngDownloadLoading.value = true
  }
  try {
    const res = await composingDesignImages(
      cardSelection.value.map((el) => el.id),
      type,
    )
    const url =
      type === 'tiff'
        ? `https://ps.jomalls.com/tiff/` + res.message
        : filePath + res.message
    if (type === 'tiff') {
      window.open(url, '_blank')
      tifDownloadLoading.value = false
    } else {
      fetch(url)
        .then((response) => {
          // 确保响应是 OK
          if (!response.ok) {
            throw new Error('网络响应错误')
          }
          // 返回图片的二进制数据（Blob）
          return response.blob()
        })
        .then((blob) => {
          const a = document.createElement('a')
          a.href = window.URL.createObjectURL(blob)
          a.target = '_blank'
          a.download = (res.message as string).split('/')[
            (res.message as string).split('/').length - 1
          ]
          a.click()
          pngDownloadLoading.value = false
        })
        .catch((error) => {
          console.error('下载图片时出错:', error)
          pngDownloadLoading.value = false
        })
    }
  } catch (e) {
    console.log(e)
    if (type === 'tiff') {
      tifDownloadLoading.value = false
    } else {
      pngDownloadLoading.value = false
    }
  }
}
const downloadTifItem = async (type: string, id: number) => {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await composingDesignImages([id], type)
    const url =
      type === 'tiff'
        ? `https://ps.jomalls.com/tiff/` + res.message
        : filePath + res.message
    if (type === 'tiff') {
      window.open(url, '_blank')
    } else {
      fetch(url)
        .then((response) => {
          // 确保响应是 OK
          if (!response.ok) {
            throw new Error('网络响应错误')
          }
          // 返回图片的二进制数据（Blob）
          return response.blob()
        })
        .then((blob) => {
          const a = document.createElement('a')
          a.href = window.URL.createObjectURL(blob)
          a.target = '_blank'
          a.download = (res.message as string).split('/')[
            (res.message as string).split('/').length - 1
          ]
          a.click()
          pngDownloadLoading.value = false
        })
        .catch((error) => {
          console.error('下载图片时出错:', error)
          pngDownloadLoading.value = false
        })
    }
  } catch (e) {
    console.log(e)
  } finally {
    loading.close()
  }
}
const loadProductionClient = async () => {
  try {
    const res = await getProductionClientApi()
    if (res.code !== 200) return
    productionClient.value = res.data
  } catch (e) {
    console.error(e)
  }
}
const submitConfirm = async () => {
  const ids = selection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await confirmOrderApi(
      ids,
      productionClientValue.value,
      'minimumCost',
    )
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    productionClientVisible.value = false
    search()
    loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const updateOrder = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  try {
    await showConfirm('确定转至待确认吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  const ids = selection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await updateExceptionOrderApi(ids)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const assignOrder = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  currentOrderIds.value = selection.value.map((item) => item.id)
  exceptionDialogVisible.value = true
}
// const handleExceptionOrder = async () => {
//   if (selection.value.length === 0) {
//     return ElMessage.warning('请选择数据')
//   }
//   try {
//     await showConfirm('确定处理异常吗?', {
//       confirmButtonText: '确认',
//       cancelButtonText: '取消',
//       type: 'warning',
//     })
//   } catch {
//     return
//   }
//   const orderIds = selection.value.map((item) => item.id)
//   const loading = ElLoading.service({
//     fullscreen: true,
//     text: '操作中...',
//     background: 'rgba(0, 0, 0, 0.3)',
//   })
//   try {
//     const res = await handleExceptionOrderApi(orderIds)
//     if (res.code !== 200) return
//     ElMessage.success('操作成功')
//     search()
//     loadTabData()
//   } catch (e) {
//     console.error(e)
//   } finally {
//     loading.close()
//   }
// }
const printProductionOrder = async () => {
  if (cardSelection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  const orderIds = cardSelection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await printProductionOrderApi(orderIds)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    window.open(filePath + res.message)
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const printPickingOrder = async () => {
  if (cardSelection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  const orderIds = cardSelection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await printPrintOrderApi(orderIds)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    window.open(filePath + res.message)
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const pickingComplete = async () => {
  if (cardSelection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  try {
    await ElMessageBox.confirm('确定完成拣胚完成吗?', '提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
    })
  } catch {
    return
  }
  const orderIds = cardSelection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await printPickingOrderApi(orderIds)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
    cardSelection.value = []
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const toOutOfStock = async () => {
  if (cardSelection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  const orderIds = cardSelection.value.map((item) => item.podJomallOrderUsId)
  try {
    await ElMessageBox.confirm('确定转至缺货吗?', '提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await toOutOfStockApi(orderIds)
    if (res.code !== 200) return
    search()
    loadTabData()
    cardSelection.value = []
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const exceptionTypes = [
  { value: '1', label: '客户' },
  { value: '2', label: '工厂' },
]
const exceptionDialogVisible = ref(false)
const currentOrderIds = ref<number[]>([])
const exceptionForm = ref({
  exceptionType: '',
  exceptionReason: '',
})
const exceptionFormRef = ref()
const changeExceptionOrder = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  currentOrderIds.value = selection.value.map((item) => item.id)
  exceptionDialogVisible.value = true
}
const inputBlur = () => {
  if (!pageSize.value || Number(pageSize.value) <= 0) {
    pageSize.value = initPageSize.value
  }
  search()
}
const handleExceptionConfirm = async () => {
  try {
    await exceptionFormRef.value.validate()
  } catch {
    return
  }

  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  const url =
    status.value === 'EXCEPTION_ORDER'
      ? 'factory/podJomallOrderUs/distributionExceptionOrders'
      : 'factory/podJomallOrderUs/exceptionOrders'
  try {
    const res = await changeExceptionOrderApi(
      url,
      currentOrderIds.value,
      exceptionForm.value.exceptionType,
      exceptionForm.value.exceptionReason,
    )
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
    exceptionDialogVisible.value = false
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const handleExceptionDialogOpen = () => {
  exceptionFormRef.value.resetFields()
}
const cancelOrder = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  const orderIds = selection.value.map((item) => item.id)
  ElMessageBox.prompt('请填写取消原因', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern: /^.{1,2000}$/,
    inputErrorMessage: '请输入取消原因',
  }).then(async ({ value }) => {
    const loading = ElLoading.service({
      fullscreen: true,
      text: '操作中...',
      background: 'rgba(0, 0, 0, 0.3)',
    })
    try {
      const res = await cancelOrderApi(orderIds, value)
      if (res.code !== 200) return
      ElMessage.success('操作成功')
      search()
      loadTabData()
    } catch (e) {
      console.error(e)
    } finally {
      loading.close()
    }
  })
}
const cardSelection = ref<ProductList[]>([])
const cardClick = (data: ProductList) => {
  const status = isSelectStatused(data)

  if (status) {
    cardSelection.value = cardSelection.value.filter(
      (item: ProductList) => item.id !== data.id,
    )
  } else {
    cardSelection.value.push(data as ProductList)
  }
}
const isSelectStatused = (data: ProductList) => {
  const index = cardSelection.value.findIndex(
    (item: ProductList) => item.id === data.id,
  )
  return index !== -1
}
const rightChange = async (code: string) => {
  const flat =
    status.value !== 'IN_PRODUCTION' &&
    status.value !== 'PICKING' &&
    status.value !== 'TO_BE_REPLENISHMENT' &&
    status.value !== 'TO_BE_ARRANGE'
  if (code === 'select-all') {
    if (flat) {
      tableRef.value?.toggleAllSelection()
    } else {
      cardSelection.value = JSON.parse(JSON.stringify(tableData.value))
    }
  } else if (code === 'cancel-select') {
    if (flat) {
      tableRef.value?.clearSelection()
    } else {
      cardSelection.value = []
    }
  } else if (code === 'copy_shopNumber') {
    const str = (tableData.value as ProductList[] | PodUsOrderListData[])
      .map((item) => item?.shopNumber)
      .join()
    navigator.clipboard.writeText(str)
    ElMessage.success('复制成功')
  } else if (code === 'order-number') {
    const str = (tableData.value as ProductList[] | PodUsOrderListData[])
      .map((item) => item?.factoryOrderNumber)
      .join()
    navigator.clipboard.writeText(str)
    ElMessage.success('复制成功')
  }
}
const currentImage = ref('')
const handleChangeImages = (item: cardImages | null, cardItem: ProductList) => {
  currentImage.value = item?.url || ''
  cardItem.variantImage =
    item?.url || JSON.parse(cardItem.imageAry || '')[0].url
}
const detailVisible = ref(false)
const fastKey = ref('')
const onFastProduction = () => {
  detailVisible.value = true
  fastKey.value = 'fastProduction'
  detailData.value = {}
}
// 下载稿件
const downloadMaterial = async () => {
  let selectedIds = []
  if (
    status.value === 'IN_PRODUCTION' ||
    status.value === 'PICKING' ||
    status.value === 'TO_BE_REPLENISHMENT'
  ) {
    selectedIds = cardSelection.value
      .map((item: ProductList) => item.id)
      .filter((id): id is number => id !== undefined)
  } else {
    selectedIds = (selection.value as PodUsOrderListData[])
      .map((item) => item?.productList)
      .flat()
      .map((item) => item?.id)
      .filter((id): id is number => id !== undefined)
  }
  if (selectedIds.length === 0) {
    return ElMessage({
      message: '请选择订单',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await downloadMaterialApi(selectedIds)
    if (res.code !== 200) return
    window.open(filePath + res.message)
  } catch (e) {
    // showError(e)
    console.error(e)
  } finally {
    loading.close()
  }
}
// 下载单个素材
const downloadMaterialItem = async (data: PodUsOrderListData) => {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await downloadMaterialApi([data.id])
    if (res.code !== 200) return
    window.open(filePath + res.message)
  } catch (e) {
    // showError(e)
    console.error(e)
  } finally {
    loading.close()
  }
}

// 排单完成
const arrangeFinish = async () => {
  const selectedIds = cardSelection.value.map((item) => item.id)

  if (selectedIds.length === 0) {
    return ElMessage({
      message: '请选择订单',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }
  try {
    await ElMessageBox.confirm('确定排单完成吗?', '提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await arrangeFinishApi(selectedIds)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
interface timeLineType {
  time_iso?: string
  time_utc?: string
  description?: string
}
const timeLineVisible = ref(false)
const timeLine = ref<timeLineType[]>([])
const logTrajectory = async (row: { id: string }) => {
  const { data } = await get17TrackInfoApi({ id: row.id })
  const res = data.accepted[0]?.track_info?.tracking
  timeLine.value = res?.providers[0]?.events
  // if (data.rejected?.length) {
  //   console.log(data.rejected[0].error.message)
  //   throw Error(data.rejected[0].error.message)
  // }
  timeLineVisible.value = true
}

const logList = ref<LogListData[]>([])
const logVisible = ref(false)
const operationLog = async (id: number, e: MouseEvent | null) => {
  e && e.stopPropagation()
  try {
    const res = await getOperationLogApi(id)
    if (res.code !== 200) return
    logList.value = res.data.map((el) => {
      return {
        ...el,
        local: 'BeiJing',
      }
    })
    tempChinaLogs.value = [...logList.value]

    logVisible.value = true
  } catch (e) {
    console.error(e)
  }
}
const handleSuccess = () => {
  loadTabData()
  search()
}
const fastClose = () => {
  loadTabData()
  detailVisible.value = false
}
const podOrderVisible = ref(false)
const printPodOrder = async () => {
  const lodop = getCLodop(null, null)
  if (!lodop) return

  sheetPrinter.value = lodop.GET_PRINTER_NAME(0)
  podOrderVisible.value = true
}

const InspPackagOrderRef = ref()

// const inspPackagOrder = async () => {
//   const lodop = getCLodop(null, null)
//   if (!lodop) return

//   sheetPrinter.value = lodop.GET_PRINTER_NAME(0)
//   InspPackagOrderRef?.value.open()
// }

/**
 * @description: 创建物流、获取跟踪号、获取打印面单、更改物流、取消物流订单
 */

const getOrderByIdApi = async (type: string) => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }

  const operationMap: {
    [key: string]: {
      message: string
      Fn: (orderIds: (string | number)[]) => Promise<BaseRespData<never>>
    }
  } = {
    createLogisticsOrder: {
      message: '创建物流订单',
      Fn: createLogisticsOrdersApi,
    },
    getTrackingNumber: { message: '获取跟踪号', Fn: getTrackingNumberApi },
    getPrintOrder: { message: '获取打印面单', Fn: getfaceSimplexFileApi },
    cancelLogisticsOrder: {
      message: '取消物流订单',
      Fn: cancelLogisticsOrderApi,
    },
  }
  let loading
  const operation = operationMap[type]
  if (operation) {
    try {
      await showConfirm(`确定对该订单 ${operation.message}?`, {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })

      const ids = selection.value.map((el) => el.id)

      loading = ElLoading.service({
        fullscreen: true,
        text: '操作中...',
        background: 'rgba(0, 0, 0, 0.3)',
      })

      const res = await operation.Fn(ids)
      if (res.code === 200) {
        if (isArray(res.data)) {
          resultInfo.value = res.data || []
          resultInfo.value =
            (res.data as {
              id: string | number
              status: boolean
              factoryOrderNumber?: string
              message: string
            }[]) || []
          resultRefs.value?.showDialog()
        } else if (isString(res.data)) {
          window.open(filePath + res.data)
        }
      } else {
        ElMessage.error(res.message)
      }
    } catch (e) {
      resultInfo.value = []
      console.error(e)
    } finally {
      loading && loading.close()
    }
  } else {
    ElMessage.warning('未知操作类型')
  }
}

// 驳回
const rejectOrder = async (type: string) => {
  if (selection.value.length === 0 && cardSelection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })

  try {
    const { value } = await ElMessageBox.prompt('驳回确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputType: 'textarea',
      inputPlaceholder: '驳回原因',
      inputPattern: /\S+/, // 非空验证，至少一个非空白字符
      inputErrorMessage: '内容不能为空',
    })

    const res = await rejectToApi({
      orderStatus: type,
      productList: selection.value.length
        ? selection.value.flatMap(
            (item: PodUsOrderListData) => item.productList || [],
          )
        : cardSelection.value,
      reasonStr: value,
    })
    if (res.code !== 200) return

    resultInfo.value = res.data
    resultInfo.value = resultInfo.value.filter((item) => !item.status)
    if (!resultInfo.value.length) {
      ElMessage.success('操作成功')
      search()
      loadTabData()
    } else {
      resultRefs.value?.showDialog()
    }
  } catch (e) {
    console.log(e)
  } finally {
    loading.close()
  }
}

const handleStockOut = async (row: PodUsOrderListData) => {
  currentItem.value = row
  wayDialogTitle.value = `切换物流(当前物流方式：${row.logisticsWayName})`

  isChangeWay.value = true
  try {
    const { data } = await getLogisticsCalculation(row.id as number)
    logisticsWayData.value = data
  } catch (error) {
    console.error(error)
  }
}
//展示返回结果
const resultInfo = ref<
  {
    id: string | number
    status: boolean
    factoryOrderNumber?: string
    message: string
  }[]
>([])
const resultConfirm = () => {
  search()
  loadTabData()
}

/**
 * @description: 更改物流方式
 */
const changeWayRow = ref<LogisticsData>({} as LogisticsData)
const isChangeWayLoading = ref(false)
const changeWayRef = ref()
const wayDialogTitle = ref('')

const rowClick = (row: LogisticsData, title?: string) => {
  console.log(title, 'title')
  try {
    // if (title == '创建物流订单') {
    //   changeWayRow.value = row
    // } else {
    if (row.logisticsWayId === selection.value[0]?.logisticsWayId) {
      ElMessage.warning('不能选择相同的物流方式')
      changeWayRow.value = {} as LogisticsData

      changeWayRef.value?.setCurrentRow()

      return
    }
    changeWayRow.value = row
    // }
  } catch (error) {
    console.log(error)
  }
}

const cancelWayDialog = () => {
  changeWayRow.value = {} as LogisticsData
  changeWayRef.value?.setCurrentRow()
  isChangeWay.value = false
}
//确认物流
const changeWaySubmit = async (title: string) => {
  if (!changeWayRow.value?.logisticsWayId) {
    return ElMessage.warning('请选择一条物流方式')
  }
  if (!changeWayRow.value.status) {
    return ElMessage.warning('请选择状态为成功的物流方式')
  }
  let Fn
  if (title !== '创建物流订单') {
    if (
      changeWayRow.value.logisticsWayId === selection.value[0]?.logisticsWayId
    ) {
      return ElMessage.warning('更改的物流方式不能相同')
    }
    Fn = changeLogisticsApi
  } else {
    Fn = createLogisticsOrderApi
  }
  isChangeWayLoading.value = true
  try {
    const params = {
      updateByIdParam: {
        id: currentItem.value?.id || '',
        dataVersion: currentItem.value?.version as number,
      },
      logisticsTrialCalculation: { ...changeWayRow.value },
    }

    await Fn(params)
    isChangeWay.value = false

    isChangeWayLoading.value = false
    ElMessage.success('操作成功')
    search()
    loadTabData()
  } catch (error) {
    console.log(error)
  } finally {
    isChangeWayLoading.value = false
  }
}

// 添加补货成功行的状态
const stockOutSuccessIds = ref<number[]>([])

const stockOutCheck = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const selectedIds = selection.value.map((item) => item.id)
    const res = await stockOutCheckApi(selectedIds)

    if (res.code !== 200) return
    const successIds = res.data.filter((e) => e.status).map((ee) => ee.id) || []
    // if (successIds.length === 0) {
    //   ElMessage.warning('未补到货')
    //   return
    // }
    resultInfo.value =
      (res.data as {
        id: string | number
        status: boolean
        factoryOrderNumber?: string
        message: string
      }[]) || []
    if (
      Array.isArray(res.data) &&
      (res.data as { status: boolean }[]).some((item) => !item.status)
    ) {
      resultRefs.value?.showDialog('stockOut')
    } else {
      ElMessage.success('操作成功')
    }

    const { success, others } = (
      tableData.value as PodUsOrderListData[]
    ).reduce(
      (acc, item) => {
        successIds.includes(item.id)
          ? acc.success.push(item)
          : acc.others.push(item)
        return acc
      },
      {
        success: [] as PodUsOrderListData[],
        others: [] as PodUsOrderListData[],
      },
    )

    tableData.value = [...success, ...others]

    // 等待DOM更新后再设置选中状态
    await nextTick()
    // 更新补货成功的行ID
    stockOutSuccessIds.value = successIds
    // 清除所有选中状态
    tableRef.value?.clearSelection()
    // 选中补货成功的行
    success.forEach((row) => {
      tableRef.value?.toggleRowSelection(row, true)
    })
  } catch (error) {
    console.error('补货校验失败:', error)
  } finally {
    loading.close()
  }
}

// 添加表格ref
const tableRef = ref()
//转至生产
const toBePicking = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  try {
    await ElMessageBox.confirm('确定补货完成吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch (e) {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await toBePickingApi(selection.value.map((item) => item.id))
    if (res.code !== 200) return
    resultInfo.value =
      (res.data as {
        id: string | number
        status: boolean
        factoryOrderNumber?: string
        message: string
      }[]) || []
    if (
      Array.isArray(res.data) &&
      (res.data as { status: boolean }[]).some((item) => !item.status)
    ) {
      resultRefs.value?.showDialog()
    } else {
      search()
      loadTabData()
    }
    ElMessage.success('操作成功')
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
//转至待排单
const logisticsToPicking = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  // if (
  //   selection.value.some(
  //     (el) =>
  //       el.trackingNumber == null || String(el.trackingNumber).trim() === '',
  //   )
  // ) {
  //   return ElMessage.warning('选中数据中有未创建物流的订单，请先创建物流')
  // }
  try {
    await ElMessageBox.confirm('确定转至待排单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch (e) {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await updateLogisticsToArrangeApi({
      ids: selection.value.map((item) => item.id).join(','),
    })
    if (res.code !== 200) return
    resultInfo.value =
      (res.data as {
        id: string | number
        status: boolean
        factoryOrderNumber?: string
        message: string
      }[]) || []
    if (
      Array.isArray(res.data) &&
      (res.data as { status: boolean }[]).some((item) => !item.status)
    ) {
      resultRefs.value?.showDialog()
    } else {
      search()
      loadTabData()
    }
    ElMessage.success('操作成功')
    // search()
    // loadTabData()
  } catch (e) {
    resultInfo.value = []
    console.error(e)
  } finally {
    loading.close()
  }
}
const sheetPrinter = ref('')
const handlePrinterChange = (value: string) => {
  console.log('value', value)

  sheetPrinter.value = value
  localStorage.setItem('sheetPrinter', JSON.stringify(value))
}
const handleWarehouseIdChange = (value: string) => {
  localStorage.setItem('locaclWarehouseId', JSON.stringify(value))
}
const { getCLodop } = useLodop()
const printOrder = async (
  data: OrderData,
  callback: (status: boolean) => void,
) => {
  const lodop = getCLodop(null, null)
  if (!lodop) return
  lodop.PRINT_INIT('打印内容')
  const printerIndex = lodop.SET_PRINTER_INDEX(sheetPrinter.value)
  console.log(
    'printerIndex',
    printerIndex,
    `sheetPrinter.value:${sheetPrinter.value}`,
  )
  if (!printerIndex) {
    ElMessage.error('打印机设置失败')
    callback && callback(false)
    return
  }
  if (data.filePath) {
    const strURL = filePath + data.filePath
    console.log('strURL', strURL, data)
    lodop.ADD_PRINT_PDF(
      0,
      0,
      '100%',
      '100%',
      /(https):\/\/([^/]+)/i.test(strURL) ? downloadPDF(strURL) : strURL,
    )
  } else {
    lodop.SEND_PRINT_RAWDATA(data.fileData || '')
  }
  console.log('lodop.CVERSION', lodop.CVERSION)
  if (lodop.CVERSION) {
    const startTime = Date.now()
    const jobCode = await lodopCall((lodop) => {
      lodop.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
      return lodop.PRINT()
    })
    console.log('jobCode', jobCode)
    // eslint-disable-next-line no-constant-condition
    while (true) {
      const ok = await lodopCall((lodop) =>
        lodop.GET_VALUE('PRINT_STATUS_OK', jobCode),
      )
      console.log('PRINT_STATUS_OK:', jobCode, `ok: ${ok}`)
      if (ok == 1) {
        console.log('打印成功')
        // 打印状态：成功
        callback && callback(true)
        return
      }
      // 如果打印状态表示未成功或者返回了空，继续获取任务是否存在
      const exist = await lodopCall((lodop) =>
        lodop.GET_VALUE('PRINT_STATUS_EXIST', jobCode),
      )
      console.log(
        '[LODOP] PRINT_STATUS OK,EXIST',
        jobCode,
        `ok:${ok}`,
        `exist:${exist}`,
        `jobCode:${jobCode}`,
        `(${Date.now() - startTime}ms)`,
      )
      if (exist == 0) {
        console.log('任务不存在了', `exist:${exist}`)
        // 任务不存在了
        callback && callback(true)
        return
      }

      await new Promise((r) => setTimeout(r, 500))
      if (Date.now() - startTime >= 30000) {
        console.log('打印超时(30秒)')
        ElMessage.error('打印超时(30秒)')
        callback && callback(false)
        return
      }
    }
  } else {
    lodop.PRINT()
    callback && callback(false)
  }
}
let _lodop: LODOPObject | null = null
let _lodopCallback: { [key: string]: (value: string) => void } = {}
const lodopCall = (fn: (lodop: LODOPObject) => string) => {
  if (!_lodop) {
    _lodop = getCLodop(null, null)
    if (!_lodop) return
    _lodop.On_Return_Remain = true
    _lodop.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
    _lodopCallback = {}
    _lodop.On_Return = (id, value) => {
      console.log('lodopCall return', id, JSON.stringify(value))
      const cb = _lodopCallback[id]
      if (!cb) return
      delete _lodopCallback[id]
      cb(value)
    }
  }

  return new Promise((resolve) => {
    if (!_lodop) return
    const id = fn(_lodop)
    console.log('lodopCall', id)
    _lodopCallback[id] = resolve
  })
}
const downloadPDF = (url: string) => {
  if (!/^https?:/i.test(url)) return url
  let xhr,
    arrybuffer = false,
    dataArray = null
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest()
  } else {
    xhr = new window.ActiveXObject('MSXML2.XMLHTTP')
  }
  xhr.open('GET', url, false) //同步方式
  if (xhr.overrideMimeType)
    try {
      xhr.responseType = 'arraybuffer'
      arrybuffer = true
    } catch (err) {
      xhr.overrideMimeType('text/plain; charset=x-user-defined')
    }
  xhr.send(null)
  const data = xhr.response || xhr.responseBody
  if (typeof Uint8Array !== 'undefined') {
    if (arrybuffer) {
      dataArray = new Uint8Array(data)
    } else {
      dataArray = new Uint8Array(data.length)
      for (let i = 0; i < dataArray.length; i++) {
        dataArray[i] = data.charCodeAt(i)
      }
    }
  } else {
    dataArray = window.VBS_BinaryToArray(data).toArray() //兼容IE低版本
  }
  const digits =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  let strData = ''
  for (let i = 0, ii = dataArray.length; i < ii; i += 3) {
    if (isNaN(dataArray[i])) break
    const b1 = dataArray[i] & 0xff,
      b2 = dataArray[i + 1] & 0xff,
      b3 = dataArray[i + 2] & 0xff
    const d1 = b1 >> 2,
      d2 = ((b1 & 3) << 4) | (b2 >> 4)
    const d3 = i + 1 < ii ? ((b2 & 0xf) << 2) | (b3 >> 6) : 64
    const d4 = i + 2 < ii ? b3 & 0x3f : 64
    strData +=
      digits.substring(d1, d1 + 1) +
      digits.substring(d2, d2 + 1) +
      digits.substring(d3, d3 + 1) +
      digits.substring(d4, d4 + 1)
  }
  return strData
}
const openDetail = async (id: number) => {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await getOrderDetailById(id)
    if (res.code == 200) {
      if (res.data.imageAry) {
        res.data.imageAry = JSON.parse(res.data.imageAry as string)
      }
      detailData.value = res.data || {}
      detailVisible.value = true
      fastKey.value = 'detail'
    }
  } catch (e) {
    //showError(e)
  } finally {
    loading.close()
  }
}
const onFastRefresh = () => {
  loadTabData()
  search()
}
// // 修改行样式方法
const getRowStyle = ({ row }: { row: PodUsOrderListData }) => {
  if (stockOutSuccessIds.value.includes(row.id)) {
    return {
      backgroundColor: '#f0f9eb',
      color: '#67c23a',
    }
  }
  return {}
}
const warehouseList = ref<WarehouseListData[]>([])
const loadWarehouseList = async () => {
  try {
    const res = await loadWarehouseListApi()
    if (res.code !== 200) return
    warehouseList.value = res.data
  } catch (e) {
    console.error(e)
  }
}
// 获取工艺列表
const craftList = ref<CraftListData[]>([])

const loadCraftList = async () => {
  try {
    const res = await getListCraftApi()
    if (res.code !== 200) return
    craftList.value = res.data
  } catch (e) {
    console.error(e)
  }
}
const refreshMaterial = async () => {
  if (
    [
      'PICKING',
      'TO_BE_REPLENISHMENT',
      'IN_PRODUCTION',
      'TO_BE_ARRANGE',
    ].includes(status.value)
  ) {
    if (cardSelection.value.length === 0) {
      return ElMessage.warning('请选择数据')
    }
  } else {
    if (selection.value.length === 0) {
      return ElMessage.warning('请选择数据')
    }
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '刷新中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await refreshMaterialApi({
      orderIds: !['PICKING', 'TO_BE_REPLENISHMENT', 'IN_PRODUCTION'].includes(
        status.value,
      )
        ? selection.value.map((item) => item.id).join(',')
        : undefined,
      productIds: [
        'PICKING',
        'TO_BE_REPLENISHMENT',
        'IN_PRODUCTION',
        'TO_BE_ARRANGE',
      ].includes(status.value)
        ? cardSelection.value.map((item) => item.id).join(',')
        : undefined,
    })
    if (res.code !== 200) return
    ElMessage.success('刷新成功')
    search()
    cardSelection.value = []
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

const showLogistics = (item: PodUsOrderListData) => {
  currentRow.value = JSON.parse(JSON.stringify(item))
  logisticsVisible.value = true
  logisticsForm.value = JSON.parse(JSON.stringify(logistics))
}

watch(
  () => status.value,
  (val) => {
    const currentUrl = new URL(window.location.href)
    currentUrl.searchParams.set('tab', val)

    window.history.pushState({}, '', currentUrl)
  },
  { immediate: true },
)

onMounted(() => {
  loadTabData()
  getUserMark()
  loadProductionClient()
  loadWarehouseList()
  loadCraftList()
})

const expressSheetUpload = async (file: File) => {
  const fm = new FormData()
  fm.append('file', file)
  fm.append('trackingNumber', logisticsForm.value.trackingNumber)
  const res = await uploadExpressSheet(fm as never)
  logisticsForm.value.expressSheetUrl = res.message || ''
  logisticsForm.value.expressSheet = file

  return false
}
const logisticsSubmit = () => {
  if (!logisticsForm.value.expressSheetUrl) {
    return ElMessage.warning('请上传物流面单')
  }
  logisticsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const params = {
        trackingNumber: logisticsForm.value.trackingNumber,
        expressSheet: logisticsForm.value.expressSheetUrl,
        processNumber: logisticsForm.value.processNumber,
        id: currentRow.value.id,
      }
      await updateSelfLogistics(params)
      ElMessage.success('操作成功')
      logisticsVisible.value = false
      search()
    }
  })
}

const handleExceptionCommand = (command: number) => {
  exceptionStatus.value = command
  search()
}
// 拦截分页
const handleInterceptionCommand = (current: number, command: number) => {
  interceptCurrent.value = current
  interceptStatus.value = command
  search()
  loadTabData()
}

const applyForReplenishment = async (row: ProductList | undefined) => {
  if (!row) {
    if (cardSelection.value.length === 0) {
      return ElMessage.warning('请至少选择一条数据')
    }
  }
  ElMessageBox.prompt('请输入补胚数量', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputValue: row ? String(row.replenishmentSumNum || '') : '',
    inputErrorMessage: '请输入补胚数量',
    inputPlaceholder: '补胚数量',
  }).then(async (res) => {
    if (res.value) {
      let data = []
      if (!row) {
        data = cardSelection.value.map((item) => {
          return {
            id: item.podJomallOrderUsId,
            productId: item.id,
            factorySubOrderNumber: item.factorySubOrderNumber || '',
            replenishmentNum: res.value,
            podJomallOrderUsStatus: status.value,
          }
        })
      } else {
        data = [
          {
            id: row.podJomallOrderUsId,
            productId: row.id,
            factorySubOrderNumber: row.factorySubOrderNumber || '',
            replenishmentNum: res.value,
            podJomallOrderUsStatus: status.value,
          },
        ]
      }
      const loading = ElLoading.service({
        fullscreen: true,
        text: '操作中...',
        background: 'rgba(0, 0, 0, 0.3)',
      })
      try {
        const result = await applyForReplenishmentApi(data)
        if (result.code !== 200) return
        ElMessage.success('操作成功')
        cardSelection.value = []
        search()
        loadTabData()
      } catch (e) {
        console.error(e)
      } finally {
        loading.close()
      }
    }
  })
}

/**
 * @description: 生产完成按钮
 */
async function productioncompleted() {
  if (cardSelection.value.length === 0) {
    return ElMessage.warning('请至少选择一条数据')
  }
  const bool = cardSelection.value.some((el) => el.isReplenishment)
  if (bool) {
    return ElMessage.warning({
      message:
        '选择数据中有<span style="color: #fff;background-color: #f56c6c; border-radius: 4px;padding:0 5px">补胚中</span>的数据，无法生产完成',
      dangerouslyUseHTMLString: true,
    })
  }
  try {
    await ElMessageBox.confirm('是否确认生产完成?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })

  const paramsArr = cardSelection.value.map((el) => {
    return {
      id: el.id ?? '',
      podJomallOrderUsId: el.podJomallOrderUsId ?? '',
      factorySubOrderNumber: el.factorySubOrderNumber ?? '',
      version: el.version ?? '',
    }
  })

  try {
    const res = await updateToWaitShipmentApi({ usUpdateParams: paramsArr })
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
    cardSelection.value = []
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

const replenishmentSuccess = async () => {
  if (cardSelection.value.length === 0) {
    return ElMessage.warning('请至少选择一条数据')
  }
  try {
    await ElMessageBox.confirm('是否确认补胚完成', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })

  try {
    const res = await replenishmentSuccessApi(
      cardSelection.value.map((item) => item.id),
    )
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
    cardSelection.value = []
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

function getPlatformImg(code: string) {
  const lowerCode = code.toLowerCase()
  const item = platformJson.find((el) =>
    el.type.toLowerCase().includes(lowerCode),
  )
  if (item) {
    return item.icon.split('/').pop()
  }
  return ''
}

function getQuantityText(qty: number) {
  if (!qty || qty <= 0) return ''
  return Math.floor(qty) === 1 ? '单' : '多'
}

const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const handlePictureCardPreview = (fileUrl: string) => {
  dialogImageUrl.value = fileUrl
  dialogVisible.value = true
}
// 全局 loading 改为每行 loading map
const reComposingLoadingMap = reactive<{ [key: number]: boolean }>({})

const handleBeforeRouteLeave = (
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext,
) => {
  console.log(to, from)

  localStorage.removeItem('podUsStatus')
  next()
}

// 拦截状态改变
const interceptChange = async (status: boolean) => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  try {
    await ElMessageBox.confirm(
      `确定${status ? '拦截成功' : '拦截失败'}吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
  } catch (e) {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })

  const interceptStatus = status
    ? interceptCurrent.value === 1
      ? 1
      : 3
    : interceptCurrent.value === 1
    ? 2
    : 4
  try {
    const res = await interceptUpdateApi({
      orderIds: selection.value.map((item) => item.id),
      interceptStatus,
    })
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
  } catch (e) {
    resultInfo.value = []
    console.error(e)
  } finally {
    loading.close()
  }
}

// 状态推送
const statusPush = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  try {
    await ElMessageBox.confirm('是否确认状态推送?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await statusPushApi(selection.value.map((item) => item.id))
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
  } catch (e) {
    resultInfo.value = []
    console.error(e)
  } finally {
    loading.close()
  }
}

// 完成发货
const completeDelivery = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择订单')
  }

  try {
    await ElMessageBox.confirm('确定完成发货吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch (e) {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await completeDeliveryApi({
      orderIdList: selection.value.map((item) => item.id),
    })
    if (res.code !== 200) return
    resultInfo.value =
      (res.data as {
        id: string | number
        status: boolean
        factoryOrderNumber?: string
        message: string
      }[]) || []
    if (
      Array.isArray(res.data) &&
      (res.data as { status: boolean }[]).some((item) => !item.status)
    ) {
      resultRefs.value?.showDialog()
    } else {
      search()
      loadTabData()
    }
    ElMessage.success('操作成功')
    // search()
    // loadTabData()
  } catch (e) {
    resultInfo.value = []
    console.error(e)
  } finally {
    loading.close()
  }
}

const tempChinaLogs = ref<LogListData[]>([])
const timeType = ref<string>('Asia/Shanghai')
function changeChinaTime(zone: string) {
  timeType.value = zone
  logList.value = tempChinaLogs.value.map((el) => {
    return {
      ...el,
      createTime: convertToChinaTime(el.createTime, 'Asia/Shanghai', zone),
      local: zone.split('/')[1] === 'Shanghai' ? 'BeiJing' : zone.split('/')[1],
    }
  })
}

const token = getToken() as string
async function getPermission() {
  const res = await getAccountCodeByFactoryIdApi({ token })
  permissionBtns.setBtn(res.data)
  console.log(res)
}
getPermission()
const globalProperties =
  getCurrentInstance()?.appContext.config.globalProperties // 获取全局挂载
const isPermissionBtn = globalProperties?.$isPermissionBtn

useRouter().beforeEach((to, from, next) => {
  handleBeforeRouteLeave(to, from, next)
})
</script>
<style lang="scss" scoped>
.header-filter-form {
  :deep(.el-form-item) {
    margin-right: 14px;
    margin-bottom: 10px;
  }
}

// .item {
//   margin-right: 15px;
// }

.tabs {
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #f0f0f0;
  height: 42px;

  .tabs-node {
    padding: 10px;
    font-size: 16px;
    color: #000;
    cursor: pointer;
    height: 40px;
    font-weight: 500;
  }

  .tabs-node:hover {
    color: #409eff;
  }

  .tabs-node.tabs-node_active {
    color: #409eff;
    border-bottom: 2px solid #409eff;
    font-weight: 600;
  }
}

.table-wrapper {
  :deep(.exception-reason) {
    .cell {
      white-space: wrap;
    }
  }
}

.goods-item {
  display: grid;
  grid-template-columns: 100px 1fr minmax(150px, 1fr) 150px;
  gap: 15px;

  .goods-item-img {
    // width: 100px;
    // height: 65px;
    position: relative;
    img {
      width: 65%;
    }
  }

  &:not(:last-child) {
    padding-bottom: 10px;
    margin-bottom: 10px;
    border-bottom: 1px solid #eee;
  }
}

.goods-item-info-item {
  display: flex;
  align-items: center;
  gap: 6px;

  .goods-item-info-item-value {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.order-detail-item {
  display: flex;
  align-items: center;
  gap: 6px;

  .order-detail-item-value {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.card-list {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: max-content;
  gap: 10px;
  height: 100%;
  overflow-y: auto;
}

.tabs-node_count {
  display: inline-block;
  min-width: 20px;
  height: 20px;
  line-height: 20px;
  border-radius: 50%;
  font-size: 14px;
  text-align: center;
  margin-left: 4px;
  background: #f2f3f5; // 默认灰色
  color: #666;
  font-weight: 500;
}

.tabs-node_count.blue {
  background: rgb(219, 234, 254);
  color: rgb(30, 64, 175);
}

.tabs-node_count.red {
  background: rgb(254 226 226);
  color: rgb(153 27 27);
}

.empty {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

.card-list-item {
  cursor: pointer;
}

.images-position {
  display: flex;
  gap: 5px;
  flex: 1;
  overflow-x: auto;

  .item-image {
    cursor: pointer;
    border: 1px solid #eee;
  }
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  font-size: 12px;
  margin-top: 10px;

  .grid-item {
    display: flex;
    overflow: hidden;
    width: 100%;
    .grid-item-value {
      display: flex;
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

.factory-sub-order-number {
  font-size: 12px;
}

.production-client-table {
  ::v-deep(.current-row > td.el-table__cell) {
    background-color: #409eff;
    color: white;

    & > td.el-table__cell {
      color: white !important;
      background-color: #409eff;
    }

    // &:hover {
    //   color: #808285;
    // }
  }

  :deep() {
    .current-row {
      &:hover {
        td.el-table__cell {
          color: #808285;
        }
      }
    }
  }
}

.sub-status {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e5e6eb;
  background: #fff;

  .sub-status-item {
    position: relative;
    font-size: 16px;
    cursor: pointer;
    padding: 6px 24px 6px 24px;
    border: 1px solid #e5e6eb;
    background: #f7f8fa;
    color: #606266;
    margin-bottom: -1px;
    transition: background 0.2s, color 0.2s;

    &:not(:last-child) {
      border-right: none;
    }

    &.sub-active {
      background: #fff;
      color: #1d2129;
      font-weight: 600;
      border-bottom: 1px solid transparent;
      z-index: 2;
    }
  }
}

.operate-box {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.operate-box-vertical {
  display: flex;
  justify-content: space-around;
  align-items: center;
  gap: 10px;
}

.file {
  position: relative;
  top: -5px;
  left: 20px;
  display: flex;
  align-items: center;

  span {
    font-size: 14px;
  }

  .expressSheetClose {
    margin-left: 30px;
    cursor: pointer;

    &:hover {
      color: red;
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin: 10px 0;

  :deep(.el-pagination) {
    margin: 0 !important;
  }

  .total {
    color: #606266;
    font-size: 15px;
  }

  .pageSize {
    line-height: 39px;
    color: #606266;
    font-size: 15px;
  }
}
.orderNumber {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
  min-width: 0; /* 关键属性 */
}
.customizedQuantity {
  height: 28px;
  width: 28px;
  color: #f56c6c;
  text-align: center;
  line-height: 24px;
  background-color: #fff;
  border: 2px solid #f56c6c;
  border-radius: 7px;
  margin-right: 2px;
  font-weight: 700;
  box-sizing: border-box;
}
.triangle-box {
  position: absolute;
  top: 0;
  right: 0;
  width: 0;
  height: 0;
  border: 18px solid transparent;
  border-top: 18px solid #e74c3c;
  border-right: 18px solid #e74c3c;
}

.multi-text {
  position: absolute;
  top: -19px;
  color: white;
  font-weight: bold;
}
</style>
<style lang="scss">
.customize-select-style {
  .el-select-dropdown__list {
    width: 500px;
    display: flex;
    flex-wrap: wrap;
  }
}
.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-success);
  display: flex;
  align-items: center;
  outline: none;
}
.el-timeline-item__wrapper {
  padding-left: 15px;
  top: -4px;
}
.el-timeline
  > .el-timeline-item:first-child
  .el-timeline-item__timestamp.is-top {
  color: #409eff;
}
.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
