<template>
  <div class="card flex-column h-100 overflow-hidden">
    <div class="header-filter-form">
      <ElForm :model="searchForm" size="default" inline>
        <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.trim="searchForm.supplierProductNo"
            placeholder="款号"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <ElFormItem label="批次号">
          <ElInput
            v-model.trim="searchForm.batchArrangeNumber"
            placeholder="批次号"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <ElFormItem label="生产单号">
          <ElInput
            v-model.trim="searchForm.factorySubOrderNumber"
            placeholder="生产单号"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <ElFormItem label="店铺单号">
          <ElInput
            v-model.trim="searchForm.shopNumber"
            placeholder="店铺单号"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <ElFormItem label="尺码类型">
          <ElSelect
            v-model="searchForm.sizeType"
            clearable
            filterable
            placeholder="请输入尺码类型"
            style="width: 150px"
          >
            <el-option
              v-for="item in sizeList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="排序">
          <el-select
            v-model="searchForm.order"
            clearable
            style="width: 100px"
            placeholder="排序类型"
          >
            <el-option value="asc" label="正序"></el-option>
            <el-option value="desc" label="倒序"></el-option>
          </el-select>
        </ElFormItem>
        <ElFormItem label="类型">
          <el-radio-group v-model="searchForm.customizedQuantity" @click.stop="(e: Event) => handleRadioGroupClick(e)">
            <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" @click.stop="(e: Event) => handleMultiRadioGroupClick(e)">
            <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.replaceShipment"
                  placeholder="是否代发"
                  clearable
                  :teleported="false"
                  style="width: 150px"
                  @change="changeReplaceShipment"
                >
                  <ElOption
                    v-for="(item, index) in ['不代发', '代发']"
                    :key="index"
                    :value="index"
                    :label="item"
                  ></ElOption>
                </ElSelect>
              </ElFormItem>
              <ElFormItem
                v-if="searchForm.replaceShipment === 0"
                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>
              <ElFormItem
                v-if="searchForm.replaceShipment === 1"
                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>
              <ElFormItem label="标签">
                <ElSelect
                  v-model="searchForm.tagsIdArr"
                  placeholder="请选择标签"
                  clearable
                  filterable
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  :teleported="false"
                  style="width: 150px"
                >
                  <ElOption
                    v-for="(item, index) in customTagList"
                    :key="index"
                    :value="item.id"
                    :label="item.name"
                  ></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'
          "
        >
          <ElDropdown>
            <el-button type="primary">
              DTF排版<el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <ElDropdownMenu>
                <ElDropdownItem
                  :loading="tifDownloadLoading"
                  @click="downloadTif('tiff', 42)"
                  >TIF(40+2cm)</ElDropdownItem
                >
                <ElDropdownItem
                  :loading="tifDownloadLoading"
                  @click="downloadTif('tiff', 60)"
                  >TIF(60cm)</ElDropdownItem
                >
                <ElDropdownItem
                  :loading="pngDownloadLoading"
                  @click="downloadTif('png', 42)"
                  >PNG(40+2cm)</ElDropdownItem
                >
                <ElDropdownItem
                  :loading="pngDownloadLoading"
                  @click="downloadTif('png', 60)"
                  >PNG(60cm)</ElDropdownItem
                >
              </ElDropdownMenu></template
            ></ElDropdown
          >
        </ElFormItem>
        <ElFormItem>
          <!-- <span
            v-if="
              status === 'PICKING' ||
              status === 'TO_BE_REPLENISHMENT' ||
              status === 'IN_PRODUCTION'
            "
            class="item"
          >
            <ElButton
              :loading="tifDownloadLoading"
              type="warning"
              @click="downloadTif('tiff')"
            >
              TIF排版
            </ElButton>
          </span>
          <span
            v-if="
              status === 'PICKING' ||
              status === 'TO_BE_REPLENISHMENT' ||
              status === 'IN_PRODUCTION'
            "
            class="item"
          >
            <ElButton
              :loading="pngDownloadLoading"
              type="warning"
              @click="downloadTif('png')"
            >
              PNG排版
            </ElButton>
          </span> -->
          <span v-if="status === 'TO_BE_CONFIRMED'" class="item">
            <ElButton type="success" @click="confirmProduct">
              确认生产
            </ElButton>
          </span>
          <span v-if="status === 'EXCEPTION_ORDER'" class="item">
            <ElButton type="success" @click="updateOrder">
              转至待确认
            </ElButton>
          </span>
          <span
            v-if="status === 'EXCEPTION_ORDER' && exceptionStatus === 3"
            class="item"
          >
            <ElButton type="warning" @click="asyncOrderAddress">
              同步收货地址
            </ElButton>
          </span>
          <span
            v-if="status === 'EXCEPTION_ORDER' && exceptionStatus === 1"
            class="item"
          >
            <ElButton type="warning" @click="assignOrder"> 分派 </ElButton>
          </span>
          <span
            v-if="
              status === 'PICKING' ||
              status === 'TO_BE_REPLENISHMENT' ||
              status === 'IN_PRODUCTION'
            "
            class="item"
          >
            <ElButton type="primary" @click="printProductionOrder">
              打印生产单
            </ElButton>
          </span>
          <span v-if="status === 'TO_BE_REPLENISHMENT'" class="item">
            <ElButton type="success" @click="replenishmentSuccess">
              补胚完成
            </ElButton>
          </span>
          <span v-if="status === 'PICKING'" class="item">
            <ElButton type="success" @click="printPickingOrder">
              打印拣货单
            </ElButton>
          </span>
          <span v-if="status === 'PICKING'" class="item">
            <ElButton type="warning" @click="pickingComplete">
              拣胚完成
            </ElButton>
          </span>
          <span v-if="status === 'PICKING'" class="item">
            <ElButton type="success" @click="toOutOfStock"> 转至缺货 </ElButton>
          </span>
          <span v-if="status === 'TO_BE_CONFIRMED'" class="item">
            <ElButton type="warning" @click="changeExceptionOrder">
              转为异常单
            </ElButton>
          </span>
          <span
            v-if="status === 'TO_BE_CONFIRMED' || status === 'EXCEPTION_ORDER'"
            class="item"
          >
            <ElButton type="danger" @click="cancelOrder">取消</ElButton>
          </span>
          <span v-if="status === 'IN_PRODUCTION'" class="item">
            <ElButton type="warning" @click="onFastProduction">
              快捷生产
            </ElButton>
          </span>
          <span v-if="status === 'IN_PRODUCTION'" class="item">
            <ElButton type="success" @click="applyForReplenishment(undefined)">
              申请补胚
            </ElButton>
          </span>
          <span v-if="status === 'IN_PRODUCTION'" class="item">
            <ElButton type="success" @click="productioncompleted">
              生产完成
            </ElButton>
          </span>
          <span v-if="status === 'WAIT_SHIPMENT'" class="item">
            <ElButton type="success" @click="printPodOrder">
              播种墙配货
            </ElButton>
          </span>
          <span v-if="status === 'WAIT_SHIPMENT'" class="item">
            <ElButton type="primary" @click="podDistributionOrderShow">
              单件打单
            </ElButton>
          </span>
          <span
            v-if="status === 'WAIT_SHIPMENT' && isSuperFactory"
            class="item"
          >
            <ElButton type="danger" @click="printSuperPodOrder">
              超级播种墙配货
            </ElButton>
          </span>
          <span v-if="status === 'CREATE_LOGISTICS'" class="item">
            <ElButton type="warning" @click="logisticsToPicking">
              转至待排单
            </ElButton>
          </span>
          <span v-if="status === 'WAIT_SHIPMENT'" class="item">
            <ElButton type="primary" @click="completeDelivery()"
              >完成发货</ElButton
            >
          </span>
          <span
            v-if="status === 'WAIT_SHIPMENT' || status === 'CREATE_LOGISTICS'"
            class="item"
          >
            <ElDropdown>
              <el-button type="success">
                物流接口<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <!-- <template #dropdown v-if="shipmentArea === 0">
                <ElDropdownMenu>
                  <ElDropdownItem
                    :disabled="
                      selection.length === 0 ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click=""
                    >待定</ElDropdownItem
                  >
                </ElDropdownMenu>
              </template> -->
              <!-- 代发:0.自有物流 1.工厂物流; 不代发: 0.自提 1.快递-->
              <template
                v-if="
                  (status === 'CREATE_LOGISTICS' && shipmentArea === 1) ||
                  status === 'WAIT_SHIPMENT'
                "
                #dropdown
              >
                <ElDropdownMenu>
                  <ElDropdownItem
                    :disabled="
                      selection.length === 0 ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('createLogisticsOrder')"
                    >创建物流订单</ElDropdownItem
                  >
                  <ElDropdownItem
                    :disabled="
                      selection.length === 0 ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('getTrackingNumber')"
                    >获取跟踪号</ElDropdownItem
                  >
                  <ElDropdownItem
                    :disabled="
                      selection.length === 0 ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('getPrintOrder')"
                    >获取打印面单</ElDropdownItem
                  >
                  <ElDropdownItem
                    :disabled="
                      selection.length === 0 ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('cancelLogisticsOrder')"
                    >取消物流订单</ElDropdownItem
                  >
                </ElDropdownMenu>
              </template>
            </ElDropdown>
          </span>
          <span v-if="status === 'STOCK_OUT'" class="item">
            <ElButton type="warning" @click="stockOutCheck">
              补货校验
            </ElButton>
          </span>
          <span v-if="status === 'STOCK_OUT'" class="item">
            <ElButton type="success" @click="toBePicking"> 转至生产 </ElButton>
          </span>
          <span v-if="status === 'TO_BE_ARRANGE'" class="item">
            <ElButton type="warning" @click="showArrange(2)">排单完成</ElButton>
          </span>
          <span
            v-if="status !== 'BATCH_DOWNLOAD' && status !== 'WAIT_SHIPMENT'"
            class="item"
          >
            <ElButton type="primary" @click="downloadMaterial"
              >下载素材</ElButton
            >
          </span>
          <span
            v-if="
              status === 'INTERCEPTED' &&
              (interceptCurrent === 1 || interceptCurrent === 4)
            "
            class="item"
          >
            <ElButton type="success" @click="interceptChange(true)">
              拦截成功
            </ElButton>
          </span>
          <span
            v-if="
              status === 'INTERCEPTED' &&
              (interceptCurrent === 1 || interceptCurrent === 4)
            "
            class="item"
          >
            <ElButton type="danger" @click="interceptChange(false)">
              拦截失败
            </ElButton>
          </span>
          <!-- <span
            v-if="
              status === 'TO_BE_CONFIRMED' ||
              status === 'PICKING' ||
              status === 'STOCK_OUT' ||
              status === 'TO_BE_REPLENISHMENT' ||
              status === 'IN_PRODUCTION'
            "
            class="item"
          >
            <ElButton type="success" @click="refreshMaterial">
              刷新素材
            </ElButton>
          </span> -->
          <span
            v-if="
              [
                'TO_BE_CONFIRMED',
                'PICKING',
                'STOCK_OUT',
                'EXCEPTION_ORDER',
                'TO_BE_REPLENISHMENT',
                'IN_PRODUCTION',
                'TO_BE_ARRANGE',
                'WAIT_SHIPMENT',
              ].includes(status)
            "
            class="item"
          >
            <ElButton type="success" @click="refreshProductInformation">
              刷新商品信息
            </ElButton>
          </span>
          <span
            v-if="
              status === 'STOCK_OUT' ||
              status === 'CREATE_LOGISTICS' ||
              status === 'TO_BE_ARRANGE' ||
              status === 'PICKING' ||
              status === 'IN_PRODUCTION'
            "
            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>
          <span
            v-if="['WAIT_TRACK', 'COMPLETE', 'IN_TRANSIT'].includes(status)"
            class="item"
          >
            <ElButton type="warning" @click="statusPush">状态推送</ElButton>
          </span>
          <span v-if="status === 'COMPLETE'" class="item">
            <ElButton
              :loading="exportLoading"
              type="success"
              @click="exportData"
              >导出</ElButton
            >
          </span>
          <span v-if="status === 'BATCH_DOWNLOAD'" 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
            class="tabs-node_count"
            :class="{
              blue: true,
            }"
            >{{ item.quantity && item.quantity > 0 ? item.quantity : 0 }}</span
          >
        </div>
      </div>
    </div>
    <div class="order-content flex-1 flex-column overflow-hidden mt-10">
      <div v-if="status === 'CREATE_LOGISTICS'" class="sub-status mb-10">
        <div
          class="sub-status-item"
          :class="shipmentArea === 0 ? 'sub-active' : ''"
          @click="handleShipmentAreaCommand(0)"
        >
          <span class="sub-status-item-label">国内</span>
        </div>
        <div
          class="sub-status-item"
          :class="shipmentArea === 1 ? 'sub-active' : ''"
          @click="handleShipmentAreaCommand(1)"
        >
          <span class="sub-status-item-label">国外</span>
        </div>
      </div>
      <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"
          :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="商品图片222"
                        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="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="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 v-if="item.sizeType" class="goods-item-info-item">
                      <span class="goods-item-info-item-label">尺码类型:</span>
                      <span class="goods-item-info-item-value">
                        {{
                          sizeList.find((i) => i.value === item.sizeType)?.name
                        }}
                      </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">
                        {{ calculatedPrice(item) }}
                      </span>
                    </div>

                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">{{
                        status === 'PICKING' ||
                        status === 'TO_BE_CONFIRMED' ||
                        status === 'STOCK_OUT' ||
                        status === 'CREATE_LOGISTICS'
                          ? '数量:'
                          : '已生产数量:'
                      }}</span>
                      <span class="goods-item-info-item-value">
                        {{
                          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"
                    >
                      <span class="goods-item-info-item-label">补胚数量:</span>
                      <span
                        class="goods-item-info-item-value"
                        :title="item.replenishmentSumNum"
                      >
                        {{ item.replenishmentSumNum || 0 }}
                      </span>
                      <el-button
                        v-if="status === 'WAIT_SHIPMENT'"
                        link
                        size="small"
                        type="success"
                        @click="applyForReplenishment(item)"
                        >申请补胚
                      </el-button>
                      <!-- f -->
                    </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>
                      <el-button
                        v-if="status === 'WAIT_SHIPMENT'"
                        link
                        size="small"
                        type="warning"
                        style="height: 23px; margin: 0"
                        @click="showArrange(3, item)"
                        >排版
                      </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 class="order-detail-item-value" :title="getTagName(row)">
                  {{ getTagName(row) }}
                </span>
              </div>
              <div class="order-detail-item">
                <!-- 是否代发 0.否 1.是 -->
                <span class="order-detail-item-label">是否代发:</span>
                <span
                  style="color: red; font-weight: 500"
                  class="order-detail-item-value"
                >
                  {{ ['否', '是'][row.replaceShipment] }}
                </span>
              </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.replaceShipment === 1
                      ? ['自有物流', '工厂物流'][row.shipmentType]
                      : ['自提', '快递'][row.shipmentType]
                  }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">
                  <!-- 自提时叫 取货码-->
                  {{
                    row.replaceShipment === 0 && row.shipmentType === 0
                      ? '取货码:'
                      : '物流跟踪号:'
                  }}</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.warehouseName"
                >
                  {{ row.warehouseName }}
                </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.receiverCountry +
                    row.receiverProvince +
                    row.receiverCity +
                    row.receiverAddress1
                  }} -->
                  {{ row.lanshouAddress }}
                </span>
              </div>
            </div>
          </template>
          <template #price="{ row }">
            <div class="order-price-box">
              <div class="order-price-item">
                <span class="order-price-item-label">商品总价￥：</span>
                <span class="order-price-item-value">
                  {{ row.productAmount }}
                </span>
              </div>
              <div v-if="row.serviceAmount" class="order-price-item">
                <span class="order-price-item-label">操作费￥：</span>
                <span class="order-price-item-value">
                  {{ row.serviceAmount }}
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="根据商品的数量计算首件2元，每多一件加价0.5元，上限5元"
                    placement="top"
                  >
                    <el-icon color="#E6A23C"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </span>
              </div>
              <!-- v-if="
                  [
                    'TO_BE_CONFIRMED',
                    'EXCEPTION_ORDER',
                    'STOCK_OUT',
                    'CREATE_LOGISTICS',
                    'WAIT_SHIPMENT',
                    'INTERCEPTED',
                  ].includes(status)
                " -->
              <div class="order-price-item">
                <span class="order-price-item-label">预收运费￥：</span>
                <span class="order-price-item-value">
                  {{ row.prepaidAmount || 0 }}
                </span>
              </div>
              <!-- <div
                v-if="
                  ['WAIT_TRACK', 'IN_TRANSIT', 'COMPLETE', 'CANCEL'].includes(
                    status,
                  )
                "
                class="order-price-item"
              >
                <span class="order-price-item-label">物流运费￥：</span>
                <span class="order-price-item-value">
                  {{ row.actualAmount || 0 }}
                </span>
              </div> -->
              <div class="order-price-item">
                <span class="order-price-item-label">合计￥：</span>
                <span class="order-price-item-value">
                  {{ totalAmountPrice(row) }}
                </span>
              </div>
            </div>
          </template>
          <template #time="{ row }">
            <el-timeline style="max-width: 600px">
              <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 #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 #automaticComposing="{ row }">
            <div style="white-space: pre-line">
              {{ row.automaticComposing ? '是' : '否' }}
            </div>
          </template>
          <template #composingParam="{ row }">
            <div style="white-space: pre-line">
              {{ row.composingParam?.split(';').join('\n') }}
            </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 && !row.tiffUrl"
                  link
                  type="primary"
                  @click="handleDownload(row)"
                >
                  下载
                </ElButton>
              </span>
              <!-- <span class="operate-item">
                <ElButton
                  :disabled="!row.tiffUrl"
                  link
                  type="primary"
                  @click="handleDownload(row, 'tiff')"
                >
                  TIF下载
                </ElButton>
              </span> -->
              <span class="operate-item">
                <ElButton
                  link
                  type="primary"
                  @click="printPickingOrderItem(row, 1)"
                >
                  打印拣货单
                </ElButton>
              </span>
              <span class="operate-item">
                <ElButton
                  link
                  type="primary"
                  @click="printPickingOrderItem(row, 2)"
                >
                  打印生产单
                </ElButton>
              </span>

              <span class="operate-item">
                <ElButton
                  :disabled="row.productNum > 50"
                  link
                  type="warning"
                  :loading="reComposingLoadingMap[row.id]"
                  @click="showArrange(1, 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.replaceShipment === 1 &&
                  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="
                  (row.replaceShipment === 1 &&
                    ['CREATE_LOGISTICS', 'WAIT_SHIPMENT'].includes(status)) ||
                  (row.replaceShipment === 0 &&
                    row.shipmentType === 1 &&
                    ['CREATE_LOGISTICS', 'WAIT_SHIPMENT'].includes(status))
                "
                class="operate-item"
              >
                <ElButton
                  link
                  type="primary"
                  @click="handleRefreshAddress(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>
                <el-tooltip
                  v-if="cardItem.customTagList"
                  :disabled="!(cardItem.customTagList?.length > 3)"
                  class="box-item"
                  effect="light"
                  :content="tooltipContent(cardItem.customTagList.slice(3))"
                  placement="bottom"
                >
                  <template #content>
                    <div
                      v-for="(item, index) in cardItem.customTagList.slice(3)"
                      :key="index"
                    >
                      <el-tag
                        type="primary"
                        :title="item.name || ''"
                        style="margin-bottom: 2px"
                        >{{ item.name || '' }}</el-tag
                      >
                    </div>
                  </template>
                  <div
                    class="flex"
                    ref="tagRefs"
                    style="gap: 5px; overflow: hidden"
                    v-if="cardItem.customTagList?.length"
                  >
                    <el-tag
                      size="small"
                      type="primary"
                      v-for="(item, index) in cardItem.customTagList.slice(
                        0,
                        3,
                      )"
                      :key="index"
                      ><span
                        style="
                          width: 50px;
                          text-align: center;
                          overflow: hidden;
                          white-space: nowrap;
                          text-overflow: ellipsis;
                          display: inline-block;
                        "
                        :title="item.name || ''"
                        >{{ item.name || '' }}</span
                      ></el-tag
                    >
                    <el-tag
                      size="small"
                      type="primary"
                      v-if="cardItem.customTagList?.slice(3)?.length"
                      >+{{ cardItem.customTagList.slice(3).length }}</el-tag
                    >
                  </div>
                </el-tooltip>
              </template>
              <template
                #top_right
                v-if="['ZPZY', 'CXZY', 'THZY'].includes(cardItem.craftCode as string)"
              >
                <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.podJomallOrderCnId, 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 JSON.parse(
                        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 class="flex-row">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="'用户编码: ' + cardItem?.userMark"
                      placement="bottom"
                    >
                      <span
                        style="
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                          width: 100%;
                          display: inline-block;
                        "
                        @click.stop="copy(String(cardItem?.userMark || ''))"
                      >
                        {{ cardItem?.userMark }}
                      </span>
                    </el-tooltip>
                    <img
                      v-if="cardItem.platform"
                      :src="`/images/icon/${getPlatformImg(cardItem.platform)}`"
                      style="width: 30px; 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">
                    <div
                      :title="`variant SKU: ${cardItem?.variantSku || ''}`"
                      class="grid-item-value orderNumber"
                      @click.stop="copy(cardItem?.variantSku || '')"
                    >
                      {{ cardItem?.variantSku }}
                    </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">
                    <span title="Variant SKU" class="grid-item-value">
                      {{ cardItem?.variantSku }}
                    </span>
                  </div> -->
                  <div
                    class="grid-item"
                    :title="`工艺:${cardItem?.craftName || ''}`"
                  >
                    <span class="grid-item-label">工艺：</span>
                    <span class="grid-item-value">
                      {{ cardItem?.craftName }}
                    </span>
                  </div>
                  <div
                    v-if="cardItem?.sizeType"
                    class="grid-item"
                    :title="`尺码类型:${
                      sizeList.find((i) => i.value === cardItem.sizeType)
                        ?.name || ''
                    }`"
                  >
                    <span class="grid-item-label">尺码类型：</span>
                    <span class="grid-item-value">
                      {{
                        sizeList.find((i) => i.value === cardItem.sizeType)
                          ?.name
                      }}
                    </span>
                  </div>
                  <div class="grid-item">
                    <div
                      :title="`库存SKU:${cardItem?.thirdSkuCode || ''}`"
                      class="grid-item-value orderNumber"
                      @click.stop="copy(cardItem?.thirdSkuCode || '')"
                    >
                      {{ cardItem?.thirdSkuCode }}
                    </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">
                    <span class="grid-item-label">货号：</span>
                    <span
                      :title="`货号: ${cardItem?.thirdStockSku}`"
                      class="grid-item-value"
                    >
                      {{ cardItem?.thirdStockSku }}
                    </span>
                  </div>

                  <div
                    class="grid-item"
                    :title="`店铺单号:${cardItem?.shopNumber || ''}`"
                  >
                    <div
                      class="grid-item-value orderNumber"
                      @click.stop="copy(cardItem?.shopNumber || '')"
                    >
                      {{ cardItem?.shopNumber }}
                    </div>
                  </div>
                  <div class="grid-item">
                    <div
                      :title="`第三方生产单号:${cardItem?.thirdSubOrderNumber}`"
                      class="grid-item-value orderNumber"
                      @click.stop="
                        copy(String(cardItem?.thirdSubOrderNumber || ''))
                      "
                    >
                      {{ cardItem?.thirdSubOrderNumber }}
                    </div>
                  </div>
                  <div
                    v-if="cardItem.batchArrangeNumber"
                    class="grid-item"
                    :title="`批次号:${cardItem?.batchArrangeNumber || ''}`"
                  >
                    <div
                      class="grid-item-value orderNumber"
                      @click.stop="copy(cardItem?.batchArrangeNumber || '')"
                    >
                      {{ cardItem?.batchArrangeNumber }}
                    </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="confirmManuShow"
    :close-on-click-modal="false"
    title="确认生产"
    width="500px"
  >
    <el-form
      ref="confirmFormRef"
      :model="confirmForm"
      label-width="120px"
      :rules="confirmRules"
    >
      <el-form-item label="发货仓库" prop="warehouseId">
        <ElSelect
          v-model="confirmForm.warehouseId"
          clearable
          filterable
          placeholder="请选择发货仓库"
          style="width: 80%"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </ElSelect>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="confirmManuShow = false">取消</el-button>
      <el-button type="primary" @click="confirmSubmit">确定</el-button>
    </template>
  </el-dialog>
  <el-dialog
    v-model="logVisible"
    title="操作日志"
    width="1000px"
    :close-on-click-modal="false"
  >
    <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-warehouse-id="handleWarehouseIdChange"
    @refresh="onFastRefresh"
  />
  <!-- :print-order-one="printOrderOne" -->
  <PodDistributionOrder
    v-model="podDistributionOrderVisible"
    :print-order="printOrder"
    :warehouse-list="warehouseList"
    @set-printer="handlePrinterChange"
    @refresh="onFastRefresh"
  />
  <SuperPodMakeOrder
    v-model="superPodOrderVisible"
    :print-order="printOrder"
    :warehouse-list="warehouseList"
    @set-printer="handlePrinterChange"
    @refresh="onFastRefresh"
  />
  <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>
  <UpdateAddress
    v-if="updateAddVisible"
    v-model:form="currentRow"
    v-model:visible="updateAddVisible"
    :country-list="countryList"
    @success="search"
  ></UpdateAddress>
  <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 type="primary" @click="submitExportForm">确认</el-button>
      </span>
    </template>
  </ElDialog>
  <el-dialog v-model="dialogVisible" width="35%">
    <img :src="dialogImageUrl" alt="商品预览图片" />
  </el-dialog>
  <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>
  <ElDialog
    v-model="typesettingVisible"
    title="选择排版类型和宽度"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form :model="typesettingForm">
      <el-form-item
        v-if="typesettingType == 2"
        label="自动排版 (烫画工艺推荐自动排版)"
        prop="bool"
      >
        <el-switch
          v-model="isAuto"
          class="ml-2"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          inline-prompt
          active-text="是"
          inactive-text="否"
          @change="changeSwitch"
        />
      </el-form-item>
      <div v-if="isAuto">
        <el-form-item label="排版类型：" prop="type">
          <el-radio-group v-model="typesettingForm.type">
            <el-radio label="tiff">tiff排版</el-radio>
            <el-radio label="png">png排版</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排版宽度：" prop="type">
          <el-radio-group v-model="typesettingForm.templateWidth">
            <el-radio :value="42">40+2cm</el-radio>
            <el-radio :value="60">60cm</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button
        @click="
          () => {
            isAuto = true
            typesettingVisible = false
          }
        "
        >取消</el-button
      >
      <el-button type="primary" @click="submitTypesetting">确认</el-button>
    </template>
  </ElDialog>
</template>
<script setup lang="ts">
import { getUserMarkList } from '@/api/common'
// import { AnyObject } from '@/types/api/warehouse'
import {
  InfoFilled,
  CaretBottom,
  CaretTop,
  ArrowDown,
  WarningFilled,
  QuestionFilled,
} from '@element-plus/icons-vue'
import {
  getCardOrderList,
  getOrderList,
  getOrderTabData,
  confirmOrderApi,
  cancelOrderApi,
  getOperationLogApi,
  downloadMaterialApi,
  printProductionOrderApi,
  getOrderDetailById,
  updateRemarkApi,
  printPickingOrderApi,
  printPrintOrderApi,
  stockOutCheckApi,
  toBePickingApi,
  loadWarehouseListApi,
  getLogisticsCalculation,
  refreshProductInformationApi,
  composingDesignImages,
  updateLogisticsToArrangeApi,
  syncReceiverAddress,
  refreshAddressApi,
  confirmProductApi,
  applyForReplenishmentApi,
  replenishmentSuccessApi,
  toOutOfStockApi,
  arrangeFinishApi,
  getListCraftApi,
  batchDownloadApi,
  batchDownloadDownloadApi,
  batchDownloadDeleteApi,
  updateToWaitShipmentApi,
  exportPodCnInfo,
  createLogisticsOrdersApi,
  getTrackingNumberApi,
  getfaceSimplexFileApi,
  cancelLogisticsOrderApi,
  getgetInterceptStateGroupList,
  interceptUpdateApi,
  changeExceptionOrderApi,
  updateExceptionOrderApi,
  rejectToApi,
  statusPushApi,
  completeDeliveryApi,
  updateSelfLogistics,
  uploadExpressSheet,
  printPickPdfByBatchNumberApi,
  printProductionPdfByBatchNumberApi,
  batchDownloadRecomposingApi,
  getCustomTagListCnApi,
} from '@/api/podCnOrder'

import { BaseRespData } from '@/types/api'

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

import { getAllCountryApi } from '@/api/logistics.ts'
import { InterceptStateGroupData } from '@/types/api/podUsOrder'
import TableView from '@/components/TableView.vue'
import {
  LogListData,
  PodCnOrderListData,
  ProductList,
  ProductionClient,
  SearchForm,
  Tab,
  WarehouseListData,
  cardImages,
  AddressInfo,
  LogisticsData,
  LogisticsFormData,
  CraftListData,
  ExportParams,
} from '@/types/api/podCnOrder'
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 PodDistributionOrder from './PodDistributionOrder.vue'
import SuperPodMakeOrder from './SuperPodMakeOrder.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 useUserStore from '@/store/user'
import BigNumber from 'bignumber.js'
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 userStore = useUserStore()

const isSuperFactory: boolean = userStore.user?.factory.dropShipping || false

const tabsNav = ref<Tab[]>()
const isAuto = ref(true)

const calculatedPrice = (item: ProductList) => {
  const templatePrice = new BigNumber(item.templatePrice || 0)
  const craftPrice = new BigNumber(item.craftPrice || 0)
  return templatePrice.plus(craftPrice).toString()
}
// const PREPAID_STATUSES = [
//   'TO_BE_CONFIRMED',
//   'EXCEPTION_ORDER',
//   'STOCK_OUT',
//   'CREATE_LOGISTICS',
//   'WAIT_SHIPMENT',
//   'INTERCEPTED',
// ] as const

const totalAmountPrice = (item: PodCnOrderListData): string => {
  // const usePrepaid = PREPAID_STATUSES.includes(status.value as typeof PREPAID_STATUSES[number])
  const productAmount = new BigNumber(item?.productAmount ?? 0)
  const serviceAmount = new BigNumber(item?.serviceAmount ?? 0)
  // const freightAmount = usePrepaid ? item?.prepaidAmount : item?.actualAmount
  const payFreight = new BigNumber(item?.prepaidAmount ?? 0)
  return productAmount.plus(serviceAmount).plus(payFreight).toString()
}
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: [],
  }
  // 使用函数封装映射逻辑
  const mapIds = (items: PodCnOrderListData[]) =>
    items.map((el) => Number(el.id))
  switch (resourceType) {
    case 0:
      params.idList = mapIds(tableData.value as PodCnOrderListData[])
      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 exportPodCnInfo({
      ...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 confirmData = ref([])
const searchVisible = ref(false)
const confirmSelectionData = ref<LogisticsData[]>([])
const confirmRowData = ref<ProductList | null>(null)
const status = ref(localStorage.getItem('podCnStatus') || 'TO_BE_CONFIRMED')

const detailData = ref({})
const [searchForm, resetSearchForm] = useValue<SearchForm>({
  timeType: 1,
  shopNumber: '',
  replaceShipment: '',
  shipmentType: '',
  userMark: '',
  processNumber: '',
  baseSku: '',
  factoryOrderNumber: '',
  sku: '',
  factorySubOrderNumber: '',
  status: '',
  customizedQuantity: '',
  multi: null,
  startTime: null,
  endTime: null,
  shipmentArea: undefined,
  platform: '',
  productionClient: '',
  warehouseId: '',
  thirdSkuCode: '',
  supplierProductNo: '',
  batchArrangeNumber: '',
  craftCode: '',
  thirdStockSku: '',
})
const shipmentArea = ref(0)
const userMarkList = ref<string[]>([])
const selection = ref<PodCnOrderListData[]>([])
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]
      },
    },
  ],
}
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 sizeList = ref<{ name: string; value: number }[]>([
  { name: '正常码', value: 1 },
  { name: '大码', value: 2 },
])

const handleRefreshAddress = async (row: PodCnOrderListData) => {
  try {
    await showConfirm('确定刷新地址吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  await refreshAddressApi([row.id])
  await ElMessageBox.alert(
    '请修改/刷新地址后取消物流或者更换物流在重新创建物流订单、获取跟踪号、获取打印面单',
    '提示',
    {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      showCancelButton: true,
    },
  )
}
const exceptionTypes = [
  { value: '1', label: '客户' },
  { value: '2', label: '工厂' },
]
const currentOrderIds = ref<number[]>([])
const exceptionDialogVisible = ref(false)
const exceptionFormRef = ref()
const exceptionForm = ref({
  exceptionType: '',
  exceptionReason: '',
})
const changeExceptionOrder = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  currentOrderIds.value = selection.value.map((item) => item.id)
  exceptionDialogVisible.value = true
}
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/podJomallOrderCn/distributionExceptionOrders'
      : 'factory/podJomallOrderCn/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 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 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 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 changeReplaceShipment = () => {
  searchForm.value.shipmentType = ''
}
const assignOrder = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  currentOrderIds.value = selection.value.map((item) => item.id)
  exceptionDialogVisible.value = true
}
const handleUpdateAddress = async (row: PodCnOrderListData) => {
  const { data } = await getAllCountryApi()
  countryList.value = data
  currentRow.value = JSON.parse(JSON.stringify(row))
  updateAddVisible.value = true
}
const exceptionStatus = ref(1)
const handleExceptionCommand = (command: number) => {
  exceptionStatus.value = command
  search()
}
const interceptCurrent = ref(1)
const interceptStatus = ref(0)

// 拦截状态改变
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 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: PodCnOrderListData) => 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 handleInterceptionCommand = (current: number, command: number) => {
  interceptCurrent.value = current
  interceptStatus.value = command
  search()
  loadTabData()
}
// 批量下载 下载
const handleDownload = async (row: PodCnOrderListData) => {
  try {
    await showConfirm('确定下载吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })

  const type = row.url && row.tiffUrl ? 'tiff' : row.url ? 'png' : 'tiff'
  try {
    const url =
      type === 'tiff'
        ? row.tiffUrl?.startsWith('/temp')
          ? `https://factory.jomalls.com/upload/factory` + row.tiffUrl
          : `https://ps.jomalls.com/tiff/` + row.tiffUrl
        : filePath + row.url

    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 refreshProductInformation = 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 refreshProductInformationApi({
      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 handleReComposingDesign = async () => {
  const row = { ...(typesettingRow.value as PodCnOrderListData) }

  reComposingLoadingMap[row.id] = true
  typesettingVisible.value = false

  const params: {
    id: number
    templateWidth?: number
    type?: string
  } = {
    id: row.id,
  }
  const { templateWidth, type } = typesettingForm.value
  if (templateWidth && type) {
    params.templateWidth = templateWidth
    params.type = type
  }
  try {
    const res = await batchDownloadRecomposingApi(params)
    if (res.code !== 200) return
    ElMessage.success(res.message)
    search()
    loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    reComposingLoadingMap[row.id] = false

    typesettingRow.value = undefined
  }
}
const tableColumns = computed(() => {
  if (status.value === 'BATCH_DOWNLOAD') {
    return [
      {
        label: '批次号',
        prop: 'batchArrangeNum',
        width: 120,
        align: 'center',
      },
      {
        label: '下载状态',
        slot: 'downloadStatus',
        width: 90,
        prop: 'downloadStatus',
        align: 'center',
      },
      {
        label: '订单数量',
        prop: 'productNum',
        width: 85,
        align: 'center',
      },
      {
        label: '素材数量',
        width: 85,
        prop: 'materialNum',
        align: 'center',
      },
      {
        label: '创建人',
        width: 85,
        prop: 'employeeAccount',
        align: 'center',
      },
      {
        label: '失败原因',
        minWidth: 250,
        prop: 'failReason',
        slot: 'failReason',
        align: 'left',
      },
      {
        label: '创建时间',
        width: 180,
        prop: 'createTime',
        slot: 'createTime',
        align: 'center',
      },
      {
        label: '完成时间',
        width: 180,
        prop: 'finishTime',
        slot: 'finishTime',
        align: 'center',
      },
      {
        label: '自动排版',
        width: 85,
        prop: 'automaticComposing',
        slot: 'automaticComposing',
        align: 'center',
      },
      {
        label: '排版参数',
        width: 140,
        prop: 'composingParam',
        slot: 'composingParam',
        align: 'center',
      },
      {
        label: '操作',
        slot: 'operate',
        width: 350,
        align: 'center',
        fixed: 'right',
        prop: 'operate',
      },
    ]
  }
  return [
    {
      label: '序号',
      prop: 'serialNumber',
      slot: 'serialNumber',
      width: 60,
      align: 'center',
    },
    {
      label: '商品',
      prop: 'goods',
      slot: 'goods',
      minWidth: 920,
    },
    {
      label: '订单详情',
      prop: 'orderDetail',
      slot: 'orderDetail',
      width: 300,
    },
    {
      label: '订单金额(￥)',
      slot: 'price',
      width: 160,
      prop: 'price',
      align: 'left',
    },
    {
      label: '时间',
      slot: 'time',
      width: 180,
      prop: 'time',
      align: 'left',
    },
    {
      label: '操作',
      slot: 'operate',
      width: 180,
      align: 'center',
      fixed: 'right',
      prop: 'operate',
    },
  ]
})
const rightMenuRef = ref()
const rightClick = (e: MouseEvent) => {
  rightMenuRef.value.setPosition({
    x: e.clientX,
    y: e.clientY,
  })
}
//展示返回结果
const resultInfo = ref<
  {
    id: string | number
    status: boolean
    factoryOrderNumber?: string
    message: string
  }[]
>([])
const resultConfirm = () => {
  search()
  loadTabData()
}

const handleSelectionChange = (val: PodCnOrderListData[]) => {
  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('podCnStatus', 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'
  ) {
    return { verticalAlign: 'top' }
  }
}
const interceptionStatus = ref<InterceptStateGroupData>({
  shipment: {},
  production: {},
})
const loadTabData = async () => {
  try {
    const res = await getOrderTabData()
    tabsNav.value = res.data
    // 获取拦截数量
    const statusRes = await getgetInterceptStateGroupList()
    interceptionStatus.value = statusRes.data as InterceptStateGroupData

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

    // 计算拦截总数）
    const calculateTotal = (data: Record<string, number>): number => {
      return Object.values(data).reduce(
        (sum, value) => sum + (Number(value) || 0),
        0,
      )
    }
    const totalIntercepted =
      calculateTotal(statusRes.data.shipment) +
      calculateTotal(statusRes.data.production)

    tabsNav.value.splice(completeIndex + 1, 0, {
      status: 'INTERCEPTED',
      statusName: '拦截',
      quantity: totalIntercepted,
    })
  } 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) => {
    const baseparams = {
      ...searchForm.value,
      startTime: timeRange.value?.[0] || null,
      endTime: timeRange.value?.[1] || null,
      tagsId: searchForm.value?.tagsIdArr?.join(',') || '',
    }
    baseparams.tagsIdArr && delete baseparams.tagsIdArr
    // 批量下载
    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(
        {
          ...baseparams,
          status: status.value === 'INTERCEPTED' ? '' : status.value,
          shipmentArea:
            status.value === 'CREATE_LOGISTICS'
              ? shipmentArea.value || undefined
              : undefined,
          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(
        {
          ...baseparams,
          status: status.value,
          interceptStatus: '',
        },
        page,
        pageSize,
      ).then((res) => res.data) as never
    }
  },
})

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')
}
const confirmManuShow = ref(false)
const confirmFormRef = ref()
const confirmForm = reactive({
  warehouseId: null,
})
const confirmRules = reactive({
  warehouseId: [
    {
      required: true,
      message: '请选择发货仓库',
      trigger: 'change',
    },
  ],
})
//确认生产
function confirmProduct() {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  confirmManuShow.value = true
  confirmFormRef.value.resetFields()
}
async function confirmSubmit() {
  try {
    await confirmFormRef.value.validate()
  } catch {
    return
  }
  const confirmName =
    warehouseList.value.find((item) => item.id == confirmForm.warehouseId)
      ?.name || '未知仓库'
  const ids = selection.value.map((el) => el.id).join(',')
  const params = {
    ids: ids,
    warehouseId: confirmForm.warehouseId,
    warehouseName: confirmName,
  }
  const { code, data } = await confirmProductApi(params)
  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('操作成功')
  confirmManuShow.value = false
}
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) => {
  navigator.clipboard.writeText(text)
  ElMessage.success('复制成功')
}
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, templateWidth: number) => {
  if (!cardSelection.value.length) {
    return ElMessage.warning('请选择数据')
  }
  if (type === 'tiff') {
    tifDownloadLoading.value = true
  } else {
    pngDownloadLoading.value = true
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await composingDesignImages(
      cardSelection.value.map((el) => el.id),
      type,
      templateWidth,
    )
    const url =
      type === 'tiff'
        ? res.message?.startsWith('/temp')
          ? `https://factory.jomalls.com/upload/factory` + res.message
          : `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
    }
  } finally {
    loading.close()
  }
}

const downloadTifItem = async () => {
  const row = { ...(typesettingRow.value as PodCnOrderListData) }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })

  try {
    const { templateWidth, type } = typesettingForm.value

    typesettingVisible.value = false

    // // 处理下载逻辑
    // if ((type as string[]).length > 1) {
    //   // 并行处理多个类型
    //   await Promise.allSettled(
    //     (type as string[]).map((el) =>
    //       downloadSingleType(row.id, el, templateWidth),
    //     ),
    //   )
    // } else {
    // 处理单个类型
    await downloadSingleType(row.id, type as string, templateWidth)
    // }
  } catch (error) {
    console.error('下载过程中出错:', error)
  } finally {
    typesettingRow.value = undefined
    loading.close()
  }
}

// 提取下载单个类型的逻辑为独立函数
const downloadSingleType = async (
  id: number,
  type: string,
  templateWidth?: number,
) => {
  try {
    const res = await composingDesignImages([id], type, templateWidth)
    const isTiff = type === 'tiff'
    const url = isTiff
      ? `https://ps.jomalls.com/tiff/${res.message}`
      : `${filePath}${res.message}`

    if (isTiff) {
      // 对于tiff类型，直接在新窗口打开
      window.open(url, '_blank')
    } else {
      // 对于其他类型，使用下载方式
      await downloadFile(url, res.message as string)
    }
  } catch (error) {
    console.error(`下载类型 ${type} 时出错:`, error)
    throw error // 重新抛出错误以便外部捕获
  }
}
const handleRadioGroupClick = (event: Event) => {
  const target = event.target as HTMLElement
  const radioButton = target.closest('.el-radio-button')
  
  if (radioButton) {
    const input = radioButton.querySelector('input[type="radio"]') as HTMLInputElement
    if (input) {
      const value = input.value
      if (searchForm.value.customizedQuantity === value) {
        event.preventDefault()
        event.stopPropagation()
        searchForm.value.customizedQuantity = ''
      }
    }
  }
}

