<template>
  <div class="card flex-column h-100 overflow-hidden">
    <div class="header-filter-form">
      <ElForm
        ref="searchFormRef"
        class="search-form"
        label-position="right"
        label-width="70px"
        :model="searchForm"
        size="default"
        inline
      >
        <!-- 批量下载 -->
         <ElFormItem label="创建时间"  v-if="
            status === 'BATCH_DOWNLOAD'
          ">
                  <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),
                    ]"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetimerange"
                    style="width: 280px"
                    :shortcuts="pickerOptions.shortcuts"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    clearable
                  >
                  </el-date-picker>
          </ElFormItem>
          <ElFormItem label="创建人"  v-if="
            status === 'BATCH_DOWNLOAD'
          ">
            <ElSelect
              v-model="searchForm.employeeId"
              placeholder="请选择"
              clearable
              :teleported="false"
              style="width: 150px"
            >
              <ElOption
                v-for="(item, index) in employeeList"
                :key="index"
                :value="item.id"
                :label="item.account"
              ></ElOption>
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="工艺类型"  v-if="
            status === 'BATCH_DOWNLOAD'
          ">
                <ElSelect
                  v-model="searchForm.craftType"
                  placeholder="请选择"
                  clearable
                  filterable
                  :teleported="false"
                  style="width: 150px"
                >
                  <ElOption
                    v-for="(item, index) in processType"
                    :key="index"
                    :value="item.value"
                    :label="item.label"
                  ></ElOption>
                </ElSelect>
          </ElFormItem>
          <ElFormItem label="下载状态" v-if="
            status === 'BATCH_DOWNLOAD'
          ">
              <ElSelect
                v-model="searchForm.downloadStatus"
                placeholder="下载状态"
                clearable
                :teleported="false"
                style="width: 150px"
                >
                <ElOption
                  v-for="(item, index) in ['未下载', '已下载']"
                  :key="index"
                  :value="index"
                  :label="item"
                ></ElOption>
              </ElSelect>
          </ElFormItem>
          <ElFormItem label="排版状态" v-if="
            status === 'BATCH_DOWNLOAD'
          ">
              <ElSelect
                v-model="searchForm.syntheticStatus"
                placeholder="排版状态"
                clearable
                :teleported="false"
                style="width: 150px"
                >
                <ElOption
                  v-for="(item, index) in ['否', '是']"
                  :key="index"
                  :value="index"
                  :label="item"
                ></ElOption>
              </ElSelect>
          </ElFormItem>
          <ElFormItem label="自动排版" v-if="
            status === 'BATCH_DOWNLOAD'
          ">
              <ElSelect
                v-model="searchForm.automaticComposing"
                placeholder="自动排版"
                clearable
                :teleported="false"
                style="width: 150px"
                >
                <ElOption
                  v-for="(item, index) in ['否', '是']"
                  :key="index"
                  :value="index"
                  :label="item"
                ></ElOption>
              </ElSelect>
          </ElFormItem>
        <!-- <div> -->
        <ElFormItem label="仓库" v-if="
            status !== 'BATCH_DOWNLOAD'
          ">
          <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="工艺" v-if="
            status !== 'BATCH_DOWNLOAD'
          ">
          <LogisticsWaySelect
            v-model="searchForm.craftCode"
            :company-list="craftList"
            :start-width="'178px'"
            search-placeholder="搜索工艺名称"
            start-placeholder="请选择工艺名称"
          ></LogisticsWaySelect>
        </ElFormItem>
        <ElFormItem label="库存SKU" v-if="
            status !== 'BATCH_DOWNLOAD'
          ">
          <ElInput
            v-model.trim="searchForm.thirdSkuCode"
            placeholder="库存SKU"
            clearable
            style="width: 150px"
          ></ElInput>
        </ElFormItem>
        <ElFormItem label="款号" v-if="
            status !== 'BATCH_DOWNLOAD'
          ">
          <ElInput
            v-model="searchForm.supplierProductNo"
            placeholder="款号"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <ElFormItem label="批次号">
          <ElInput
            v-model="searchForm.batchArrangeNumber"
            placeholder="批次号"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <ElFormItem label="生产单号" v-if="
            status !== 'BATCH_DOWNLOAD'
          ">
          <ElInput
            v-model="searchForm.factorySubOrderNumber"
            placeholder="生产单号"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <ElFormItem label="店铺单号" v-if="
            status !== 'BATCH_DOWNLOAD'
          ">
          <ElInput
            v-model="searchForm.shopNumber"
            placeholder="店铺单号"
            clearable
            style="width: 150px"
          />
        </ElFormItem>
        <ElFormItem label="尺码类型" v-if="
            status !== 'BATCH_DOWNLOAD'
          ">
          <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="平台" v-if="
            status !== 'BATCH_DOWNLOAD'
          ">
          <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>
        <!-- </div> -->
        <ElFormItem label="类型" v-if="
            status !== 'BATCH_DOWNLOAD'
          ">
          <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-button label="normal">普品</el-radio-button>
          </el-radio-group>
        </ElFormItem>
        <ElFormItem label="数量" v-if="
            status !== 'BATCH_DOWNLOAD'
          ">
          <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"  v-if="
            status !== 'BATCH_DOWNLOAD'
          ">
            <ElForm
              ref="searchFormPopoverRef"
              :model="searchForm"
              size="default"
              inline
              label-width="100px"
            >
              <ElFormItem style="width: 100%; padding-right: 40px">
                <div style="width: 100%; display: flex; flex-wrap: nowrap">
                  <el-select
                    v-model="searchForm.timeType"
                    clearable
                    :teleported="false"
                    placeholder="时间类型"
                    style="flex: 1; margin-right: 10px"
                  >
                    <el-option :value="1" label="创建时间"></el-option>
                    <el-option :value="2" label="确认时间"></el-option>
                    <el-option :value="3" label="发货时间"></el-option>
                  </el-select>
                  <el-date-picker
                    v-model="timeRange"
                    :teleported="false"
                    :default-time="[
                      new Date(0, 0, 0, 0, 0, 0),
                      new Date(0, 0, 0, 23, 59, 59),
                    ]"
                    placeholder="收货人"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetimerange"
                    style="width: 280px"
                    :shortcuts="pickerOptions.shortcuts"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    clearable
                  >
                  </el-date-picker>
                </div>
              </ElFormItem>
              <ElFormItem label="订单号">
                <ElInput
                  v-model="searchForm.factoryOrderNumber"
                  placeholder="订单号"
                  clearable
                  style="width: 150px"
                />
              </ElFormItem>

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

              <ElFormItem label="生产端">
                <ElSelect
                  v-model="searchForm.productionClient"
                  placeholder="生产端"
                  clearable
                  :teleported="false"
                  style="width: 150px"
                >
                  <ElOption
                    v-for="(item, index) in productionClient"
                    :key="index"
                    :value="item.code || ''"
                    :label="`${item.remark}(${item.code})`"
                  ></ElOption>
                </ElSelect>
              </ElFormItem>
              <ElFormItem label="Variant SKU">
                <ElInput
                  v-model.trim="searchForm.sku"
                  placeholder="Variant SKU"
                  clearable
                  style="width: 150px"
                ></ElInput>
              </ElFormItem>
              <!-- <ElFormItem label="Base SKU">
                <ElInput
                  v-model.trim="searchForm.baseSku"
                  placeholder=" Base SKU"
                  clearable
                  style="width: 150px"
                ></ElInput>
              </ElFormItem> -->
              <ElFormItem label="物流跟踪号">
                <ElInput
                  v-model.trim="searchForm.trackingNumber"
                  placeholder="物流跟踪号"
                  clearable
                  style="width: 150px"
                ></ElInput>
              </ElFormItem>
              <ElFormItem label="物流类型">
                <ElSelect
                  v-model="searchForm.shipmentType"
                  placeholder="物流类型"
                  clearable
                  :teleported="false"
                  style="width: 150px"
                  :disabled="searchForm.replaceShipment === 0"
                >
                  <ElOption
                    v-for="(item, index) in shipmentList"
                    :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>
              <ElFormItem label="是否代发">
                <ElSelect
                  v-model="searchForm.replaceShipment"
                  placeholder="请选择"
                  clearable
                  :teleported="false"
                  style="width: 150px"
                  @change="
                    (e:number) => {
                      if (e == 0) {
                        shipmentList=['自提','快递']
                        searchForm.shipmentType=0
                      }else{
                        shipmentList=['自有物流', '工厂物流']
                        searchForm.shipmentType=''
                      }
                    }
                  "
                >
                  <ElOption
                    v-for="(item, index) in [
                      { value: 1, label: '代发' },
                      { value: 0, label: '不代发' },
                    ]"
                    :key="index"
                    :value="item.value"
                    :label="item.label"
                  ></ElOption>
                </ElSelect>
              </ElFormItem>
              <ElFormItem label="物流方式">
                <ElSelect
                  v-model="searchForm.logisticsWayId"
                  placeholder="请选择"
                  clearable
                  :teleported="false"
                  style="width: 150px"
                >
                  <ElOption
                    v-for="(item, index) in logisticsWayList"
                    :key="index"
                    :value="item.id"
                    :label="item.name"
                  ></ElOption>
                </ElSelect>
              </ElFormItem>
              <ElFormItem label="订单来源">
                <ElSelect
                  v-model="searchForm.source"
                  placeholder="请选择"
                  clearable
                  :teleported="false"
                  style="width: 150px"
                >
                  <ElOption
                    v-for="(item, index) in sourceList"
                    :key="index"
                    :value="item.id"
                    :label="item.name"
                  ></ElOption>
                </ElSelect>
              </ElFormItem>
              <ElFormItem label="尺码筛选">
                <ElSelect
                  v-model="searchForm.size"
                  placeholder="请选择"
                  clearable
                  filterable
                  :teleported="false"
                  style="width: 150px"
                >
                  <ElOption
                    v-for="(item, index) in sizes"
                    :key="index"
                    :value="item"
                    :label="item"
                  ></ElOption>
                </ElSelect>
              </ElFormItem>
              <ElFormItem label="拦截订单">
                <ElSelect
                  v-model="searchForm.blocking"
                  placeholder="请选择"
                  clearable
                  filterable
                  :teleported="false"
                  style="width: 150px"
                >
                  <ElOption
                    v-for="(_, index) in ['否', '是']"
                    :key="index"
                    :value="!!index"
                    :label="index === 0 ? '否' : '是'"
                  ></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 style="font-size: 12px" @click="resetSearchForm"
              ><span title="重置查询条件">重置</span></ElButton
            >
          </span>
        </ElFormItem>
        <ElFormItem>
          <span>
            <ElButton ref="searchBtnRef" 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
          v-if="
            status === 'PICKING' ||
            status === 'TO_BE_REPLENISHMENT' ||
            status === 'IN_PRODUCTION'
          "
        >
          <span class="item">
            <ElButton
              :loading="tifDownloadLoading"
              type="warning"
              @click="downloadTif('tiff')"
            >
              TIF排版
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="
            status === 'PICKING' ||
            status === 'TO_BE_REPLENISHMENT' ||
            status === 'IN_PRODUCTION'
          "
        >
          <span class="item">
            <ElButton
              :loading="pngDownloadLoading"
              type="warning"
              @click="downloadTif('png')"
            >
              PNG排版
            </ElButton>
          </span>
        </ElFormItem> -->
        <ElFormItem v-if="status === 'TO_BE_CONFIRMED'">
          <span class="item">
            <ElButton type="success" @click="confirmProduct">
              确认生产
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'EXCEPTION_ORDER'">
          <span class="item">
            <ElButton type="success" @click="updateOrder">
              转至待确认
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="status === 'EXCEPTION_ORDER' && exceptionStatus === 3"
        >
          <span class="item">
            <ElButton type="warning" @click="asyncOrderAddress">
              同步收货地址
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="status === 'EXCEPTION_ORDER' && exceptionStatus === 1"
        >
          <span class="item">
            <ElButton type="warning" @click="assignOrder"> 分派 </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="
            status === 'PICKING' ||
            status === 'TO_BE_REPLENISHMENT' ||
            status === 'IN_PRODUCTION'
          "
        >
          <!-- <span
          v-if="status === 'EXCEPTION_ORDER' && exceptionStatus === 2"
          class="item"
        >
          <ElButton type="warning" @click="handleExceptionOrder">
            处理异常
          </ElButton>
        </span> -->
          <span class="item">
            <ElButton type="primary" @click="printProductionOrder(2, null)">
              打印生产单
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'TO_BE_REPLENISHMENT'">
          <span class="item">
            <ElButton type="success" @click="replenishmentSuccess">
              补胚完成
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'PICKING'">
          <span class="item">
            <ElButton type="success" @click="printPickingOrder">
              打印拣货单
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'PICKING'">
          <span class="item">
            <ElButton type="warning" @click="pickingComplete">
              拣胚完成
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'PICKING'">
          <span class="item">
            <ElButton type="success" @click="toOutOfStock"> 转至缺货 </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'TO_BE_CONFIRMED'">
          <span class="item">
            <ElButton type="warning" @click="changeExceptionOrder">
              转为异常单
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="status === 'TO_BE_CONFIRMED' && isPermissionBtn('RIIN')"
        >
          <span class="item">
            <ElButton type="success" @click="confirmProductToRiin">
              转至锐印生产
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="status === 'TO_BE_CONFIRMED' || status === 'EXCEPTION_ORDER'"
        >
          <span class="item">
            <ElButton type="danger" @click="cancelOrder">取消</ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'IN_PRODUCTION'">
          <!-- <span v-if="status !== 'IN_PRODUCTION'" class="item">
          <ElButton type="success" @click="handleUpdateRemark">
            添加内部标签
          </ElButton>
        </span> -->
          <span class="item">
            <ElButton type="warning" @click="onFastProduction">
              快捷生产
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'IN_PRODUCTION'">
          <span class="item">
            <ElButton type="success" @click="applyForReplenishment(undefined)">
              申请补胚
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'IN_PRODUCTION'">
          <span class="item">
            <ElButton type="success" @click="productioncompleted">
              生产完成
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'WAIT_SHIPMENT'">
          <span class="item">
            <ElButton type="warning" @click="printPodOrder">
              播种墙配货
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'CREATE_LOGISTICS'">
          <!-- <span v-if="status === 'WAIT_SHIPMENT'" class="item">
            <ElButton type="warning" @click="inspPackagOrder">
              质检包装
            </ElButton>
          </span> -->
          <span class="item">
            <ElButton type="warning" @click="logisticsToPicking">
              转至待排单
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'WAIT_SHIPMENT'">
          <span class="item">
            <ElButton type="primary" @click="completeDelivery()"
              >完成发货</ElButton
            >
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="status === 'WAIT_SHIPMENT' || status === 'CREATE_LOGISTICS'"
        >
          <span class="item">
            <ElDropdown>
              <el-button type="success">
                物流接口<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <ElDropdownMenu>
                  <ElDropdownItem
                    :disabled="
                      (selection.length === 0 && cardSelection.length === 0) ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('createLogisticsOrder')"
                    >创建物流订单</ElDropdownItem
                  >
                  <ElDropdownItem
                    :disabled="
                      (selection.length === 0 && cardSelection.length === 0) ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('getTrackingNumber')"
                    >获取跟踪号</ElDropdownItem
                  >
                  <ElDropdownItem
                    :disabled="
                      (selection.length === 0 && cardSelection.length === 0) ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('getPrintOrder')"
                    >获取打印面单</ElDropdownItem
                  >
                  <ElDropdownItem
                    :disabled="
                      (selection.length === 0 && cardSelection.length === 0) ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('cancelLogisticsOrder')"
                    >取消物流订单</ElDropdownItem
                  >
                  <!-- <ElDropdownItem
                    :disabled="
                      selection.length === 0 ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('batchChangeLogistics')"
                    >更换物流</ElDropdownItem
                  > -->
                </ElDropdownMenu>
              </template>
            </ElDropdown>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'STOCK_OUT'">
          <span class="item">
            <ElButton type="warning" @click="stockOutCheck">
              补货校验
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'STOCK_OUT'">
          <span class="item">
            <ElButton type="success" @click="toBePicking"> 转至生产 </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'TO_BE_ARRANGE'">
          <span class="item">
            <ElButton type="warning" @click="showArrange(2)">排单</ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="status !== 'BATCH_DOWNLOAD' && status !== 'WAIT_SHIPMENT'"
        >
          <span class="item">
            <ElButton type="primary" @click="downloadMaterial"
              >下载素材</ElButton
            >
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="
            status === 'INTERCEPTED' &&
            (interceptCurrent === 1 || interceptCurrent === 4)
          "
        >
          <span class="item">
            <ElButton type="success" @click="interceptChange(true)">
              拦截成功
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="
            status === 'INTERCEPTED' &&
            (interceptCurrent === 1 || interceptCurrent === 4)
          "
        >
          <span class="item">
            <ElButton type="danger" @click="interceptChange(false)">
              拦截失败
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="
            [
              'TO_BE_CONFIRMED',
              'PICKING',
              'STOCK_OUT',
              'EXCEPTION_ORDER',
              'TO_BE_REPLENISHMENT',
              'IN_PRODUCTION',
              'TO_BE_ARRANGE',
              'WAIT_SHIPMENT',
            ].includes(status)
          "
        >
          <span class="item">
            <ElButton type="success" @click="refreshMaterial">
              刷新商品信息
            </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="['WAIT_SHIPMENT'].includes(status)">
          <span class="item">
            <ElButton type="primary" @click="printNormal"> 普货拣货 </ElButton>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="
            [
              'STOCK_OUT',
              'CREATE_LOGISTICS',
              'TO_BE_ARRANGE',
              'PICKING',
              'IN_PRODUCTION',
            ].includes(status)
          "
        >
          <span class="item">
            <ElDropdown>
              <el-button type="warning">
                驳回至<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <ElDropdownMenu>
                  <ElDropdownItem
                    :disabled="
                      selection.length === 0 && cardSelection.length === 0
                    "
                    @click="rejectOrder('TO_BE_CONFIRMED')"
                    >待确认</ElDropdownItem
                  >
                  <ElDropdownItem
                    v-if="
                      status === 'IN_PRODUCTION' ||
                      status === 'TO_BE_ARRANGE' ||
                      status === 'PICKING'
                    "
                    :disabled="
                      selection.length === 0 && cardSelection.length === 0
                    "
                    @click="rejectOrder('CREATE_LOGISTICS')"
                    >待创建物流</ElDropdownItem
                  >
                  <ElDropdownItem
                    v-if="status === 'PICKING' || status === 'IN_PRODUCTION'"
                    :disabled="
                      selection.length === 0 && cardSelection.length === 0
                    "
                    @click="rejectOrder('TO_BE_ARRANGE')"
                    >待排单</ElDropdownItem
                  >
                  <ElDropdownItem
                    v-if="status === 'IN_PRODUCTION'"
                    :disabled="
                      selection.length === 0 && cardSelection.length === 0
                    "
                    @click="rejectOrder('PICKING')"
                    >待拣胚</ElDropdownItem
                  >
                </ElDropdownMenu>
              </template>
            </ElDropdown>
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="['WAIT_TRACK', 'COMPLETE', 'IN_TRANSIT'].includes(status)"
        >
          <span class="item">
            <ElButton type="warning" @click="statusPush">状态推送</ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="['WAIT_TRACK'].includes(status)">
          <span class="item">
            <ElButton type="success" @click="setFinish">转至已完成</ElButton>
          </span>
        </ElFormItem>

        <ElFormItem v-if="status === 'COMPLETE'">
          <span class="item">
            <ElButton type="success" @click="exportData">导出</ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'BATCH_DOWNLOAD'">
          <span class="item">
            <ElButton type="danger" @click="handleBatchDelete('batch')"
              >批量删除</ElButton
            >
          </span>
        </ElFormItem>
        <ElFormItem
          v-if="['WAIT_TRACK'].includes(status) && waitTrackStatus === 5"
        >
          <span class="item">
            <ElButton type="success" @click="reissueOrder">补发</ElButton>
          </span>
        </ElFormItem>
        <ElFormItem v-if="status === 'WAIT_SHIPMENT'">
          <span class="item">
            <ElButton type="warning" @click="showPrintSku"
              >打印库存sku标签</ElButton
            >
          </span>
        </ElFormItem>
      </ElForm>
    </div>
    <div class="header-filter-tab">
      <div class="tabs">
        <div
          v-for="item in tabsNav"
          :key="item.status"
          class="tabs-node"
          :class="item.status === status ? 'tabs-node_active' : ''"
          @click="changeTab(item)"
        >
          <span class="tabs-node_label">{{ item.statusName }}</span>
          <span
            v-if="item.quantity"
            class="tabs-node_count"
            :class="{
              blue: item.quantity && item.quantity > 0,
              red: item.status === 'EXCEPTION_ORDER',
            }"
            >{{ item.quantity }}</span
          >
          <span
            v-if="
              item.status === 'INTERCEPTED' &&
              (interceptionStatus.production['0'] ||
                interceptionStatus.shipment['0'])
            "
            class="tabs-node-quantity"
            >+{{
              (interceptionStatus.production['0'] || 0) +
                (interceptionStatus.shipment['0'] || 0) || ''
            }}</span
          >
        </div>
      </div>
    </div>
    <div class="order-content flex-1 flex-column overflow-hidden mt-10">
      <div v-if="status === 'EXCEPTION_ORDER'" class="sub-status mb-10">
        <div
          class="sub-status-item"
          :class="exceptionStatus === 1 ? 'sub-active' : ''"
          @click="handleExceptionCommand(1)"
        >
          <span class="sub-status-item-label">待分派</span>
        </div>
        <div
          class="sub-status-item"
          :class="exceptionStatus === 2 ? 'sub-active' : ''"
          @click="handleExceptionCommand(2)"
        >
          <span class="sub-status-item-label">待处理</span>
        </div>
        <div
          class="sub-status-item"
          :class="exceptionStatus === 3 ? 'sub-active' : ''"
          @click="handleExceptionCommand(3)"
        >
          <span class="sub-status-item-label">待同步</span>
        </div>
      </div>
      <div v-if="status === 'WAIT_TRACK'" class="sub-status mb-10">
        <div
          class="sub-status-item"
          :class="waitTrackStatus === 1 ? 'sub-active' : ''"
          @click="handleWaitTrackCommand(1)"
        >
          <span class="sub-status-item-label">{{
            trackRegisterCount[0]?.name
          }}</span>
          <span class="tabs-node_count">{{
            trackRegisterCount[0]?.count || 0
          }}</span>
        </div>
        <div
          class="sub-status-item"
          :class="waitTrackStatus === 2 ? 'sub-active' : ''"
          @click="handleWaitTrackCommand(2)"
        >
          <span class="sub-status-item-label">{{
            trackRegisterCount[1]?.name
          }}</span>
          <span class="tabs-node_count blue">{{
            trackRegisterCount[1]?.count || 0
          }}</span>
        </div>
        <div
          class="sub-status-item"
          :class="waitTrackStatus === 3 ? 'sub-active' : ''"
          @click="handleWaitTrackCommand(3)"
        >
          <span class="sub-status-item-label">{{
            trackRegisterCount[2]?.name
          }}</span>
          <span class="tabs-node_count green">{{
            trackRegisterCount[2]?.count || 0
          }}</span>
        </div>
        <div
          class="sub-status-item"
          :class="waitTrackStatus === 4 ? 'sub-active' : ''"
          @click="handleWaitTrackCommand(4)"
        >
          <span class="sub-status-item-label">{{
            trackRegisterCount[3]?.name
          }}</span>
          <span class="tabs-node_count yellow">{{
            trackRegisterCount[3]?.count || 0
          }}</span>
        </div>
        <div
          class="sub-status-item"
          :class="waitTrackStatus === 5 ? 'sub-active' : ''"
          @click="handleWaitTrackCommand(5)"
        >
          <span class="sub-status-item-label">{{
            trackRegisterCount[4]?.name
          }}</span>
          <span class="tabs-node_count red">{{
            trackRegisterCount[4]?.count || 0
          }}</span>
        </div>
      </div>
      <div v-if="status === 'INTERCEPTED'" class="sub-status mb-10">
        <div
          class="sub-status-item"
          :class="interceptCurrent === 1 ? 'sub-active' : ''"
          @click="handleInterceptionCommand(1, 0)"
        >
          <span class="sub-status-item-label">生产拦截申请</span>
          <span
            v-if="interceptionStatus.production['0']"
            class="tabs-node_count blue"
            >{{ interceptionStatus.production['0'] }}</span
          >
        </div>
        <div
          class="sub-status-item"
          :class="interceptCurrent === 2 ? 'sub-active' : ''"
          @click="handleInterceptionCommand(2, 1)"
        >
          <span class="sub-status-item-label">生产拦截成功</span>
          <span
            v-if="interceptionStatus.production['1']"
            class="tabs-node_count blue"
            >{{ interceptionStatus.production['1'] }}</span
          >
        </div>
        <div
          class="sub-status-item"
          :class="interceptCurrent === 3 ? 'sub-active' : ''"
          @click="handleInterceptionCommand(3, 2)"
        >
          <span class="sub-status-item-label">生产拦截失败</span>
          <span
            v-if="interceptionStatus.production['2']"
            class="tabs-node_count red"
            >{{ interceptionStatus.production['2'] }}</span
          >
        </div>
        <div
          class="sub-status-item"
          :class="interceptCurrent === 4 ? 'sub-active' : ''"
          @click="handleInterceptionCommand(4, 2)"
        >
          <span class="sub-status-item-label">发货拦截申请</span>
          <span
            v-if="interceptionStatus.shipment['0']"
            class="tabs-node_count blue"
            >{{ interceptionStatus.shipment['0'] }}</span
          >
        </div>
        <div
          class="sub-status-item"
          :class="interceptCurrent === 5 ? 'sub-active' : ''"
          @click="handleInterceptionCommand(5, 3)"
        >
          <span class="sub-status-item-label">发货拦截成功</span>
          <span
            v-if="interceptionStatus.shipment['1']"
            class="tabs-node_count blue"
            >{{ interceptionStatus.shipment['1'] }}</span
          >
        </div>
        <div
          class="sub-status-item"
          :class="interceptCurrent === 6 ? 'sub-active' : ''"
          @click="handleInterceptionCommand(6, 4)"
        >
          <span class="sub-status-item-label">发货拦截失败</span>
          <span
            v-if="interceptionStatus.shipment['2']"
            class="tabs-node_count red"
            >{{ interceptionStatus.shipment['2'] }}</span
          >
        </div>
      </div>
      <div
        v-if="
          status !== 'IN_PRODUCTION' &&
          status !== 'PICKING' &&
          status !== 'TO_BE_REPLENISHMENT' &&
          status !== 'TO_BE_ARRANGE'
        "
        v-loading="loading"
        element-loading-text="加载中..."
        class="table-wrapper flex-1 flex-column overflow-hidden"
        @contextmenu.prevent="(v) => rightClick(v)"
      >
        <TableView
          ref="tableRef"
          :columns="tableColumns"
          :selectionable="true"
          :paginated-data="tableData"
          :cell-style="onCellStyle"
          :cell-class-name="onCellClassName"
          :row-style="getRowStyle"
          @selection-change="handleSelectionChange"
        >
          <template #serialNumber="{ row, index }">
            <div>
              <el-tooltip
                v-if="
                  status !== 'INTERCEPTED' &&
                  (row.interceptStatus == 0 || row.interceptStatus == 2)
                "
                effect="light"
                :content="
                  row.interceptStatus == 0
                    ? '订单已提交至生产拦截申请'
                    : '订单已提交至发货拦截申请'
                "
                placement="bottom"
              >
                <el-icon color="#E6A23C">
                  <InfoFilled />
                </el-icon>
              </el-tooltip>
              <span class="serial-number">{{ index + 1 }}</span>
            </div>
          </template>
          <template #goods="{ row }">
            <div class="goods-info-box">
              <div class="goods-list">
                <div
                  v-for="item in row.productList"
                  :key="item"
                  class="goods-item"
                >
                  <div
                    class="goods-item-img"
                    style="display: flex; flex-direction: column"
                  >
                    <template v-if="item.previewImgs?.length">
                      <div
                        v-for="img in item.previewImgs"
                        :key="img"
                        style="text-align: center"
                      >
                        <img
                          :src="img.url"
                          alt="商品图片"
                          style="cursor: pointer"
                          @click="handlePictureCardPreview(img.url)"
                        />
                        <div
                          v-if="item.customizedQuantity"
                          class="triangle-box"
                          :title="`类型:${getQuantityText(
                            item.customizedQuantity,
                          )}面`"
                        >
                          <div class="multi-text">
                            {{ getQuantityText(item.customizedQuantity) }}
                          </div>
                        </div>
                      </div>
                    </template>
                    <template v-else>
                      <img
                        :src="item.variantImage"
                        alt="商品图片"
                        style="cursor: pointer"
                        @click="handlePictureCardPreview(item.variantImage)"
                      />
                      <div class="triangle-container-wrap">
                        <div class="triangle-container">
                          <div class="triangle-marker"></div>
                          <div
                            class="content"
                            :title="handleMark(item.productMark).label"
                          >
                            {{ handleMark(item.productMark).name }}
                          </div>
                        </div>
                      </div>
                    </template>
                  </div>
                  <div class="goods-item-info">
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">商品名称:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.productName }}
                      </span>
                    </div>
                    <!-- <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">Base SKU:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.baseSku }}
                      </span>
                      <el-icon class="icon" @click="copy(item.baseSku || '')">
                        <DocumentCopy />
                      </el-icon>
                    </div> -->
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">变体SKU:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.variantSku }}
                      </span>
                      <el-icon
                        class="icon"
                        @click="copy(item.variantSku || '')"
                      >
                        <DocumentCopy />
                      </el-icon>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">库存SKU:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.thirdSkuCode }}
                      </span>
                      <el-icon
                        class="icon"
                        @click="copy(item.thirdSkuCode || '')"
                      >
                        <DocumentCopy />
                      </el-icon>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">货号:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.thirdStockSku }}
                      </span>
                      <el-icon
                        class="icon"
                        @click="copy(item.thirdStockSku || '')"
                      >
                        <DocumentCopy />
                      </el-icon>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">工艺:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.craftName }}
                      </span>
                    </div>

                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">备注:</span>
                      <span
                        class="goods-item-info-item-value"
                        :title="item.remark"
                      >
                        {{ item.remark }}
                      </span>
                      <el-icon
                        class="icon"
                        style="color: #e6a23c"
                        @click="handleUpdateRemark(item)"
                      >
                        <EditPen />
                      </el-icon>
                    </div>
                  </div>
                  <div class="goods-item-info">
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">生产单号:</span>
                      <span
                        class="goods-item-info-item-value"
                        :title="item.factorySubOrderNumber"
                      >
                        {{ item.factorySubOrderNumber }}
                      </span>
                      <el-icon
                        class="icon"
                        @click.stop="copy(item.factorySubOrderNumber || '')"
                      >
                        <DocumentCopy />
                      </el-icon>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label"
                        >第三方生产单号:</span
                      >
                      <span
                        class="goods-item-info-item-value"
                        :title="item.thirdSubOrderNumber"
                      >
                        {{ item.thirdSubOrderNumber }}
                      </span>
                      <el-icon
                        class="icon"
                        @click.stop="copy(item.thirdSubOrderNumber || '')"
                      >
                        <DocumentCopy />
                      </el-icon>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">工厂:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.factoryCode }}
                      </span>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">款号:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.supplierProductNo }}
                      </span>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">克重:</span>
                      <span
                        v-if="item.weight"
                        class="goods-item-info-item-value"
                      >
                        {{ item.weight }}g
                      </span>
                    </div>
                    <div v-if="item.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">
                        {{ item.payAmount }}($)
                      </span>
                    </div> -->

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

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

                      <!-- f -->
                    </div>
                    <div
                      v-if="
                        status === 'WAIT_SHIPMENT' &&
                        item.productMark !== 'custom_normal'
                      "
                      style="display: flex; justify-content: space-between"
                    >
                      <el-button
                        link
                        size="small"
                        type="primary"
                        style="height: 23px; padding: 0"
                        @click="downloadMaterialItem(item)"
                        >下载素材
                      </el-button>

                      <el-button
                        link
                        size="small"
                        type="warning"
                        style="height: 23px; margin: 0"
                        @click="showArrange(3, item)"
                        >排版
                      </el-button>
                    </div>
                    <div
                      v-if="
                        status === 'WAIT_SHIPMENT' &&
                        item.productMark !== 'custom_normal'
                      "
                      style="
                        display: flex;
                        flex-direction: column;
                        align-items: start;
                      "
                    >
                      <el-button
                        link
                        size="small"
                        type="success"
                        style="height: 23px"
                        @click="printProductionOrder(1, 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.shipmentType == 0 && row.replaceShipment == 0
                      ? '自提'
                      : ['自有物流', '工厂物流'][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
                  :class="{ 'red-big': row.source === 'factory-reissue' }"
                  class="order-detail-item-value"
                >
                  {{
                    row.source
                      ? {
                          'jomall-erp': 'erp推送',
                          'third-party': '第三方推送',
                          'factory-reissue': '补发订单',
                        }[
                          row.source as
                            | 'jomall-erp'
                            | 'third-party'
                            | 'factory-reissue'
                        ]
                      : ''
                  }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">总克重:</span>
                <span v-if="row.weight" class="order-detail-item-value">
                  {{ row.weight }}g
                </span>
              </div>
              <div
                v-if="row.status !== 'TO_BE_CONFIRMED'"
                class="order-detail-item"
              >
                <span class="order-detail-item-label">生产端:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.productionClient"
                >
                  {{ row.productionClient }}
                </span>
              </div>
              <div
                v-if="
                  row.productionClient === 'JOMALL' &&
                  row.status !== 'TO_BE_CONFIRMED'
                "
                class="order-detail-item"
              >
                <span class="order-detail-item-label">发货仓库:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.warehouseName"
                >
                  {{ row.warehouseName }}
                </span>
              </div>
              <div
                v-if="
                  row.productionClient === 'JOMALL' &&
                  row.status !== 'TO_BE_CONFIRMED'
                "
                class="order-detail-item"
              >
                <span class="order-detail-item-label">物流方式:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.logisticsWayName"
                >
                  {{ row.logisticsWayName }}
                </span>
              </div>
              <!-- <div class="order-detail-item">
                <span class="order-detail-item-label">收货人:</span>
                <span class="order-detail-item-value" :title="row.receiverName">
                  {{ row.receiverName }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">收货人电话:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.receiverPhone"
                >
                  {{ row.receiverPhone }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">收货人邮编:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.receiverPostCode"
                >
                  {{ row.receiverPostCode }}
                </span>
              </div> -->
              <!-- <div class="order-detail-item">
                <span class="order-detail-item-label">收货地址:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.lanshouAddress"
                >
                  {{ row.lanshouAddress }}
                </span>
              </div> -->
            </div>
          </template>
          <template #price="{ row }">
            <div class="order-price-box">
              <div class="order-price-item">
                <div class="order-price-item-label">商品总价</div>
                <div class="order-price-item-value">
                  {{ row.totalAmount }}
                </div>
              </div>

              <div
                v-if="
                  row.status !== 'TO_BE_CONFIRMED' &&
                  row.status !== 'EXCEPTION_ORDER'
                "
                class="order-price-item"
              >
                <div class="order-price-item-label">物流运费</div>
                <div class="order-price-item-value">
                  {{ row.payFreight }}
                </div>
              </div>
            </div>
          </template>
          <template #time="{ row }">
            <el-timeline>
              <el-timeline-item
                :color="row.createTime ? '#409EFF' : ''"
                :timestamp="row.createTime"
                >创建时间
              </el-timeline-item>
              <el-timeline-item
                :color="row.startStockingTime ? '#E6A23C' : ''"
                :timestamp="row.startStockingTime"
                >确认时间
              </el-timeline-item>
              <el-timeline-item
                :color="row.finishTime ? '#67C23A' : ''"
                :timestamp="row.finishTime"
                >发货时间
              </el-timeline-item>
              <el-timeline-item
                v-if="status === 'IN_TRANSIT'"
                :color="row.finishTime ? '#F56C6C' : ''"
              >
                {{
                  `延迟${(() => {
                    if (!row.finishTime) return ''
                    const finishDate = new Date(row.finishTime)
                    const today = new Date()
                    const diffTime = today.getTime() - finishDate.getTime()
                    const diffDays = Math.floor(
                      diffTime / (1000 * 60 * 60 * 24),
                    )
                    return diffDays
                  })()}
              天`
                }}
              </el-timeline-item>
            </el-timeline>
            <div v-if="status === 'IN_TRANSIT'" style="color: #f56c6c"></div>

            <!-- <div class="order-time-box">
              <div class="order-time-item">
                <span class="order-time-item-label">创建时间：</span>
                <span class="order-time-item-value">
                  {{ row.createTime }}
                </span>
              </div>
              <div class="order-time-item">
                <span class="order-time-item-label">确认时间：</span>
                <span class="order-time-item-value">
                  {{ row.startStockingTime }}
                </span>
              </div>

              <div class="order-time-item">
                <span class="order-time-item-label">完成时间：</span>
                <span class="order-time-item-value">
                  {{ row.finishTime }}
                </span>
              </div>
            </div> -->
          </template>
          <template #exceptionReason="{ row }">
            <div style="white-space: pre-line">{{ row.exceptionReason }}</div>
          </template>
          <template #innerLabel="{ row }">
            <div v-if="row.internalMemoList" class="inner-label-box">
              <div
                v-for="(item, index) in row.internalMemoList"
                :key="index"
                class="inner-label-item"
              >
                <span class="inner-label-item-value">
                  {{
                    `${item.operatorTime} ${item.operatorEmployeeName}:  ${item.content}`
                  }}
                </span>
              </div>
            </div>
          </template>
          <template #downloadStatus="{ row }">
            <div style="white-space: pre-line">
              <el-tag v-if="row.downloadStatus" type="success">已下载</el-tag>
              <el-tag v-else type="danger">未下载</el-tag>
            </div>
          </template>
          <template #createTime="{ row }">
            <div style="white-space: pre-line">
              {{ row.createTime.replace('T', ' ') }}
            </div>
          </template>
          <template #finishTime="{ row }">
            <div style="white-space: pre-line">
              {{ row.finishTime?.replace('T', ' ') }}
            </div>
          </template>
          <template #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 style="white-space: pre-line" v-html="row.failReason"></span>
          </template>
          <template #operate="{ row }">
            <div
              v-if="status === 'BATCH_DOWNLOAD'"
              class="operate-box-vertical"
            >
              <el-link
                :disabled="row.isUpload"
                underline="never"
                type="success"
                @click="uploadFile(row)"
                >上传PRN</el-link
              >
              <el-icon
                v-if="row.isUpload"
                style="right: 0; top: 5px"
                class="is-loading"
              >
                <Loading />
              </el-icon>
              <el-link
                :disabled="!row.prnUrl"
                style="margin-left: 8px"
                underline="never"
                :title="fileName(row)"
                type="success"
                @click="downloadRowProFile(row)"
                >下载PRN
              </el-link>
              <el-icon
                v-if="row.prnDownloadStatus"
                class="download-icon"
                style="position: relative; right: 7px"
              >
                <CircleCheckFilled />
              </el-icon>

              <!-- <span class="operate-item">
                <ElButton
                  :disabled="!row.tiffUrl"
                  link
                  type="primary"
                  @click="handleDownload(row, 'tiff')"
                >
                  TIF下载
                </ElButton>
              </span> -->
              <span class="operate-item">
                <ElButton
                  link
                  title="打印拣货单"
                  type="primary"
                  @click="printPickingOrderItem(row, 1)"
                >
                  拣货单
                </ElButton>
                <el-icon v-if="row.printPickOrder" class="check-icon"
                  ><CircleCheckFilled
                /></el-icon>
              </span>
              <span class="operate-item">
                <ElButton
                  link
                  title="打印生产单"
                  type="primary"
                  @click="printPickingOrderItem(row, 2)"
                >
                  生产单
                </ElButton>
                <el-icon v-if="row.printProductOrder" class="check-icon"
                  ><CircleCheckFilled
                /></el-icon>
              </span>
              <span class="operate-item">
                <ElButton
                  :disabled="!row.url && !row.tiffUrl"
                  link
                  type="primary"
                  @click="handleDownload(row)"
                >
                  下载素材
                </ElButton>
                <el-icon v-if="row.downloadStatus" class="download-icon"
                  ><CircleCheckFilled
                /></el-icon>
              </span>
              <span class="operate-item">
                <ElButton
                  :disabled="row.productNum > 50"
                  link
                  title="重新排版"
                  type="warning"
                  :loading="reComposingLoadingMap[row.id]"
                  @click="showArrange(1, row)"
                >
                  重排
                </ElButton>
              </span>
            </div>
            <div v-else class="operate-box">
              <span v-if="status !== 'BATCH_DOWNLOAD'" class="operate-item">
                <ElButton
                  link
                  type="warning"
                  @click="handleUpdateAddress(row, 2)"
                >
                  地址信息
                </ElButton>
              </span>
              <span v-if="status !== 'BATCH_DOWNLOAD'" class="operate-item">
                <ElButton
                  link
                  type="primary"
                  @click="operationLog(row.id, null, row)"
                >
                  操作日志
                </ElButton>
              </span>

              <span
                v-if="
                  ['WAIT_TRACK'].includes(status) &&
                  row.replaceShipment !== 0 &&
                  row.shipmentType !== 0
                "
                class="operate-item"
              >
                <ElButton link type="warning" @click="updateTrackingNumber(row)"
                  >修改跟踪号</ElButton
                >
              </span>
              <!-- <span
                v-if="!row.expressSheet && row.status === 'TO_BE_CONFIRMED'"
                class="operate-item"
              >
                <ElButton link type="primary" @click="confirm(row)">
                  确认
                </ElButton>
              </span> -->
              <span
                v-if="
                  row.shipmentType === 0 &&
                  row.replaceShipment !== 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, 1)"
                >
                  修改地址
                </ElButton>
              </span>
              <span
                v-if="
                  (status === 'WAIT_SHIPMENT' ||
                    status === 'CREATE_LOGISTICS') &&
                  row.shipmentType === 1
                "
                class="operate-item"
              >
                <ElButton link type="primary" @click="handleStockOut(row)">
                  更换物流
                </ElButton>
              </span>
              <span
                v-if="
                  row.shipmentType === 0 &&
                  row.replaceShipment !== 0 &&
                  ['CREATE_LOGISTICS', 'WAIT_SHIPMENT'].includes(status)
                "
                class="operate-item"
              >
                <ElButton
                  link
                  type="primary"
                  @click="handleRefreshAddress(row)"
                >
                  刷新地址
                </ElButton>
              </span>
              <span
                v-if="
                  row.shipmentType !== 0 &&
                  row.replaceShipment !== 0 &&
                  (status === 'IN_TRANSIT' || status === 'COMPLETE') &&
                  isPermissionBtn('TRACK')
                "
                class="operate-item"
              >
                <ElButton link type="primary" @click="logTrajectory(row)"
                  >物流轨迹</ElButton
                >
              </span>
            </div>
          </template>
          <template #trackRegisterFailContent="{ row }">
            <div style="white-space: pre-line">
              {{ JSON.parse(row.trackRegisterFailContent)?.error || '' }}
            </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"
            ref="cardRefs"
            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
                    v-if="cardItem.customTagList?.length"
                    ref="tagRefs"
                    class="flex"
                    style="gap: 5px; overflow: hidden"
                  >
                    <el-tag
                      v-for="(item, index) in cardItem.customTagList.slice(
                        0,
                        3,
                      )"
                      :key="index"
                      size="small"
                      type="primary"
                      ><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
                      v-if="cardItem.customTagList?.slice(3)?.length"
                      size="small"
                      type="primary"
                      >+{{ cardItem.customTagList.slice(3).length }}
                    </el-tag>
                  </div>
                </el-tooltip>
              </template>
              <template
                v-if="['ZPZY', 'CXZY', 'THZY'].includes(cardItem.craftCode as string)"
                #top_right
              >
                <img
                  :src="`/images/pic/${cardItem.craftCode}.png`"
                  width="100px;"
                  height="100px"
                  alt=""
                />
              </template>
              <template #bottom_left>
                <span
                  v-if="cardItem?.factorySubOrderNumber"
                  :title="`生产单号:${cardItem?.factorySubOrderNumber || ''}`"
                  class="factory-sub-order-number"
                  @click.stop="
                    copy(String(cardItem?.factorySubOrderNumber || ''))
                  "
                >
                  {{ cardItem?.factorySubOrderNumber }}
                </span>
              </template>
              <template #operations>
                <div
                  v-if="cardItem?.customizedQuantity"
                  class="customizedQuantity"
                  :title="`类型:${getQuantityText(
                    cardItem?.customizedQuantity,
                  )}面`"
                >
                  {{ getQuantityText(cardItem?.customizedQuantity) }}
                </div>
                <Icon
                  name="caozuorizhi"
                  style="width: 28px; height: 28px"
                  @click="(e: MouseEvent) => operationLog(cardItem.podJomallOrderUsId, e)"
                >
                  <template #title>
                    <title>操作日志</title>
                  </template>
                </Icon>
                <Icon name="chakanxiangqing" @click="openDetail(cardItem.id)">
                  <template #title>
                    <title>查看详情</title>
                  </template>
                </Icon>
              </template>
              <template #images>
                <div class="flex-between">
                  <div v-if="cardItem.imageAry" class="images-position">
                    <div
                      v-for="(item, index) in filteredImages(cardItem.imageAry)"
                      :key="index"
                      :title="item.title"
                      class="item-image"
                      @mousemove="handleChangeImages(item, cardItem)"
                    >
                      <img
                        :src="item?.url"
                        height="28"
                        @click="handlePictureCardPreview(item?.url)"
                      />
                    </div>
                  </div>
                  <div v-if="cardItem.platform">
                    <img
                      :src="`/images/icon/${getPlatformImg(cardItem.platform)}`"
                      style="height: 30px"
                    />
                  </div>
                </div>
              </template>
              <template #info>
                <div class="grid-container">
                  <div
                    class="grid-item"
                    :title="`商品名称:${cardItem?.productName || ''}`"
                  >
                    <span class="grid-item-value"
                      >{{ cardItem?.productName }}
                    </span>
                  </div>
                  <div
                    :style="{
                      visibility:
                        status === 'IN_PRODUCTION' ||
                        status === 'PICKING' ||
                        status === 'TO_BE_ARRANGE'
                          ? 'visible'
                          : 'hidden',
                    }"
                    class="grid-item"
                    :title="status === 'PICKING' ? '数量' : '未生产数量'"
                  >
                    <span class="grid-item-label">数量：</span>
                    <span class="grid-item-value">
                      {{
                        status === 'PICKING'
                          ? cardItem.num || 0
                          : cardItem?.notPassNum || 0
                      }}
                    </span>
                  </div>
                  <div
                    class="grid-item"
                    @click="copy(cardItem?.variantSku || '')"
                  >
                    <div
                      :title="`variant SKU: ${cardItem?.variantSku || ''}`"
                      class="grid-item-value"
                    >
                      <div class="orderNumber">{{ cardItem?.variantSku }}</div>
                    </div>
                  </div>
                  <div v-if="status !== 'TO_BE_ARRANGE'" class="grid-item">
                    <span class="grid-item-label">补胚数量：</span>
                    <span class="grid-item-value">
                      {{ cardItem?.replenishmentNum || 0 }}
                    </span>
                  </div>
                  <div
                    class="grid-item"
                    @click="copy(cardItem?.thirdSkuCode || '')"
                  >
                    <div
                      :title="`库存SKU:${cardItem?.thirdSkuCode || ''}`"
                      class="grid-item-value"
                    >
                      <div class="orderNumber">
                        {{ cardItem?.thirdSkuCode }}
                      </div>
                    </div>
                  </div>
                  <div
                    class="grid-item"
                    :title="`工艺:${cardItem?.craftName || ''}`"
                  >
                    <span class="grid-item-label">工艺：</span>
                    <span class="grid-item-value">
                      {{ cardItem?.craftName }}
                    </span>
                  </div>
                  <div
                    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"
                    :title="`店铺单号:${cardItem?.shopNumber || ''}`"
                    @click="copy(cardItem?.shopNumber || '')"
                  >
                    <div class="grid-item-value">
                      <div class="orderNumber">
                        {{ cardItem?.shopNumber }}
                      </div>
                    </div>
                  </div>
                  <div class="grid-item">
                    <span class="grid-item-label">款号：</span>
                    <span
                      :title="`款号: ${cardItem?.supplierProductNo}`"
                      class="grid-item-value"
                    >
                      {{ cardItem?.supplierProductNo }}
                    </span>
                  </div>
                  <div
                    class="grid-item"
                    @click="copy(cardItem?.factoryOrderNumber || '')"
                  >
                    <div
                      :title="`订单号:${cardItem?.factoryOrderNumber}`"
                      class="grid-item-value orderNumber"
                    >
                      {{ cardItem?.factoryOrderNumber }}
                    </div>
                  </div>
                  <div class="grid-item">
                    <span class="grid-item-label">货号：</span>
                    <span
                      :title="`货号: ${cardItem?.thirdStockSku}`"
                      class="grid-item-value"
                    >
                      {{ cardItem?.thirdStockSku }}
                    </span>
                  </div>

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

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

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

  <el-dialog
    v-model="isChangeWay"
    :close-on-click-modal="false"
    :title="wayDialogTitle"
  >
    <el-table
      ref="changeWayRef"
      v-loading="isChangeWayLoading"
      height="400px"
      class="production-client-table"
      :data="logisticsWayData"
      border
      highlight-current-row
      @row-click="(v:LogisticsData) =>rowClick(v, wayDialogTitle)"
    >
      <el-table-column
        label="序号"
        width="60"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column
        label="物流名称"
        align="center"
        prop="logisticsWayName"
      ></el-table-column>
      <el-table-column
        label="发货仓库"
        align="center"
        prop="warehouseName"
      ></el-table-column>
      <el-table-column
        label="物流编码"
        align="center"
        prop="logisticsWayCode"
      ></el-table-column>
      <el-table-column
        label="所在分区"
        align="center"
        prop="partition"
      ></el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="{ row }">
          <b v-if="row.status" style="color: green">成功</b>
          <b v-else-if="!row.status" style="color: red">失败</b>
        </template>
      </el-table-column>
      <el-table-column label="预计运费（$）" align="center" prop="payFreight">
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button :disabled="isChangeWayLoading" @click="cancelWayDialog">
        取消
      </el-button>
      <el-button
        :loading="isChangeWayLoading"
        type="primary"
        @click="changeWaySubmit(wayDialogTitle)"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
  <UpdateAddress
    v-if="updateAddVisible"
    v-model:form="currentRow"
    v-model:visible="updateAddVisible"
    :country-list="countryList"
    :type="updateAddressType"
    @success="search"
  ></UpdateAddress>
  <ElDialog
    v-model="exceptionDialogVisible"
    title="转为异常单"
    width="500px"
    :close-on-click-modal="false"
    @open="handleExceptionDialogOpen"
  >
    <ElForm ref="exceptionFormRef" :model="exceptionForm" label-width="100px">
      <ElFormItem
        label="异常类型"
        prop="exceptionType"
        :rules="
          status === 'EXCEPTION_ORDER'
            ? { required: true, message: '请选择异常类型' }
            : {}
        "
      >
        <ElSelect
          v-model="exceptionForm.exceptionType"
          style="width: 100%"
          placeholder="请选择异常类型"
          clearable
        >
          <ElOption
            v-for="type in exceptionTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem
        label="异常原因"
        prop="exceptionReason"
        :rules="
          status !== 'EXCEPTION_ORDER'
            ? { required: true, message: '请输入异常原因' }
            : {}
        "
      >
        <ElInput
          v-model="exceptionForm.exceptionReason"
          style="width: 100%"
          type="textarea"
          :rows="3"
          placeholder="请输入异常原因"
        />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="exceptionDialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleExceptionConfirm">
          确定
        </ElButton>
      </span>
    </template>
  </ElDialog>
  <el-dialog
    v-model="logisticsVisible"
    :close-on-click-modal="false"
    width="700px"
    title="更新物流信息"
  >
    <el-form
      v-if="logisticsVisible"
      ref="logisticsFormRef"
      label-width="100px"
      label-position="left"
      :model="logisticsForm"
    >
      <el-form-item prop="processNumber" label="物流处理号">
        <el-input
          v-model="logisticsForm.processNumber"
          placeholder="请输入物流处理号"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="trackingNumber" label="物流跟踪号">
        <el-input
          v-model="logisticsForm.trackingNumber"
          placeholder="请输入物流跟踪号"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="logisticsForm.trackingNumber"
        prop="expressSheetUrl"
        label="物流面单"
      >
        <el-upload accept=".pdf" action="" :before-upload="expressSheetUpload">
          <el-button type="primary">点击上传</el-button>
        </el-upload>
        <div v-if="logisticsForm.expressSheet" class="file">
          <span>{{ logisticsForm.expressSheet.name }}</span>
          <el-icon
            class="expressSheetClose"
            @click="logisticsForm.expressSheet = null"
          >
            <Close></Close>
          </el-icon>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="logisticsVisible = false">取消</el-button>
      <el-button type="primary" @click="logisticsSubmit"> 确定</el-button>
    </template>
  </el-dialog>
  <!-- 导出 -->
  <ElDialog
    v-model="exportVisible"
    title="导出选项"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form :model="exportForm" label-width="80px">
      <el-form-item label="" prop="resource">
        <el-radio-group v-model="exportForm.resource">
          <el-radio :label="0">导出本页</el-radio>
          <el-radio :label="1">导出选中</el-radio>
          <el-radio :label="2">全部</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportVisible = false">取消</el-button>
        <el-button
          :loading="exportLoading"
          type="primary"
          @click="submitExportForm"
          >确认</el-button
        >
      </span>
    </template>
  </ElDialog>
  <el-dialog v-model="dialogVisible" width="35%">
    <img :src="dialogImageUrl" alt="商品预览图片" />
  </el-dialog>
  <el-dialog v-model="timeLineVisible" title="物流轨迹" width="1000px">
    <el-timeline>
      <el-timeline-item
        v-for="(item, index) in timeLine"
        :key="index"
        :timestamp="item.time_utc"
        placement="top"
        :type="index == 0 ? 'primary' : ''"
      >
        <el-card>
          {{ item.description }}
        </el-card>
      </el-timeline-item>
    </el-timeline>
  </el-dialog>
  <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>

  <!-- 补胚数量输入对话框 -->
  <ElDialog
    v-model="replenishmentDialogVisible"
    title="申请补胚"
    width="400px"
    @close="resetReplenishmentForm"
  >
    <ElForm
      ref="replenishmentFormRef"
      :model="replenishmentForm"
      :rules="replenishmentRules"
      label-width="80px"
    >
      <ElFormItem label="补胚数量" prop="replenishmentNum">
        <ElInputNumber
          v-model="replenishmentForm.replenishmentNum"
          placeholder="请输入补胚数量"
          style="width: 100%"
          :step="1"
          :precision="0"
          :min="1"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="补胚原因" prop="replenishmentReason">
        <ElInput
          v-model="replenishmentForm.replenishmentReason"
          placeholder="请输入补胚原因"
          style="width: 100%"
          clearable
        />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="replenishmentDialogVisible = false">取消</ElButton>
      <ElButton type="primary" @click="confirmReplenishment">确定</ElButton>
    </template>
  </ElDialog>
  <print-warehouse-sku-tag ref="printWarehouseSkuDialogRef" />
  <ReissueOrderComponent
    ref="reissueOrderRef"
    :selection="selection"
    @success="handleSuccess"
  ></ReissueOrderComponent>

  <uploadBox
    v-if="status === 'BATCH_DOWNLOAD'"
    :uploadList="uploadList"
  ></uploadBox>
</template>
<script setup lang="tsx">
import LogisticsWaySelect from '../../logistics/components/LogisticsWaySelect.tsx'
import { getUserMarkList } from '@/api/common'
// import { AnyObject } from '@/types/api/warehouse'
import uploadBox from '@/components/uploadBox.vue'
import { convertToChinaTime } from '@/utils/index'
import {
  InfoFilled,
  ArrowDown,
  CaretBottom,
  CaretTop,
  // Edit,
  Close,
  WarningFilled,
} from '@element-plus/icons-vue'
import {
  getCardOrderList,
  uploadPRNFile,
  getOrderList,
  getOrderTabData,
  confirmOrderApi,
  changeExceptionOrderApi,
  cancelOrderApi,
  getOperationLogApi,
  downloadMaterialApi,
  updateExceptionOrderApi,
  printProductionOrderApi,
  getOrderDetailById,
  updateRemarkApi,
  getProductionClientApi,
  printPickingOrderApi,
  printPrintOrderApi,
  stockOutCheckApi,
  toBePickingApi,
  loadWarehouseListApi,
  getLogisticsCalculation,
  refreshMaterialApi,
  getTrackingNumberApi,
  getfaceSimplexFileApi,
  cancelLogisticsOrderApi,
  composingDesignImages,
  changeLogisticsApi,
  createLogisticsOrderApi,
  // updateLogisticsToPickingApi,
  updateLogisticsToArrangeApi,
  createLogisticsOrdersApi,
  syncReceiverAddress,
  refreshAddressApi,
  confirmProductApi,
  confirmProductToRiinApi,
  updateSelfLogistics,
  uploadExpressSheet,
  // handleExceptionOrderApi,
  applyForReplenishmentApi,
  replenishmentSuccessApi,
  toOutOfStockApi,
  arrangeFinishApi,
  getListCraftApi,
  batchDownloadApi,
  batchDownloadDownloadApi,
  batchDownloadDeleteApi,
  batchDownloadRecomposingApi,
  updateToWaitShipmentApi,
  exportPodUSInfo,
  getgetInterceptStateGroupList,
  interceptUpdateApi,
  rejectToApi,
  statusPushApi,
  completeDeliveryApi,
  get17TrackInfoApi,
  getAccountCodeByFactoryIdApi,
  printPickPdfByBatchNumberApi,
  printProductionPdfByBatchNumberApi,
  changeToFinished,
  updateTrackingNumberAndRegister,
  countTrackRegisterApi,
  getCustomTagListApi,
  getLogisticsWayApi,
  printNormalPickPdfApi,
  updatePRNDownloadStatus,
  getEmployeeListApi,
} from '@/api/podUsOrder'
import { BaseRespData } from '@/types/api'

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

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

import TableView from '@/components/TableView.vue'
import {
  LogListData,
  PodUsOrderListData,
  ProductList,
  ProductionClient,
  SearchForm,
  Tab,
  WarehouseListData,
  cardImages,
  AddressInfo,
  LogisticsData,
  LogisticsFormData,
  CraftListData,
  ExportParams,
  InterceptStateGroupData,
  IAllList,
} from '@/types/api/podUsOrder'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from '@/utils/hooks/useValue'
import { useEnterKeyTrigger } from '@/utils/hooks/useEnterKeyTrigger.ts'
import { showConfirm } from '@/utils/ui'
import {
  DocumentCopy,
  EditPen,
  Loading,
  CircleCheckFilled,
} from '@element-plus/icons-vue'
import { Column, ElFormItem, ElMessage } from 'element-plus'
import { computed, onMounted, ref, nextTick, reactive} from 'vue'
import FastProduction from './FastProduction.vue'
import { filePath } from '@/api/axios'
import PodMakeOrder from './PodMakeOrder.vue'
import InspPackagOrder from './InspPackagOrder.vue'
import { OrderData } from '@/types/api/podMakeOrder'
import useLodop, { LODOPObject } from '@/utils/hooks/useLodop'
import dayjs from 'dayjs'
import RightClickMenu from '@/components/RightClickMenu.vue'
import ResultInfo from './components/ResultInfo.vue'
import { isArray, isString } from '@/utils/validate'
import platformJson from '../../../json/platform.json'
import { getToken } from '@/api/axios'
import usePermissionBtnStore from '@/store/permission'
import ReissueOrderComponent from './components/ReissueOrder.vue'

const permissionBtns = usePermissionBtnStore()

import {
  useRouter,
  type NavigationGuardNext,
  type RouteLocationNormalized,
} from 'vue-router'
import PrintWarehouseSkuTag from '@/views/order/components/printWarehouseSkuTag.vue'

declare global {
  interface Window {
    ActiveXObject: {
      new (type: string): XMLHttpRequest
    }
    VBS_BinaryToArray: {
      (data: unknown): { toArray(): number[] }
    }
  }

  interface XMLHttpRequest {
    responseBody?: unknown
  }
}

const sourceList = [
  {
    name: 'erp推送',
    id: 'jomall-erp',
  },
  {
    name: '第三方推送',
    id: 'third-party',
  },
  {
    name: '补发订单',
    id: 'factory-reissue',
  },
]
const sizes = ['FS', 'XS', 'S', 'M', 'L', 'XL', 'XXL', '3XL', '4XL', '5XL']
const tabsNav = ref<Tab[]>()
const reissueOrderRef = ref()
const printWarehouseSkuDialogRef = ref()
const isAuto = ref(true)
const countryList = ref([])
const logisticsWayList = ref<{ name: string; id: number }[]>([])
const employeeList = ref<{ account: string; id: number }[]>([])
const currentRow = ref<AddressInfo>({
  receiverName: '',
  receiverPhone: '',
  receiverCountry: '',
  receiverProvince: '',
  receiverCity: '',
  receiverDistrict: '',
  receiverAddress1: '',
  receiverAddress2: '',
  receiverPostCode: '',
})
const currentItem = ref<PodUsOrderListData | null>(null)
const exportLoading = ref(false)
const exportVisible = ref(false)
const exportForm = ref({
  resource: '',
})

// 修改物流跟踪号
const updateTrackingNumber = async (row: PodUsOrderListData) => {
  const { value } = await ElMessageBox.prompt('请输入物流跟踪号', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '请输入物流跟踪号',
    inputPlaceholder: '物流跟踪号',
    inputValue: row.trackingNumber,
  })
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await updateTrackingNumberAndRegister(row.id, value)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    await loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

const showPrintSku = async () => {
  if (!selection.value.length) {
    return ElMessage.warning('请选择数据')
  }
  await printWarehouseSkuDialogRef.value?.open(
    2,
    selection.value.map((item) => item.id).join(','),
  )
}

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

// 补胚对话框相关数据
const replenishmentDialogVisible = ref(false)
const replenishmentFormRef = ref()
const currentReplenishmentRow = ref<ProductList | null>(null)
const replenishmentForm = ref({
  replenishmentNum: '1',
  replenishmentReason: '',
})
const replenishmentRules = {
  replenishmentNum: [
    { required: true, message: '请输入补胚数量', trigger: 'blur' },
  ],
  replenishmentReason: [
    { required: true, message: '请输入补胚原因', trigger: 'blur' },
  ],
}

// 尺码类型表
const sizeList = ref<{ name: string; value: number }[]>([
  { name: '正常码', value: 1 },
  { name: '大码', value: 2 },
])

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

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

const getWeekRange = (weeks = 0, type: 'past' | 'future' = 'past') => {
  const now = dayjs()
  const start =
    type === 'past' ? now.subtract(weeks, 'week') : now.add(weeks, 'week')
  return [start.startOf('week').toDate(), start.endOf('week').toDate()]
}
const handleRefreshAddress = async (row: PodUsOrderListData) => {
  try {
    await showConfirm('确定刷新地址吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  await refreshAddressApi([row.id])
  await ElMessageBox.alert(
    '请修改/刷新地址后取消物流或者更换物流在重新创建物流订单、获取跟踪号、获取打印面单',
    '提示',
    {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      showCancelButton: true,
    },
  )
}
const updateAddressType = ref<1 | 2>(1)
const handleUpdateAddress = async (row: PodUsOrderListData, type: 1 | 2) => {
  const { data } = await getAllCountryApi()
  countryList.value = data
  currentRow.value = JSON.parse(JSON.stringify(row))
  updateAddVisible.value = true
  updateAddressType.value = type
}
// 批量下载 下载
const handleDownload = async (row: PodUsOrderListData) => {
  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 shipmentList = ref(['自有物流', '工厂物流'])

// 批量下载 重新排版
const handleReComposingDesign = async () => {
  const row = { ...(typesettingRow.value as PodUsOrderListData) }

  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
  }
}
interface ProcessTypeData {
  label: string
  value:string
}
const processType = ref<ProcessTypeData[]>([
  {
    label: '烫画',
    value: 'TH',
  },
  {
    label: '直喷',
    value: 'ZP',
  },
  {
    label: '刺绣',
    value: 'CX',
  },
  {
    label: '雕刻',
    value: 'DK',
  },
  {
    label: '白胚',
    value: 'BP',
  },
  {
    label: '其他',
    value: 'QT',
  },
])
const tableColumns = computed(() => {
  let arr = []
  if (status.value === 'BATCH_DOWNLOAD') {
    arr = [
      {
        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: '工艺类型',
        width: 150,
        prop: 'craftType',
        align: 'center',
        render: (item:ProductList) => {
          if (!item.craftType) {
            return (
              <div>
                <span>-</span>
              </div>
            )
          }
          
          // 分割字符串并查找对应的 label
          const labels = item.craftType
            .split(',')
            .map(type => type.trim())
            .map(type => processType.value.find(e => e.value === type)?.label || type)
            .filter(Boolean)
          
          return (
            <div>
              <span>{labels.join(',')}</span>
            </div>
          )
        }
      },

      {
        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: '失败原因',
        minWidth: 200,
        prop: 'failReason',
        slot: 'failReason',
        align: 'left',
      },
      {
        label: '排版参数',
        width: 140,
        prop: 'composingParam',
        slot: 'composingParam',
        align: 'center',
      },
      {
        label: '操作',
        slot: 'operate',
        width: 400,
        align: 'center',
        fixed: 'right',
        prop: 'operate',
      },
    ]
    return arr
  }
  arr = [
    {
      label: '序号',
      prop: 'serialNumber',
      slot: 'serialNumber',
      width: 60,
      align: 'center',
    },
    {
      label: '商品',
      prop: 'goods',
      slot: 'goods',
      minWidth: 800,
    },
    {
      label: '订单详情',
      prop: 'orderDetail',
      slot: 'orderDetail',
      width: 300,
    },
    {
      label: '订单金额($)',
      slot: 'price',
      width: 110,
      prop: 'price',
      align: 'left',
    },
    {
      label: '时间',
      slot: 'time',
      width: 170,
      prop: 'time',
      align: 'left',
    },
    // {
    //   label: '内部便签',
    //   slot: 'innerLabel',
    //   width: 300,
    //   prop: 'innerLabel',
    // },
    {
      label: '异常原因',
      width: 250,
      prop: 'exceptionReason',
      slot: 'exceptionReason',
      align: 'left',
    },
    {
      label: '物流跟踪状态',
      width: 220,
      prop: 'track17Status',
      align: 'left',
    },
    {
      label: '注册失败信息',
      width: 220,
      prop: 'trackRegisterFailContent',
      slot: 'trackRegisterFailContent',
      align: 'left',
    },
    {
      label: '操作',
      slot: 'operate',
      width: 120,
      align: 'center',
      fixed: 'right',
      prop: 'operate',
    },
  ]
  // 根据状态动态调整列显示
  if (!['WAIT_TRACK'].includes(status.value)) {
    const trackRegisterIndex = arr.findIndex(
      (item) => item.prop === 'trackRegisterFailContent',
    )
    if (trackRegisterIndex >= 0) {
      arr.splice(trackRegisterIndex, 1)
    }
  } else {
    if (waitTrackStatus.value !== 1) {
      const trackRegisterIndex = arr.findIndex(
        (item) => item.prop === 'trackRegisterFailContent',
      )
      if (trackRegisterIndex >= 0) {
        arr.splice(trackRegisterIndex, 1)
      }
    }
  }

  if (!['WAIT_TRACK', 'IN_TRANSIT'].includes(status.value)) {
    const index = arr.findIndex((item) => item.prop === 'track17Status')
    if (index >= 0) {
      arr.splice(index, 1)
    }
  }
  return arr
})
const rightMenuRef = ref()
const rightClick = (e: MouseEvent) => {
  rightMenuRef.value.setPosition({
    x: e.clientX,
    y: e.clientY,
  })
}

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

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

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

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

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

// 获取注册列表tab信息
const getRegistData = async () => {
  const res = await countTrackRegisterApi()
  trackRegisterCount.value = res.data
}

// 获取Tab信息
const loadTabData = async () => {
  try {
    const res = await getOrderTabData()
    tabsNav.value = res.data
    if (status.value === 'WAIT_TRACK') {
      await getRegistData()
    }

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

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

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

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

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

const {
  loading,
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  initPageSize: initPageSize.value,
  query: (page, pageSize) => {
    // 批量查询生产单号
    const factorySubOrderNumber = (() => {
      const originalValue = searchForm.value?.factorySubOrderNumber || ''
      if (!originalValue) return ''

      // 用中英文逗号或中英文分号分割
      const values = originalValue.split(/[,，;；]/).filter((v) => v.trim())

      // 处理每个值
      const processedValues = values.map((value) => {
        const trimmedValue = value.trim()
        const underscoreCount = (trimmedValue.match(/_/g) || []).length

        if (underscoreCount >= 3) {
          // 如果有3个或更多下划线，取第三个下划线后的值
          const parts = trimmedValue.split('_')

          return parts[3]
        } else {
          // 如果没有3个下划线，取原值
          return trimmedValue
        }
      })

      // 用英文逗号连接
      return processedValues.join(',')
    })()

    //基本params
    const baseparams = {
      ...searchForm.value,
      factorySubOrderNumber,
      startTime: timeRange.value?.[0] || null,
      endTime: timeRange.value?.[1] || null,
      // craftCode: searchForm.value?.craftCodeArr?.join(',') || '',
      tagsId: searchForm.value?.tagsIdArr?.join(',') || '',
    }
    // baseparams.craftCodeArr && delete baseparams.craftCodeArr
    baseparams.tagsIdArr && delete baseparams.tagsIdArr
    // 批量下载
    if (status.value === 'BATCH_DOWNLOAD') {
      const params = {
        ...baseparams
      }
      return batchDownloadApi(params,
        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'
    ) {
      const params = {
        ...baseparams,
        status: status.value === 'INTERCEPTED' ? '' : status.value,
        exceptionHandling:
          status.value === 'EXCEPTION_ORDER'
            ? exceptionStatus.value || undefined
            : undefined,
        interceptStatus:
          status.value === 'INTERCEPTED' ? interceptStatus.value : '',
        trackRegisterSelect:
          status.value === 'WAIT_TRACK' ? waitTrackStatus.value : '',
      }

      return getOrderList(params, page, pageSize).then(
        (res) => res.data,
      ) as never
    } else {
      const params = {
        ...baseparams,
        status: status.value,
        interceptStatus: '',
      }

      return getCardOrderList(params, page, pageSize).then(
        (res) => res.data,
      ) as never
    }
  },
})

/**
 * @description: 页面添加回车监听
 */
const searchFormRef = ref()
const searchFormPopoverRef = ref()
const searchBtnRef = ref()

useEnterKeyTrigger({
  formRef: searchFormRef,
  btnRef: searchBtnRef,

  callback: (event: KeyboardEvent) => {
    console.log('回车键被按下', event)
    refresh()
  },
})
useEnterKeyTrigger({
  formRef: searchFormPopoverRef,
  btnRef: searchBtnRef,

  callback: (event: KeyboardEvent) => {
    console.log('回车键被按下', event)
    refresh()
  },
})

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

    newData.forEach((order) => {
      order.productList?.forEach((product) => {
        if (!product.previewImgs && product.imageAry) {
          try {
            if (
              product.productMark === 'custom_normal' ||
              product.productMark === 'normal'
            ) {
              product.previewImgs = []
            } else {
              product.previewImgs =
                JSON.parse(product.imageAry)?.filter(
                  (el: { title: string }) => el.title,
                ) || []
            }
          } catch (error) {
            console.error('JSON解析失败:', error)
            product.previewImgs = []
          }
        }
      })
    })
  },
  { deep: true, immediate: true }, // 添加immediate确保初始化时执行
)
const fileName = (row: PodUsOrderListData) => {
  if (!row.prnUrl) return ''
  return row.prnUrl.split('/')[row.prnUrl.split('/').length - 1]
}
const search = () => {
  selection.value = []
  cardSelection.value = []
  refresh()
}
const currentChange = (row: LogisticsData) => {
  if (row) {
    confirmSelectionData.value = [row]
  }
}
const handleProductionClientChange = async (v: string) => {
  if (v !== 'RIIN') {
    if (confirmRowData.value) {
      const { data } = await getLogisticsCalculation(confirmRowData.value?.id)
      confirmData.value = data
    }
  }
}
const downloadFacebook = async (row: string) => {
  window.open(filePath + row, '_blank')
}

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

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

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

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

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

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

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

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

const downloadRowProFile = async (row: PodUsOrderListData) => {
  const url = `https://factory.jomalls.com/upload/factory` + row.prnUrl
  window.open(url, '_blank')
  await updatePRNDownloadStatus(row.id)
  search()
}
const uploadList = ref<PodUsOrderListData[]>([])
const uploadFile = (row: PodUsOrderListData) => {
  const input = document.createElement('input')
  input.style.display = 'none'
  input.type = 'file'
  input.multiple = false
  input?.click()

  input.onchange = async function () {
    try {
      if (input.files && input.files.length) {
        if (!input.files[0].name.startsWith(row.batchArrangeNumber || '')) {
          await ElMessageBox.confirm(
            `文件名不是以批次号开头是否继续上传?`,
            '提示',
            {
              confirmButtonText: '确定',
              type: 'warning',
            },
          )
        }
        row.isUpload = true
        uploadList.value.push(row)

        const fm = new FormData()
        fm.append('file', (input.files as never)?.[0])
        row.fileName = input.files?.[0]?.name
        // console.log(4219, input.files?.[0])

        const res = await uploadPRNFile(row.id, fm as never)
        row.prnUrl = res.message
      }
    } finally {
      row.isUpload = false
    }
  }
  input.oncancel = () => {
    row.isUpload = false
  }
  if (input.parentNode) {
    input.parentNode.removeChild(input)
  }
}

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 PodUsOrderListData) }
  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
      ? res.message?.startsWith('/temp')
        ? `https://factory.jomalls.com/upload/factory` + res.message
        : `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 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 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 downloadTifItem = async () => {
//   const row = { ...(typesettingRow.value as PodUsOrderListData) }
//   const loading = ElLoading.service({
//     fullscreen: true,
//     text: '操作中...',
//     background: 'rgba(0, 0, 0, 0.3)',
//   })
//   const { templateWidth, typeArr } = typesettingForm.value

//   const type = (typeArr?.join(',') as string) || ''

//   typesettingVisible.value = false
//   try {
//     if ((typeArr as string[]).length > 1) {
//       typeArr?.forEach(async (el) => {
//         const res = await composingDesignImages([row.id], el, templateWidth)
//         const url =
//           type === 'tiff'
//             ? `https://ps.jomalls.com/tiff/` + res.message
//             : filePath + res.message
//         if (el === 'tiff') {
//           window.open(url, '_blank')
//         } else {
//           fetch(url)
//             .then((response) => {
//               // 确保响应是 OK
//               if (!response.ok) {
//                 throw new Error('网络响应错误')
//               }
//               // 返回图片的二进制数据（Blob）
//               return response.blob()
//             })
//             .then((blob) => {
//               const a = document.createElement('a')
//               a.href = window.URL.createObjectURL(blob)
//               a.target = '_blank'
//               a.download = (res.message as string).split('/')[
//                 (res.message as string).split('/').length - 1
//               ]
//               a.click()
//               pngDownloadLoading.value = false
//             })
//             .catch((error) => {
//               console.error('下载图片时出错:', error)
//               pngDownloadLoading.value = false
//             })
//         }
//       })
//     } else {
//       const res = await composingDesignImages([row.id], type, templateWidth)
//       const url =
//         type === 'tiff'
//           ? `https://ps.jomalls.com/tiff/` + res.message
//           : filePath + res.message
//       if (type === 'tiff') {
//         window.open(url, '_blank')
//       } else {
//         fetch(url)
//           .then((response) => {
//             // 确保响应是 OK
//             if (!response.ok) {
//               throw new Error('网络响应错误')
//             }
//             // 返回图片的二进制数据（Blob）
//             return response.blob()
//           })
//           .then((blob) => {
//             const a = document.createElement('a')
//             a.href = window.URL.createObjectURL(blob)
//             a.target = '_blank'
//             a.download = (res.message as string).split('/')[
//               (res.message as string).split('/').length - 1
//             ]
//             a.click()
//             pngDownloadLoading.value = false
//           })
//           .catch((error) => {
//             console.error('下载图片时出错:', error)
//             pngDownloadLoading.value = false
//           })
//       }
//     }
//   } catch (e) {
//     console.log(e)
//   } finally {
//     typesettingRow.value = undefined
//     loading.close()
//   }
// }
const loadProductionClient = async () => {
  try {
    const res = await getProductionClientApi()
    if (res.code !== 200) return
    productionClient.value = res.data
  } catch (e) {
    console.error(e)
  }
}
const submitConfirm = async () => {
  const ids = selection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await confirmOrderApi(
      ids,
      productionClientValue.value,
      'minimumCost',
    )
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    productionClientVisible.value = false
    search()
    loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const updateOrder = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  try {
    await showConfirm('确定转至待确认吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  const ids = selection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await updateExceptionOrderApi(ids)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const assignOrder = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  currentOrderIds.value = selection.value.map((item) => item.id)
  exceptionDialogVisible.value = true
}
// const handleExceptionOrder = async () => {
//   if (selection.value.length === 0) {
//     return ElMessage.warning('请选择数据')
//   }
//   try {
//     await showConfirm('确定处理异常吗?', {
//       confirmButtonText: '确认',
//       cancelButtonText: '取消',
//       type: 'warning',
//     })
//   } catch {
//     return
//   }
//   const orderIds = selection.value.map((item) => item.id)
//   const loading = ElLoading.service({
//     fullscreen: true,
//     text: '操作中...',
//     background: 'rgba(0, 0, 0, 0.3)',
//   })
//   try {
//     const res = await handleExceptionOrderApi(orderIds)
//     if (res.code !== 200) return
//     ElMessage.success('操作成功')
//     search()
//     loadTabData()
//   } catch (e) {
//     console.error(e)
//   } finally {
//     loading.close()
//   }
// }
const printProductionOrder = async (
  type: 1 | 2,
  item: PodUsOrderListData | null,
) => {
  if (type === 2 && cardSelection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }

  const orderIds =
    type === 1 ? [item!.id] : cardSelection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await printProductionOrderApi(orderIds)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    window.open(filePath + res.message)
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const printPickingOrder = async () => {
  if (cardSelection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  const orderIds = cardSelection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await printPrintOrderApi(orderIds)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    window.open(filePath + res.message)
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const printPickingOrderItem = async (
  row: { batchArrangeNum: string },
  type: number,
) => {
  console.log(333, row)

  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)
    search()
    loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const pickingComplete = async () => {
  if (cardSelection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  try {
    await ElMessageBox.confirm('确定完成拣胚完成吗?', '提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
    })
  } catch {
    return
  }
  const orderIds = cardSelection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await printPickingOrderApi(orderIds)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
    cardSelection.value = []
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const toOutOfStock = async () => {
  if (cardSelection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  const orderIds = cardSelection.value.map((item) => item.podJomallOrderUsId)
  try {
    await ElMessageBox.confirm('确定转至缺货吗?', '提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await toOutOfStockApi(orderIds)
    if (res.code !== 200) return
    search()
    loadTabData()
    cardSelection.value = []
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const exceptionTypes = [
  { value: '1', label: '客户' },
  { value: '2', label: '工厂' },
]
const exceptionDialogVisible = ref(false)
const currentOrderIds = ref<number[]>([])
const exceptionForm = ref({
  exceptionType: '',
  exceptionReason: '',
})
const exceptionFormRef = ref()
const changeExceptionOrder = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  currentOrderIds.value = selection.value.map((item) => item.id)
  exceptionDialogVisible.value = true
}
const inputBlur = () => {
  if (!pageSize.value || Number(pageSize.value) <= 0) {
    pageSize.value = initPageSize.value
  }
  search()
}
const handleExceptionConfirm = async () => {
  try {
    await exceptionFormRef.value.validate()
  } catch {
    return
  }

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

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

// 排单完成

const typesettingForm = ref<{
  typeArr?: string[]
  type?: string
  templateWidth?: number
}>({})
const typesettingVisible = ref(false)
const typesettingType = ref<number>()
const typesettingRow = ref<PodUsOrderListData>()

const showArrange = async (type: number, data?: PodUsOrderListData) => {
  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.craftType)) {
      if (seen.size > 1) return true
    } else {
      seen.add(item.craftType)
      if (seen.size > 1) return true
    }
  }
  return false
}

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
  }

  console.log(4233, params)
  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 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 = {}
}

interface timeLineType {
  time_iso?: string
  time_utc?: string
  description?: string
}

const timeLineVisible = ref(false)
const timeLine = ref<timeLineType[]>([])
const logTrajectory = async (row: { id: string }) => {
  const { data } = await get17TrackInfoApi({ id: row.id })
  const res = data.accepted[0]?.track_info?.tracking
  timeLine.value = res?.providers[0]?.events
  // if (data.rejected?.length) {
  //   console.log(data.rejected[0].error.message)
  //   throw Error(data.rejected[0].error.message)
  // }
  timeLineVisible.value = true
}

const logList = ref<LogListData[]>([])
const logVisible = ref(false)
const operationLog = async (
  id: number,
  e: MouseEvent | null,
  row?: PodUsOrderListData,
) => {
  if (row) {
    currentItem.value = row
  }

  e && e.stopPropagation()
  try {
    const res = await getOperationLogApi(id)
    if (res.code !== 200) return
    logList.value = res.data.map((el) => {
      return {
        ...el,
        local: 'BeiJing',
      }
    })
    tempChinaLogs.value = [...logList.value]

    logVisible.value = true
  } catch (e) {
    console.error(e)
  }
}

const addressInfoVisible = ref(false)

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

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

const InspPackagOrderRef = ref()

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

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

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

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

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

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

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

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

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

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

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

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

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

  isChangeWay.value = true
  try {
    const { data } = await getLogisticsCalculation(row.id as number)
    logisticsWayData.value = data
  } catch (error) {
    console.error(error)
  }
}
//展示返回结果
const resultInfo = ref<
  {
    id: string | number
    status: boolean
    factoryOrderNumber?: string
    message: string
  }[]
>([])
const resultConfirm = () => {
  search()
  loadTabData()
}
const handleMark = (mark: string) => {
  switch (mark) {
    case 'virtual':
      return {
        name: 'VIR',
        color: '#ff9900',
        label: '虚拟商品',
      }
    case 'normal':
      return {
        name: 'G',
        color: '#67C23A',
        label: '普通商品',
      }
    case 'pod':
      return {
        name: 'P',
        color: '#F56C6C',
        label: 'pod商品',
      }
    case 'custom':
      return {
        name: 'C',
        color: '#6d9eeb',
        label: '一件定制商品',
      }
    case 'custom_part':
      return {
        name: 'CP',
        color: '#6d9eeb',
        label: '一件定制局部印商品',
      }
    case 'custom_full':
      return {
        name: 'CF',
        color: '#6d9eeb',
        label: '一件定制满印商品',
      }
    case 'custom_normal':
      return {
        name: 'CB',
        color: '#67C23A',
        label: '胚衣',
      }
    default:
      return {
        name: '',
        color: '#FFFFFF',
        width: '0',
      }
  }
}
/**
 * @description: 更改物流方式
 */
const changeWayRow = ref<LogisticsData>({} as LogisticsData)
const isChangeWayLoading = ref(false)
const changeWayRef = ref()
const wayDialogTitle = ref('')

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

      changeWayRef.value?.setCurrentRow()

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

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

    await Fn(params)
    isChangeWay.value = false

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

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

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

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

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

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

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

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

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

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

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

// 获取工艺列表
const craftList = ref<IAllList[]>([])

const processTypeMap = processType.value.reduce((acc, cur) => {
  acc[cur.value] = cur.label
  return acc
}, {} as Record<string, string>)
const loadCraftList = async () => {
  try {
    const res = await getListCraftApi()
    if (res.code !== 200) return
    const data: CraftListData[] = res.data
    craftList.value = data.map((item) => ({
      id: item.craftCode,
      name: item.craftName,
      warehouseName: processTypeMap[item.craftType] ?? '其他', // craftType 对应中文
    })) as IAllList[]
  } catch (e) {
    console.error(e)
  }
}

const customTagList = ref<{ id: string; name: string }[]>([])

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

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

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

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

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

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

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

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

// 待跟踪分页
const handleWaitTrackCommand = (command: number) => {
  waitTrackStatus.value = command
  search()
  loadTabData()
}

// 重置补胚表单
const resetReplenishmentForm = () => {
  replenishmentForm.value.replenishmentNum = '1'
  replenishmentForm.value.replenishmentReason = ''
  currentReplenishmentRow.value = null
  replenishmentFormRef.value?.clearValidate()
}

// 确认补胚申请
const confirmReplenishment = async () => {
  if (!replenishmentFormRef.value) return

  try {
    await replenishmentFormRef.value.validate()

    const row = currentReplenishmentRow.value
    let data = []

    if (!row) {
      data = cardSelection.value.map((item) => {
        return {
          id: item.podJomallOrderUsId,
          productId: item.id,
          factorySubOrderNumber: item.factorySubOrderNumber || '',
          replenishmentNum: replenishmentForm.value.replenishmentNum,
          podJomallOrderUsStatus: status.value,
          replenishmentReason: replenishmentForm.value.replenishmentReason,
        }
      })
    } else {
      data = [
        {
          id: row.podJomallOrderUsId,
          productId: row.id,
          factorySubOrderNumber: row.factorySubOrderNumber || '',
          replenishmentNum: replenishmentForm.value.replenishmentNum,
          podJomallOrderUsStatus: status.value,
          replenishmentReason: replenishmentForm.value.replenishmentReason,
        },
      ]
    }

    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()
      replenishmentDialogVisible.value = false
    } catch (e) {
      console.error(e)
    } finally {
      loading.close()
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 打开补胚弹窗
const applyForReplenishment = async (row: ProductList | undefined) => {
  if (!row) {
    if (cardSelection.value.length === 0) {
      return ElMessage.warning('请至少选择一条数据')
    }
  }

  currentReplenishmentRow.value = row || null

  // 显示对话框
  replenishmentDialogVisible.value = true
}

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

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

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

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

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

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

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

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

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

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

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

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

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

// 转至已完成
const setFinish = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  await ElMessageBox.confirm('是否转至已完成?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await changeToFinished(
      selection.value.map((item) => item.id).join(','),
    )
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    await loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const reissueOrder = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  const isSameShipmentType =
    Array.from(new Set(selection.value.map((s) => s.shipmentType))).length === 1
  if (!isSameShipmentType) {
    return ElMessage.warning('请选择相同物流类型的数据')
  }
  reissueOrderRef.value.open()
}

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

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

const tempChinaLogs = ref<LogListData[]>([])
const timeType = ref<string>('Asia/Shanghai')

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

function tooltipContent(arr: { name: string }[]) {
  return arr.map((tag) => tag.name).join('、')
}

const token = getToken() as string

async function getPermission() {
  const res = await getAccountCodeByFactoryIdApi({ token })
  permissionBtns.setBtn(res.data)
  console.log(res)
}

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

const getLogisticsWay = async () => {
  const { data } = await getLogisticsWayApi()
  logisticsWayList.value = data
}

const getEmployeeList = async () => {
  const { data } = await getEmployeeListApi()
  employeeList.value = data
}


getPermission()
getLogisticsWay()
getEmployeeList()

const globalProperties =
  getCurrentInstance()?.appContext.config.globalProperties // 获取全局挂载
const isPermissionBtn = globalProperties?.$isPermissionBtn

useRouter().beforeEach((to, from, next) => {
  handleBeforeRouteLeave(to, from, next)
})

const printNormal = async () => {
  await showConfirm('确定普货拣货吗?', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
  const arr: (number | undefined)[] = []
  if (!selection.value.length) {
    return ElMessage.warning('请选择订单')
  }
  console.log(3660, selection.value)

  selection.value.forEach((s) => {
    s.productList &&
      s.productList.forEach((p) => {
        if (p.productMark === 'normal' || p.productMark === 'custom_normal') {
          arr.push(p.id)
        }
      })
  })
  console.log(3661, arr)

  if (!arr.length) {
    ElMessage.warning('暂无可打印的普货拣货单')
    return
  }
  const res = await printNormalPickPdfApi(arr.join())
  ElMessage.success('操作成功')
  window.open(filePath + res.message)
}
</script>
<style lang="scss" scoped>
.header-filter-form {
  :deep(.el-form-item) {
    margin-right: 14px;
    margin-bottom: 10px;
  }
}

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

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

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

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

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

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

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

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

  &: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);
}

.tabs-node_count.green {
  background: rgb(223 240 216);
  color: rgb(39 174 96);
}

.tabs-node_count.yellow {
  background: rgb(255 243 205);
  color: rgb(91, 99, 18);
}

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

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

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

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

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

  .grid-item {
    display: flex;
    overflow: hidden;
    width: 100%;

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

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

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

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

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

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

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

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

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

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

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

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

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

  span {
    font-size: 14px;
  }

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

    &:hover {
      color: red;
    }
  }
}

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

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

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

  .pageSize {
    line-height: 39px;
    color: #606266;
    font-size: 15px;
  }
}

.orderNumber {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
  min-width: 0; /* 关键属性 */
}

.customizedQuantity {
  height: 28px;
  width: 28px;
  color: #f56c6c;
  text-align: center;
  line-height: 24px;
  background-color: #fff;
  border: 2px solid #f56c6c;
  border-radius: 7px;
  margin-right: 2px;
  font-weight: 700;
  box-sizing: border-box;
}

.triangle-box {
  position: absolute;
  top: 0;
  right: 0;
  width: 0;
  height: 0;
  border: 18px solid transparent;
  border-top: 18px solid #e74c3c;
  border-right: 18px solid #e74c3c;
}

.multi-text {
  position: absolute;
  top: -19px;
  color: white;
  font-weight: bold;
}

.triangle-container-wrap {
  position: absolute;
  top: 0;
  right: 0;
}

.triangle-container {
  position: relative;

  .triangle-marker {
    width: 0;
    height: 0;
    border: 18px solid transparent;
    border-right: 18px solid #e74c3c;
    border-top: 18px solid #e74c3c;
  }

  .content {
    position: absolute;
    top: 0;
    left: 18px;
    transform: rotate(45deg);
    color: white;
    text-align: center;
    font-weight: bold;
    font-size: 12px;
  }
}

.triangle-container-wrap {
  position: absolute;
  top: 0;
  right: 0;
}

.triangle-container {
  position: relative;

  .triangle-marker {
    width: 0;
    height: 0;
    border: 18px solid transparent;
    border-right: 18px solid #e74c3c;
    border-top: 18px solid #e74c3c;
  }

  .content {
    position: absolute;
    top: 0;
    left: 18px;
    transform: rotate(45deg);
    color: white;
    text-align: center;
    font-weight: bold;
    font-size: 12px;
  }
}
</style>
<style lang="scss">
.customize-select-style {
  .el-select-dropdown__list {
    width: 500px;
    display: flex;
    flex-wrap: wrap;
  }
}

.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-success);
  display: flex;
  align-items: center;
  outline: none;
}

.el-timeline-item__wrapper {
  padding-left: 15px;
  top: -4px;
}

.el-timeline
  > .el-timeline-item:first-child
  .el-timeline-item__timestamp.is-top {
  color: #409eff;
}

.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tabs-node-quantity {
  position: relative;
  color: red;
  font-size: 12px;
  top: -10px;
  right: 0px;
}

.operate-item {
  position: relative;
}
.download-icon {
  color: var(--el-color-success);
}
.check-icon {
  color: var(--el-color-success);
  position: absolute;
  right: -9px;
  top: 30%;
  transform: translateY(-50%);
}

.flex-1 {
  flex: 1;
  flex-shrink: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.red-big {
  font-size: 15px;
  color: red;
}
</style>