const handleMultiRadioGroupClick = (event: Event) => {
  const target = event.target as HTMLElement
  const radioButton = target.closest('.el-radio-button')
  
  if (radioButton) {
    const input = radioButton.querySelector('input[type="radio"]') as HTMLInputElement
    if (input) {
      const value = input.value === 'true' ? true : false
      if (searchForm.value.multi === value) {
        event.preventDefault()
        event.stopPropagation()
        searchForm.value.multi = null
      }
    }
  }
}
// 提取文件下载逻辑为独立函数
const downloadFile = async (url: string, message: string) => {
  try {
    const response = await fetch(url)
    const blob = await response.blob()
    const filename = message.split('/').pop() || 'download'

    // 创建下载链接
    const a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = filename
    a.target = '_blank'

    // 模拟点击下载
    document.body.appendChild(a)
    a.click()

    // 清理
    setTimeout(() => {
      document.body.removeChild(a)
      URL.revokeObjectURL(a.href)
    }, 100)
  } catch (error) {
    console.error('下载文件时出错:', error)
    throw error // 重新抛出错误
  } finally {
    pngDownloadLoading.value = false
  }
}

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 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 printPickingOrderItem = async (
  row: { batchArrangeNum: string },
  type: number,
) => {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })

  try {
    let res
    if (type === 1) {
      res = await printPickPdfByBatchNumberApi({
        batchArrangeNumber: row.batchArrangeNum,
      })
    } else if (type === 2) {
      res = await printProductionPdfByBatchNumberApi({
        batchArrangeNumber: row.batchArrangeNum,
      })
    }

    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.podJomallOrderCnId)
  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 inputBlur = () => {
  if (!pageSize.value || Number(pageSize.value) <= 0) {
    pageSize.value = initPageSize.value
  }
  search()
}
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[] | PodCnOrderListData[])
      .map((item) => item?.shopNumber)
      .join()
    navigator.clipboard.writeText(str)
    ElMessage.success('复制成功')
  } else if (code === 'order-number') {
    const str = (tableData.value as ProductList[] | PodCnOrderListData[])
      .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' ||
    status.value === 'TO_BE_ARRANGE'
  ) {
    selectedIds = cardSelection.value
      .map((item: ProductList) => item.id)
      .filter((id): id is number => id !== undefined)
  } else {
    selectedIds = (selection.value as PodCnOrderListData[])
      .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)
    const a = document.createElement('a')
    a.href = filePath + res.message
    a.download = res.message!
    a.target = '_blank'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  } catch (e) {
    // showError(e)
    console.error(e)
  } finally {
    loading.close()
  }
}

// 排单完成
const arrangeFinish = async () => {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  const selectedIds = cardSelection.value.map((item) => item.id)
  const params: {
    productIdList: number[]
    templateWidth?: number
    type?: string
  } = {
    productIdList: selectedIds,
  }
  const { templateWidth, type } = typesettingForm.value
  if (templateWidth && type) {
    params.templateWidth = templateWidth
    params.type = type
  }

  typesettingVisible.value = false
  try {
    const res = await arrangeFinishApi(params)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

// 重新排版
const typesettingForm = ref<{
  typeArr?: string[]
  type?: string
  templateWidth?: number
}>({})

const typesettingVisible = ref(false)
const typesettingType = ref<number>()
const typesettingRow = ref<PodCnOrderListData>()

const showArrange = async (type: number, data?: PodCnOrderListData) => {
  typesettingType.value = type
  typesettingForm.value = {}
  if (type === 1 || type === 3) {
    typesettingRow.value = data
  } else if (type === 2) {
    const selectedIds = cardSelection.value.map((item) => item.id)

    if (selectedIds.length === 0) {
      return ElMessage({
        message: '请选择订单',
        type: 'warning',
        offset: window.innerHeight / 2,
      })
    }
    const bool = hasDifferentCraftCodeWithSet(cardSelection.value)
    if (bool) {
      try {
        await ElMessageBox.confirm(
          '选中排单的生产单存在多个工艺, 是否继续排单?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          },
        )

        typesettingVisible.value = true
      } catch (error) {
        return (typesettingVisible.value = false)
      }
    }
  }

  typesettingVisible.value = true
}

function hasDifferentCraftCodeWithSet(items: ProductList[]) {
  if (items.length <= 1) return false

  const seen = new Set()
  for (const item of items) {
    if (seen.has(item.craftCode)) {
      if (seen.size > 1) return true
    } else {
      seen.add(item.craftCode)
      if (seen.size > 1) return true
    }
  }
  return false
}

const submitTypesetting = () => {
  const { templateWidth, type } = typesettingForm.value

  // 如果是自动排版且没有填必选项
  if (isAuto.value && (!templateWidth || !type)) {
    return ElMessage.warning('排版类型和排版宽度为必选项')
  }

  // 针对排版宽度和类型分别判断
  if (!templateWidth && type) {
    return ElMessage.warning('请选择排版宽度')
  }
  if (templateWidth && !type) {
    return ElMessage.warning('请选择排版类型')
  }

  // 针对类型 3 的特殊判断
  if (typesettingType.value === 3 && (!templateWidth || !type)) {
    return ElMessage.warning('排版类型和排版宽度为必选项')
  }

  // 设置为自动排版
  isAuto.value = true

  // 根据排版类型执行相应的操作
  switch (typesettingType.value) {
    case 1:
      return handleReComposingDesign()
    case 2:
      return arrangeFinish()
    default:
      return downloadTifItem()
  }
}

const changeSwitch = () => {
  typesettingForm.value = {}
}

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
    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 podDistributionOrderVisible = ref(false)
const podDistributionOrderShow = async () => {
  podDistributionOrderVisible.value = true
}
const superPodOrderVisible = ref(false)
const printSuperPodOrder = async () => {
  const lodop = getCLodop(null, null)
  if (!lodop) return

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

/**
 * @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 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 PodCnOrderListData[]
    ).reduce(
      (acc, item) => {
        successIds.includes(item.id)
          ? acc.success.push(item)
          : acc.others.push(item)
        return acc
      },
      {
        success: [] as PodCnOrderListData[],
        others: [] as PodCnOrderListData[],
      },
    )

    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) => {
  sheetPrinter.value = value
  localStorage.setItem('sheetPrinter', JSON.stringify(value))
}
const handleWarehouseIdChange = (value: string) => {
  sessionStorage.setItem('locaclCnWarehouseId', 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: PodCnOrderListData }) => {
  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 customTagList = ref<{ id: string; name: string }[]>([])

const getCustomTagList = async () => {
  try {
    const res = await getCustomTagListCnApi()
    if (res.code !== 200) return
    customTagList.value = res.data
  } catch (e) {
    console.error(e)
  }
}

function tooltipContent(arr: { name: string }[]) {
  return arr.map((tag) => tag.name).join('、')
}
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 showLogistics = (item: PodCnOrderListData) => {
  currentRow.value = JSON.parse(JSON.stringify(item))
  logisticsVisible.value = true
  logisticsForm.value = JSON.parse(JSON.stringify(logistics))
}
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()
    }
  })
}
watch(
  // () => status.value,
  // (val) => {
  //   const currentUrl = new URL(window.location.href)
  //   currentUrl.searchParams.set('tab', val)

  //   window.history.pushState({}, '', currentUrl)
  // },
  // { immediate: true },
  () => [...(tableData.value as PodCnOrderListData[])], // 创建新数组避免直接修改原始数据
  (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确保初始化时执行
)

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

const handleShipmentAreaCommand = (command: number) => {
  shipmentArea.value = command
  search()
}
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.podJomallOrderCnId,
            productId: item.id,
            factorySubOrderNumber: item.factorySubOrderNumber || '',
            replenishmentNum: res.value,
            podJomallOrderCnStatus: status.value,
          }
        })
      } else {
        data = [
          {
            id: row.podJomallOrderCnId,
            productId: row.id,
            factorySubOrderNumber: row.factorySubOrderNumber || '',
            replenishmentNum: res.value,
            podJomallOrderCnStatus: 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 ?? '',
      podJomallOrderCnId: el.podJomallOrderCnId ?? '',
      factorySubOrderNumber: el.factorySubOrderNumber ?? '',
      version: el.version ?? '',
    }
  })

  try {
    const res = await updateToWaitShipmentApi({ cnUpdateParams: 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('podCnStatus')
  next()
}

const getTagName = (row: ProductList) => {
  return row.customTagList?.length
    ? row.customTagList.map((item: { name: string }) => item.name).join(',')
    : ''
}

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;
  }
}

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

  .goods-item-img {
    // width: 100px;
    // height: 100px;
    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;
  .flex-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .images-position {
      display: flex;
      height: 30px;
      gap: 10px;
      .item-image {
        width: 30px;
        height: 30px;
        border: 1px solid #909399;
        cursor: pointer;
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
    }
    b {
      margin-right: 5px;
      font-size: 15px;
    }
  }
  .flex-row {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    gap: 15px;
  }
}

.images-position {
  display: flex;
  gap: 5px;

  .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;

    .grid-item-value {
      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 {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.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;
  }
}
</style>
