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

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

              <ElFormItem label="店铺单号">
                <ElInput
                  v-model="searchForm.shopNumber"
                  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.logisticsTracking"
                  placeholder="物流跟踪号"
                  clearable
                  style="width: 150px"
                ></ElInput>
              </ElFormItem>
              <ElFormItem label="物流类型">
                <ElSelect
                  v-model="searchForm.shipmentType"
                  placeholder="物流类型"
                  clearable
                  :teleported="false"
                  style="width: 150px"
                >
                  <ElOption
                    v-for="(item, index) in ['自有物流', '工厂物流']"
                    :key="index"
                    :value="index"
                    :label="item"
                  ></ElOption>
                </ElSelect>
              </ElFormItem>
            </ElForm>
            <template #reference>
              <el-button type="warning" @click="searchVisible = !searchVisible">
                <el-icon v-if="searchVisible">
                  <CaretTop />
                </el-icon>
                <el-icon v-else>
                  <CaretBottom />
                </el-icon>
              </el-button>
            </template>
          </ElPopover>
        </ElFormItem>
        <ElFormItem>
          <span>
            <ElButton type="primary" @click="search">查询</ElButton>
          </span>
        </ElFormItem>
        <ElFormItem>
          <span>
            <ElButton type="danger" @click="resetSearchForm">清空</ElButton>
          </span>
        </ElFormItem>
        <ElFormItem>
          <span v-if="status === 'PICKING'" class="item">
            <ElButton
              :loading="tifDownloadLoading"
              type="warning"
              @click="downloadTif('tiff')"
            >
              TIF排版
            </ElButton>
          </span>
          <span v-if="status === 'PICKING'" class="item">
            <ElButton
              :loading="pngDownloadLoading"
              type="warning"
              @click="downloadTif('png')"
            >
              PNG排版
            </ElButton>
          </span>
          <span v-if="status === 'TO_BE_CONFIRMED'" class="item">
            <ElButton type="success" @click="confirmProduct">
              确认生产
            </ElButton>
          </span>
          <span v-if="status === 'EXCEPTION_ORDER'" class="item">
            <ElButton type="success" @click="updateOrder">
              转至待确认
            </ElButton>
          </span>
          <span
            v-if="status === 'EXCEPTION_ORDER' && exceptionStatus === 3"
            class="item"
          >
            <ElButton type="warning" @click="asyncOrderAddress">
              同步收货地址
            </ElButton>
          </span>
          <span
            v-if="status === 'EXCEPTION_ORDER' && exceptionStatus === 1"
            class="item"
          >
            <ElButton type="warning" @click="assignOrder"> 分派 </ElButton>
          </span>
          <!-- <span
          v-if="status === 'EXCEPTION_ORDER' && exceptionStatus === 2"
          class="item"
        >
          <ElButton type="warning" @click="handleExceptionOrder">
            处理异常
          </ElButton>
        </span> -->
          <span
            v-if="status === 'PICKING' || status === 'TO_BE_REPLENISHMENT'"
            class="item"
          >
            <ElButton type="primary" @click="printProductionOrder">
              打印生产单
            </ElButton>
          </span>
          <span v-if="status === 'TO_BE_REPLENISHMENT'" class="item">
            <ElButton type="success" @click="replenishmentSuccess">
              补胚完成
            </ElButton>
          </span>
          <span v-if="status === 'PICKING'" class="item">
            <ElButton type="success" @click="printPickingOrder">
              打印拣货单
            </ElButton>
          </span>
          <span v-if="status === 'PICKING'" class="item">
            <ElButton type="warning" @click="pickingComplete">
              拣胚完成
            </ElButton>
          </span>
          <span v-if="status === 'PICKING'" class="item">
            <ElButton type="success" @click="toOutOfStock"> 转至缺货 </ElButton>
          </span>
          <span v-if="status === 'TO_BE_CONFIRMED'" class="item">
            <ElButton type="warning" @click="changeExceptionOrder">
              转为异常单
            </ElButton>
          </span>
          <span v-if="status === 'TO_BE_CONFIRMED'" class="item">
            <ElButton type="success" @click="confirmProductToRiin">
              转至锐印生产
            </ElButton>
          </span>
          <span
            v-if="status === 'TO_BE_CONFIRMED' || status === 'EXCEPTION_ORDER'"
            class="item"
          >
            <ElButton type="danger" @click="cancelOrder">取消</ElButton>
          </span>
          <!-- <span v-if="status !== 'IN_PRODUCTION'" class="item">
          <ElButton type="success" @click="handleUpdateRemark">
            添加内部标签
          </ElButton>
        </span> -->
          <span v-if="status === 'IN_PRODUCTION'" class="item">
            <ElButton type="warning" @click="onFastProduction">
              快捷生产
            </ElButton>
          </span>
          <span v-if="status === 'IN_PRODUCTION'" class="item">
            <ElButton type="success" @click="applyForReplenishment(undefined)">
              申请补胚
            </ElButton>
          </span>
          <span v-if="status === 'WAIT_SHIPMENT'" class="item">
            <ElButton type="warning" @click="printPodOrder"> POD打单 </ElButton>
          </span>
          <span v-if="status === 'CREATE_LOGISTICS'" class="item">
            <ElButton type="warning" @click="logisticsToPicking">
              转至待排单
            </ElButton>
          </span>
          <span
            v-if="status === 'WAIT_SHIPMENT' || status === 'CREATE_LOGISTICS'"
            class="item"
          >
            <ElDropdown>
              <el-button type="success">
                物流接口<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <ElDropdownMenu>
                  <ElDropdownItem
                    :disabled="
                      selection.length === 0 ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('createLogisticsOrder')"
                    >创建物流订单</ElDropdownItem
                  >
                  <ElDropdownItem
                    :disabled="
                      selection.length === 0 ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('getTrackingNumber')"
                    >获取跟踪号</ElDropdownItem
                  >
                  <ElDropdownItem
                    :disabled="
                      selection.length === 0 ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('getPrintOrder')"
                    >获取打印面单</ElDropdownItem
                  >
                  <ElDropdownItem
                    :disabled="
                      selection.length === 0 ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('cancelLogisticsOrder')"
                    >取消物流订单</ElDropdownItem
                  >
                  <ElDropdownItem
                    :disabled="
                      selection.length === 0 ||
                      selection.some((item) => item.shipmentType !== 1)
                    "
                    @click="getOrderByIdApi('batchChangeLogistics')"
                    >更换物流</ElDropdownItem
                  >
                </ElDropdownMenu>
              </template>
            </ElDropdown>
          </span>
          <span v-if="status === 'STOCK_OUT'" class="item">
            <ElButton type="warning" @click="stockOutCheck">
              补货校验
            </ElButton>
          </span>
          <span v-if="status === 'STOCK_OUT'" class="item">
            <ElButton type="success" @click="toBePicking"> 转至生产 </ElButton>
          </span>
          <span v-if="status === 'TO_BE_ARRANGE'" class="item">
            <ElButton type="warning" @click="arrangeFinish">排单完成</ElButton>
          </span>
          <span v-if="status !== 'BATCH_DOWNLOAD'" class="item">
            <ElButton type="primary" @click="downloadMaterial"
              >下载素材</ElButton
            >
          </span>
          <span
            v-if="
              status === 'TO_BE_CONFIRMED' ||
              status === 'PICKING' ||
              status === 'STOCK_OUT' ||
              status === 'EXCEPTION_ORDER' ||
              status === 'TO_BE_REPLENISHMENT'
            "
            class="item"
          >
            <ElButton type="success" @click="refreshMaterial">
              刷新素材
            </ElButton>
          </span>
        </ElFormItem>
      </ElForm>
    </div>
    <div class="header-filter-tab">
      <div class="tabs">
        <div
          v-for="item in tabsNav"
          :key="item.status"
          class="tabs-node"
          :class="item.status === status ? 'tabs-node_active' : ''"
          @click="changeTab(item)"
        >
          <span class="tabs-node_label">{{ item.statusName }}</span>
          <span
            v-if="item.quantity"
            class="tabs-node_count"
            :class="{
              blue: item.quantity && item.quantity > 0,
              red: item.status === 'EXCEPTION_ORDER',
            }"
            >{{ item.quantity }}</span
          >
        </div>
        <!-- <div
            v-if="item.status === 'EXCEPTION_ORDER'"
            :key="item.status"
            class="tabs-node"
          >
            <el-dropdown @command="handleExceptionCommand">
              <div>
                <span
                  class="tabs-node_label"
                  style="color: #000; font-weight: 500"
                >
                  异常单
                </span>
                <span
                  class="tabs-node_count"
                  :class="{
                    blue: item.quantity && item.quantity > 0,
                    red: item.status === 'EXCEPTION_ORDER',
                  }"
                  >{{ item.quantity }}</span
                >
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </div>

              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="1">待分派</el-dropdown-item>
                  <el-dropdown-item command="2">待处理</el-dropdown-item>
                  <el-dropdown-item command="3">已处理</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div> -->
      </div>
    </div>
    <div class="order-content flex-1 flex-column overflow-hidden mt-10">
      <div v-if="status === 'EXCEPTION_ORDER'" class="sub-status mb-10">
        <div
          class="sub-status-item"
          :class="exceptionStatus === 1 ? 'sub-active' : ''"
          @click="handleExceptionCommand(1)"
        >
          <span class="sub-status-item-label">待分派</span>
        </div>
        <div
          class="sub-status-item"
          :class="exceptionStatus === 2 ? 'sub-active' : ''"
          @click="handleExceptionCommand(2)"
        >
          <span class="sub-status-item-label">待处理</span>
        </div>
        <div
          class="sub-status-item"
          :class="exceptionStatus === 3 ? 'sub-active' : ''"
          @click="handleExceptionCommand(3)"
        >
          <span class="sub-status-item-label">待同步</span>
        </div>
      </div>
      <div
        v-if="
          status !== '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"
          :serial-numberable="true"
          :selectionable="true"
          :paginated-data="tableData"
          :cell-style="onCellStyle"
          :cell-class-name="onCellClassName"
          :row-style="getRowStyle"
          @selection-change="handleSelectionChange"
        >
          <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">
                    <img :src="item.variantImage" alt="商品图片" />
                  </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 v-if="item.thirdStockSku" class="goods-item-info-item">
                      <span class="goods-item-info-item-label">货号:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.thirdStockSku }}
                      </span>
                      <el-icon
                        class="icon"
                        @click="copy(item.thirdStockSku || '')"
                      >
                        <DocumentCopy />
                      </el-icon>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">工艺:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.craftName }}
                      </span>
                    </div>

                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">备注:</span>
                      <span
                        class="goods-item-info-item-value"
                        :title="item.remark"
                      >
                        {{ item.remark }}
                      </span>
                      <el-icon
                        class="icon"
                        style="color: #e6a23c"
                        @click="handleUpdateRemark(item)"
                      >
                        <EditPen />
                      </el-icon>
                    </div>
                  </div>
                  <div class="goods-item-info">
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">生产单号:</span>
                      <span
                        class="goods-item-info-item-value"
                        :title="item.factorySubOrderNumber"
                      >
                        {{ item.factorySubOrderNumber }}
                      </span>
                      <el-icon
                        class="icon"
                        @click="copy(item.factorySubOrderNumber || '')"
                      >
                        <DocumentCopy />
                      </el-icon>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label"
                        >第三方生产单号:</span
                      >
                      <span
                        class="goods-item-info-item-value"
                        :title="item.thirdSubOrderNumber"
                      >
                        {{ item.thirdSubOrderNumber }}
                      </span>
                      <el-icon
                        class="icon"
                        @click="copy(item.thirdSubOrderNumber || '')"
                      >
                        <DocumentCopy />
                      </el-icon>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">工厂:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.factoryCode }}
                      </span>
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">款号:</span>
                      <span class="goods-item-info-item-value">
                        {{ item.supplierProductNo }}
                      </span>
                    </div>
                    <div
                      v-if="item.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"
                    >
                      <span class="goods-item-info-item-label">补胚数量:</span>
                      <span
                        class="goods-item-info-item-value"
                        :title="item.replenishmentSumNum"
                      >
                        {{ item.replenishmentSumNum || 0 }}
                      </span>
                      <el-button
                        v-if="status === 'WAIT_SHIPMENT'"
                        link
                        size="small"
                        type="success"
                        @click="applyForReplenishment(item)"
                        >申请补胚
                      </el-button>
                      <!-- f -->
                    </div>
                    <div class="goods-item-info-item">
                      <span class="goods-item-info-item-label">克重:</span>
                      <span
                        v-if="item.weight"
                        class="goods-item-info-item-value"
                      >
                        {{ item.weight }}g
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <template #orderDetail="{ row }">
            <div class="order-detail-box">
              <div class="order-detail-item">
                <span class="order-detail-item-label">订单号:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.factoryOrderNumber"
                >
                  {{ row.factoryOrderNumber }}
                </span>
                <el-icon
                  class="icon"
                  @click="copy(row.factoryOrderNumber || '')"
                >
                  <DocumentCopy />
                </el-icon>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">第三方订单号:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.thirdOrderNumber"
                >
                  {{ row.thirdOrderNumber }}
                </span>
                <el-icon class="icon" @click="copy(row.thirdOrderNumber || '')">
                  <DocumentCopy />
                </el-icon>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">店铺单号:</span>
                <span class="order-detail-item-value" :title="row.shopNumber">
                  {{ row.shopNumber }}
                </span>
                <el-icon class="icon" @click="copy(row.shopNumber || '')">
                  <DocumentCopy />
                </el-icon>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">物流类型:</span>
                <span
                  style="color: red; font-weight: 500"
                  class="order-detail-item-value"
                >
                  {{ ['自有物流', '工厂物流'][row.shipmentType] }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">物流跟踪号:</span>
                <span class="order-detail-item-value">
                  <el-button
                    type="primary"
                    :title="row.trackingNumber"
                    link
                    :disabled="!row.expressSheet"
                    @click="downloadFacebook(row.expressSheet)"
                  >
                    {{ row.trackingNumber }}</el-button
                  >
                </span>
                <el-icon class="icon" @click="copy(row.trackingNumber || '')">
                  <DocumentCopy />
                </el-icon>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">总克重:</span>
                <span v-if="row.weight" class="order-detail-item-value">
                  {{ row.weight }}g
                </span>
              </div>
              <div
                v-if="row.status !== 'TO_BE_CONFIRMED'"
                class="order-detail-item"
              >
                <span class="order-detail-item-label">生产端:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.productionClient"
                >
                  {{ row.productionClient }}
                </span>
              </div>
              <div
                v-if="
                  row.productionClient === 'JOMALL' &&
                  row.status !== 'TO_BE_CONFIRMED'
                "
                class="order-detail-item"
              >
                <span class="order-detail-item-label">发货仓库:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.warehouseName"
                >
                  {{ row.warehouseName }}
                </span>
              </div>
              <div
                v-if="
                  row.productionClient === 'JOMALL' &&
                  row.status !== 'TO_BE_CONFIRMED'
                "
                class="order-detail-item"
              >
                <span class="order-detail-item-label">物流方式:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.logisticsWayName"
                >
                  {{ row.logisticsWayName }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">收货人:</span>
                <span class="order-detail-item-value" :title="row.receiverName">
                  {{ row.receiverName }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">收货人电话:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.receiverPhone"
                >
                  {{ row.receiverPhone }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">收货人邮编:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.receiverPostCode"
                >
                  {{ row.receiverPostCode }}
                </span>
              </div>
              <div class="order-detail-item">
                <span class="order-detail-item-label">收货地址:</span>
                <span
                  class="order-detail-item-value"
                  :title="row.lanshouAddress"
                >
                  {{ row.lanshouAddress }}
                </span>
              </div>
            </div>
          </template>
          <template #price="{ row }">
            <div class="order-price-box">
              <div class="order-price-item">
                <span class="order-price-item-label">商品总价：</span>
                <span class="order-price-item-value">
                  {{ row.totalAmount }}($)
                </span>
              </div>

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

              <div class="order-time-item">
                <span class="order-time-item-label">完成时间：</span>
                <span class="order-time-item-value">
                  {{ row.finishTime }}
                </span>
              </div>
            </div> -->
          </template>
          <template #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 #operate="{ row }">
            <div
              v-if="status === 'BATCH_DOWNLOAD'"
              class="operate-box-vertical"
            >
              <span class="operate-item">
                <ElButton
                  :disabled="!row.url"
                  link
                  type="primary"
                  @click="handleDownload(row, 'png')"
                >
                  PNG下载
                </ElButton>
              </span>
              <span class="operate-item">
                <ElButton
                  :disabled="!row.tiffUrl"
                  link
                  type="primary"
                  @click="handleDownload(row, 'tiff')"
                >
                  TIF下载
                </ElButton>
              </span>
              <span class="operate-item">
                <ElButton
                  link
                  type="warning"
                  @click="handleReComposingDesign(row)"
                >
                  重新排版
                </ElButton>
              </span>
              <span class="operate-item">
                <ElButton link type="danger" @click="handleBatchDelete(row)">
                  删除
                </ElButton>
              </span>
            </div>
            <div v-else class="operate-box">
              <span v-if="status !== 'BATCH_DOWNLOAD'" class="operate-item">
                <ElButton
                  link
                  type="primary"
                  @click="operationLog(row.id, null)"
                >
                  操作日志
                </ElButton>
              </span>

              <!-- <span
                v-if="!row.expressSheet && row.status === 'TO_BE_CONFIRMED'"
                class="operate-item"
              >
                <ElButton link type="primary" @click="confirm(row)">
                  确认
                </ElButton>
              </span> -->
              <span
                v-if="
                  row.shipmentType === 0 &&
                  ['CREATE_LOGISTICS', 'WAIT_SHIPMENT'].includes(status)
                "
                class="operate-item"
              >
                <ElButton link type="primary" @click="showLogistics(row)">
                  更新物流信息
                </ElButton>
              </span>
              <span
                v-if="
                  row.shipmentType === 1 &&
                  ['CREATE_LOGISTICS', 'WAIT_SHIPMENT'].includes(status)
                "
                class="operate-item"
              >
                <ElButton link type="primary" @click="handleUpdateAddress(row)">
                  修改地址
                </ElButton>
              </span>
              <span
                v-if="
                  (status === 'WAIT_SHIPMENT' ||
                    status === 'CREATE_LOGISTICS') &&
                  row.shipmentType === 1
                "
                class="operate-item"
              >
                <ElButton link type="primary" @click="handleStockOut(row)">
                  更换物流
                </ElButton>
              </span>
              <span
                v-if="
                  row.shipmentType === 0 &&
                  ['CREATE_LOGISTICS', 'WAIT_SHIPMENT'].includes(status)
                "
                class="operate-item"
              >
                <ElButton
                  link
                  type="primary"
                  @click="handleRefreshAddress(row)"
                >
                  刷新地址
                </ElButton>
              </span>
            </div>
          </template>
        </TableView>
      </div>
      <div
        v-else
        v-loading="loading"
        element-loading-text="加载中..."
        class="card-wrapper flex-1 flex-column overflow-hidden"
      >
        <div v-if="tableData.length > 0" class="card-list">
          <div
            v-for="cardItem in tableData as ProductList[]"
            :key="cardItem.id"
            class="card-list-item"
            @click="cardClick(cardItem)"
            @mouseleave="handleChangeImages(null, cardItem)"
          >
            <CommonCard
              :card-item="cardItem"
              :active="isSelectStatused(cardItem)"
              :show-sku="false"
              :show-product-info="false"
              :image-field="'variantImage'"
              @contextmenu.prevent="(v: MouseEvent) => rightClick(v)"
            >
              <template
                #top_right
               v-if="['ZPZY', 'CXZY', 'THZY'].includes(cardItem?.craftCode || '')"
              >
                <img
                  :src="`/images/pic/${cardItem.craftCode}.png`"
                  width="100px;"
                  height="100px"
                  alt=""
                />
              </template>
              <template #bottom_left>
                <span
                  v-if="cardItem?.factorySubOrderNumber"
                  title="生产单号"
                  class="factory-sub-order-number"
                  @click.stop="
                    copy(String(cardItem?.factorySubOrderNumber || ''))
                  "
                >
                  {{ cardItem?.factorySubOrderNumber }}
                </span>
              </template>
              <template #operations>
                <div
                  style="position: absolute; top: -35px; right: 2px"
                  v-if="cardItem.platform"
                >
                  <img
                    :src="`/images/icon/${getPlatformImg(cardItem.platform)}`"
                    style="height: 30px"
                  />
                </div>

                <Icon
                  name="caozuorizhi"
                  @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 JSON.parse(
                        cardItem.imageAry || '',
                      )"
                      :key="index"
                      :title="item.title"
                      class="item-image"
                      @mousemove="handleChangeImages(item, cardItem)"
                    >
                      <img :src="item?.url" height="28" />
                    </div>
                  </div>
                </div>
              </template>
              <template #info>
                <div class="grid-container">
                  <div class="grid-item" title="商品名称">
                    <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">
                    <span title="Base SKU" class="grid-item-value">
                      {{ cardItem?.baseSku }}
                    </span>
                  </div>
                  <div v-if="status !== 'TO_BE_ARRANGE'" class="grid-item">
                    <span class="grid-item-label">补胚数量：</span>
                    <span class="grid-item-value">
                      {{ cardItem?.replenishmentNum || 0 }}
                    </span>
                  </div>

                  <!-- <div class="grid-item">
                    <span title="Variant SKU" class="grid-item-value">
                      {{ cardItem?.variantSku }}
                    </span>
                  </div> -->
                  <div class="grid-item" title="工艺">
                    <span class="grid-item-label">工艺：</span>
                    <span class="grid-item-value">
                      {{ cardItem?.craftName }}
                    </span>
                  </div>
                  <div class="grid-item">
                    <span title="库存SKU" class="grid-item-value">
                      {{ cardItem?.thirdSkuCode }}
                    </span>
                  </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" title="店铺单号">
                    <span
                      class="grid-item-value"
                      @click="copy(cardItem?.shopNumber || '')"
                    >
                      {{ cardItem?.shopNumber }}
                    </span>
                  </div>
                  <!-- <div class="grid-item" title="订单号">
                    <span
                      class="grid-item-value"
                      @click="copy(cardItem?.factoryOrderNumber || '')"
                    >
                      {{ cardItem?.factoryOrderNumber }}
                    </span>
                  </div> -->

                  <div class="grid-item">
                    <span
                      :title="`第三方生产单号:${cardItem?.thirdSubOrderNumber}`"
                      class="grid-item-value"
                      @click.stop="
                        copy(String(cardItem?.thirdSubOrderNumber || ''))
                      "
                    >
                      {{ cardItem?.thirdSubOrderNumber }}
                    </span>
                  </div>
                  <div
                    v-if="cardItem.batchArrangeNumber"
                    class="grid-item"
                    title="批次号"
                  >
                    <span
                      class="grid-item-value"
                      @click="copy(cardItem?.batchArrangeNumber || '')"
                    >
                      {{ cardItem?.batchArrangeNumber }}
                    </span>
                  </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"
  >
    <LogList :log-list="logList" />
  </el-dialog>
  <FastProduction
    v-model:detail-visible="detailVisible"
    :current-status="status"
    :detail-data="detailData"
    :fast-key="fastKey"
    @on-success="handleSuccess"
    @close="fastClose"
  ></FastProduction>
  <PodMakeOrder
    v-model="podOrderVisible"
    :print-order="printOrder"
    :warehouse-list="warehouseList"
    @set-printer="handlePrinterChange"
    @refresh="onFastRefresh"
  />
  <ElDialog
    v-model="productionClientVisible"
    title="生产端"
    width="600px"
    :close-on-click-modal="false"
  >
    <template #header>
      <div class="dialog-header">
        <span style="margin-right: 8px; font-size: 18px">确认</span>
        <el-tooltip content="默认最低运费分派">
          <el-icon color="red">
            <WarningFilled />
          </el-icon>
        </el-tooltip>
      </div>
    </template>
    <div
      class="production-client"
      style="display: flex; align-items: center; gap: 8px"
    >
      <label style="white-space: nowrap" for="">生产端：</label>
      <ElSelect
        v-model="productionClientValue"
        clearable
        placeholder="请选择生产端"
      >
        <ElOption
          v-for="(item, index) in productionClient"
          :key="index"
          :value="item.code || ''"
          :label="`${item.remark}(${item.code})`"
        ></ElOption>
      </ElSelect>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="productionClientVisible = false">取消</ElButton>
        <ElButton type="primary" @click="submitConfirm">确认</ElButton>
      </div>
    </template>
  </ElDialog>

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

  <el-dialog
    v-model="isChangeWay"
    :close-on-click-modal="false"
    :title="wayDialogTitle"
  >
    <el-table
      ref="changeWayRef"
      v-loading="isChangeWayLoading"
      height="400px"
      class="production-client-table"
      :data="logisticsWayData"
      border
      highlight-current-row
      @row-click="(v:LogisticsData) =>rowClick(v, wayDialogTitle)"
    >
      <el-table-column
        label="序号"
        width="60"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column
        label="物流名称"
        align="center"
        prop="logisticsWayName"
      ></el-table-column>
      <el-table-column
        label="发货仓库"
        align="center"
        prop="warehouseName"
      ></el-table-column>
      <el-table-column
        label="物流编码"
        align="center"
        prop="logisticsWayCode"
      ></el-table-column>
      <el-table-column
        label="所在分区"
        align="center"
        prop="partition"
      ></el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="{ row }">
          <b v-if="row.status" style="color: green">成功</b>
          <b v-else-if="!row.status" style="color: red">失败</b>
        </template>
      </el-table-column>
      <el-table-column label="预计运费（$）" align="center" prop="payFreight">
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button :disabled="isChangeWayLoading" @click="cancelWayDialog">
        取消
      </el-button>
      <el-button
        :loading="isChangeWayLoading"
        type="primary"
        @click="changeWaySubmit(wayDialogTitle)"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
  <UpdateAddress
    v-if="updateAddVisible"
    v-model:form="currentRow"
    v-model:visible="updateAddVisible"
    :country-list="countryList"
    @success="search"
  ></UpdateAddress>
  <ElDialog
    v-model="exceptionDialogVisible"
    title="转为异常单"
    width="500px"
    :close-on-click-modal="false"
    @open="handleExceptionDialogOpen"
  >
    <ElForm ref="exceptionFormRef" :model="exceptionForm" label-width="100px">
      <ElFormItem
        label="异常类型"
        prop="exceptionType"
        :rules="
          status === 'EXCEPTION_ORDER'
            ? { required: true, message: '请选择异常类型' }
            : {}
        "
      >
        <ElSelect
          v-model="exceptionForm.exceptionType"
          style="width: 100%"
          placeholder="请选择异常类型"
          clearable
        >
          <ElOption
            v-for="type in exceptionTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem
        label="异常原因"
        prop="exceptionReason"
        :rules="
          status !== 'EXCEPTION_ORDER'
            ? { required: true, message: '请输入异常原因' }
            : {}
        "
      >
        <ElInput
          v-model="exceptionForm.exceptionReason"
          style="width: 100%"
          type="textarea"
          :rows="3"
          placeholder="请输入异常原因"
        />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="exceptionDialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleExceptionConfirm">
          确定
        </ElButton>
      </span>
    </template>
  </ElDialog>
  <el-dialog
    v-model="logisticsVisible"
    :close-on-click-modal="false"
    width="700px"
    title="更新物流信息"
  >
    <el-form
      v-if="logisticsVisible"
      ref="logisticsFormRef"
      label-width="100px"
      label-position="left"
      :model="logisticsForm"
    >
      <el-form-item prop="processNumber" label="物流处理号">
        <el-input
          v-model="logisticsForm.processNumber"
          placeholder="请输入物流处理号"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="trackingNumber" label="物流跟踪号">
        <el-input
          v-model="logisticsForm.trackingNumber"
          placeholder="请输入物流跟踪号"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="logisticsForm.trackingNumber"
        prop="expressSheetUrl"
        label="物流面单"
      >
        <el-upload accept=".pdf" action="" :before-upload="expressSheetUpload">
          <el-button type="primary">点击上传</el-button>
        </el-upload>
        <div v-if="logisticsForm.expressSheet" class="file">
          <span>{{ logisticsForm.expressSheet.name }}</span>
          <el-icon
            class="expressSheetClose"
            @click="logisticsForm.expressSheet = null"
          >
            <Close></Close>
          </el-icon>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="logisticsVisible = false">取消</el-button>
      <el-button type="primary" @click="logisticsSubmit"> 确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { getUserMarkList } from '@/api/common'
import {
  ArrowDown,
  CaretBottom,
  CaretTop,
  // Edit,
  WarningFilled,
} from '@element-plus/icons-vue'
import {
  getCardOrderList,
  getOrderList,
  getOrderTabData,
  confirmOrderApi,
  changeExceptionOrderApi,
  cancelOrderApi,
  getOperationLogApi,
  downloadMaterialApi,
  updateExceptionOrderApi,
  printProductionOrderApi,
  getOrderDetailById,
  updateRemarkApi,
  getProductionClientApi,
  printPickingOrderApi,
  printPrintOrderApi,
  stockOutCheckApi,
  toBePickingApi,
  loadWarehouseListApi,
  getLogisticsCalculation,
  refreshMaterialApi,
  getTrackingNumberApi,
  getfaceSimplexFileApi,
  cancelLogisticsOrderApi,
  composingDesignImages,
  changeLogisticsApi,
  createLogisticsOrderApi,
  // updateLogisticsToPickingApi,
  updateLogisticsToArrangeApi,
  createLogisticsOrdersApi,
  syncReceiverAddress,
  refreshAddressApi,
  confirmProductApi,
  confirmProductToRiinApi,
  updateSelfLogistics,
  uploadExpressSheet,
  // handleExceptionOrderApi,
  applyForReplenishmentApi,
  replenishmentSuccessApi,
  toOutOfStockApi,
  arrangeFinishApi,
  getListCraftApi,
  batchDownloadApi,
  batchDownloadDownloadApi,
  batchDownloadDeleteApi,
  batchDownloadRecomposingApi,
} 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,
} from '@/types/api/podUsOrder'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from '@/utils/hooks/useValue'
import { showConfirm } from '@/utils/ui'
import { DocumentCopy, EditPen } from '@element-plus/icons-vue'
import { Column, ElFormItem } from 'element-plus'
import { computed, onMounted, ref, nextTick } from 'vue'
import FastProduction from './FastProduction.vue'
import { filePath } from '@/api/axios'
import PodMakeOrder from './PodMakeOrder.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'

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

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

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

const 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('TO_BE_CONFIRMED')
const detailData = ref({})
const [searchForm, resetSearchForm] = useValue<SearchForm>({
  timeType: 1,
  shopNumber: '',
  shipmentType: '',
  userMark: '',
  logisticsTracking: '',
  baseSku: '',
  factoryOrderNumber: '',
  sku: '',
  factorySubOrderNumber: '',
  status: '',
  customizedQuantity: '',
  multi: null,
  startTime: null,
  endTime: null,
  exceptionHandling: undefined,
  platform: '',
  productionClient: '',
  warehouseId: '',
  thirdSkuCode: '',
  supplierProductNo: '',
  batchArrangeNumber: '',
  craftCode: '',
  thirdStockSku: '',
})
const exceptionStatus = ref(1)
const 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]
      },
    },
  ],
}
const timeRange = ref<string[]>([])
const getDateRange = (days = 0, type: 'past' | 'future' = 'past') => {
  const end = dayjs()
  const start =
    type === 'past' ? end.subtract(days, 'day') : end.add(days, 'day')
  return [start.startOf('day').toDate(), end.endOf('day').toDate()]
}

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

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

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

    await batchDownloadDownloadApi({ id: row.id, type })
    ElMessage.success('操作成功')
    search()
    loadTabData()
  } catch (e) {
    ElMessage.error('下载失败')
    console.error(e)
  } finally {
    loading.close()
  }
}
// 批量下载 删除
const handleBatchDelete = async (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)',
  })
  try {
    const res = await batchDownloadDeleteApi({ id: row.id })
    if (res.code !== 200) return
    ElMessage.success(res.message)
    search()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
// 批量下载 重新排版
const handleReComposingDesign = async (row: PodUsOrderListData) => {
  try {
    await showConfirm('确定重新排版吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await batchDownloadRecomposingApi({ id: row.id })
    if (res.code !== 200) return
    ElMessage.success(res.message)
    search()
    loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const tableColumns = computed(() => {
  if (status.value === 'BATCH_DOWNLOAD') {
    return [
      {
        label: '批次号',
        prop: 'batchArrangeNum',
        minWidth: 200,
        align: 'center',
      },
      {
        label: '下载状态',
        slot: 'downloadStatus',
        width: 150,
        prop: 'downloadStatus',
        align: 'center',
      },
      {
        label: '订单数量',
        prop: 'productNum',
        width: 120,
        align: 'center',
      },
      {
        label: '素材数量',
        width: 120,
        prop: 'materialNum',
        align: 'center',
      },
      {
        label: '创建人',
        width: 200,
        prop: 'employeeAccount',
        align: 'center',
      },
      {
        label: '创建时间',
        width: 250,
        prop: 'createTime',
        slot: 'createTime',
        align: 'center',
      },
      {
        label: '完成时间',
        width: 250,
        prop: 'finishTime',
        slot: 'finishTime',
        align: 'center',
      },
      {
        label: '操作',
        slot: 'operate',
        width: 300,
        align: 'center',
        fixed: 'right',
        prop: 'operate',
      },
    ]
  }
  return [
    {
      label: '商品',
      prop: 'goods',
      slot: 'goods',
      minWidth: 920,
    },
    {
      label: '订单详情',
      prop: 'orderDetail',
      slot: 'orderDetail',
      width: 300,
    },
    {
      label: '单价',
      slot: 'price',
      width: 160,
      prop: 'price',
      align: 'left',
    },
    {
      label: '时间',
      slot: 'time',
      width: 180,
      prop: 'time',
      align: 'left',
    },
    // {
    //   label: '内部便签',
    //   slot: 'innerLabel',
    //   width: 300,
    //   prop: 'innerLabel',
    // },
    {
      label: '异常原因',
      width: 300,
      prop: 'exceptionReason',
      slot: 'exceptionReason',
      align: 'left',
    },
    {
      label: '操作',
      slot: 'operate',
      width: 180,
      align: 'center',
      fixed: 'right',
      prop: 'operate',
    },
  ]
})
const rightMenuRef = ref()
const rightClick = (e: MouseEvent) => {
  rightMenuRef.value.setPosition({
    x: e.clientX,
    y: e.clientY,
  })
}

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

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

const changeTab = (item: Tab) => {
  status.value = item.status || ''
  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 === 'operate' ||
    column.property === 'exceptionReason'
  ) {
    return { verticalAlign: 'top' }
  }
}
const onCellClassName = ({ column }: { column: Column }) => {
  if (column.property === 'exceptionReason') {
    return 'exception-reason'
  }
}
const loadTabData = async () => {
  try {
    const res = await getOrderTabData()
    tabsNav.value = res.data
  } catch (error) {
    // showError(error)
  }
}
const getUserMark = async () => {
  try {
    const res = await getUserMarkList()
    userMarkList.value = res.data
  } catch (error) {
    //showError(error)
  }
}

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

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

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

const downloadTif = async (type: string) => {
  if (!cardSelection.value.length) {
    return ElMessage.warning('请选择数据')
  }
  if (type === 'tiff') {
    tifDownloadLoading.value = true
  } else {
    pngDownloadLoading.value = true
  }
  try {
    const res = await composingDesignImages(
      cardSelection.value.map((el) => el.id),
      type,
    )
    const url =
      type === 'tiff'
        ? `https://ps.jomalls.com/tiff/` + res.message
        : filePath + res.message
    if (type === 'tiff') {
      window.open(url, '_blank')
      tifDownloadLoading.value = false
    } else {
      fetch(url)
        .then((response) => {
          // 确保响应是 OK
          if (!response.ok) {
            throw new Error('网络响应错误')
          }
          // 返回图片的二进制数据（Blob）
          return response.blob()
        })
        .then((blob) => {
          const a = document.createElement('a')
          a.href = window.URL.createObjectURL(blob)
          a.target = '_blank'
          a.download = (res.message as string).split('/')[
            (res.message as string).split('/').length - 1
          ]
          a.click()
          pngDownloadLoading.value = false
        })
        .catch((error) => {
          console.error('下载图片时出错:', error)
          pngDownloadLoading.value = false
        })
    }
  } catch (e) {
    console.log(e)
    if (type === 'tiff') {
      tifDownloadLoading.value = false
    } else {
      pngDownloadLoading.value = false
    }
  }
}

const loadProductionClient = async () => {
  try {
    const res = await getProductionClientApi()
    if (res.code !== 200) return
    productionClient.value = res.data
  } catch (e) {
    console.error(e)
  }
}
const submitConfirm = async () => {
  const ids = selection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await confirmOrderApi(
      ids,
      productionClientValue.value,
      'minimumCost',
    )
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    productionClientVisible.value = false
    search()
    loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const updateOrder = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  try {
    await showConfirm('确定转至待确认吗?', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  const ids = selection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await updateExceptionOrderApi(ids)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const assignOrder = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  currentOrderIds.value = selection.value.map((item) => item.id)
  exceptionDialogVisible.value = true
}
// const handleExceptionOrder = async () => {
//   if (selection.value.length === 0) {
//     return ElMessage.warning('请选择数据')
//   }
//   try {
//     await showConfirm('确定处理异常吗?', {
//       confirmButtonText: '确认',
//       cancelButtonText: '取消',
//       type: 'warning',
//     })
//   } catch {
//     return
//   }
//   const orderIds = selection.value.map((item) => item.id)
//   const loading = ElLoading.service({
//     fullscreen: true,
//     text: '操作中...',
//     background: 'rgba(0, 0, 0, 0.3)',
//   })
//   try {
//     const res = await handleExceptionOrderApi(orderIds)
//     if (res.code !== 200) return
//     ElMessage.success('操作成功')
//     search()
//     loadTabData()
//   } catch (e) {
//     console.error(e)
//   } finally {
//     loading.close()
//   }
// }
const printProductionOrder = async () => {
  if (cardSelection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  const orderIds = cardSelection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await printProductionOrderApi(orderIds)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    window.open(filePath + res.message)
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const printPickingOrder = async () => {
  if (cardSelection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  const orderIds = cardSelection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await printPrintOrderApi(orderIds)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    window.open(filePath + res.message)
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const pickingComplete = async () => {
  if (cardSelection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  try {
    await ElMessageBox.confirm('确定完成拣胚完成吗?', '提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
    })
  } catch {
    return
  }
  const orderIds = cardSelection.value.map((item) => item.id)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await printPickingOrderApi(orderIds)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
    cardSelection.value = []
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const toOutOfStock = async () => {
  if (cardSelection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  const orderIds = cardSelection.value.map((item) => item.podJomallOrderUsId)
  try {
    await ElMessageBox.confirm('确定转至缺货吗?', '提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await toOutOfStockApi(orderIds)
    if (res.code !== 200) return
    search()
    loadTabData()
    cardSelection.value = []
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const exceptionTypes = [
  { value: '1', label: '客户' },
  { value: '2', label: '工厂' },
]
const exceptionDialogVisible = ref(false)
const currentOrderIds = ref<number[]>([])
const exceptionForm = ref({
  exceptionType: '',
  exceptionReason: '',
})
const exceptionFormRef = ref()
const changeExceptionOrder = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  currentOrderIds.value = selection.value.map((item) => item.id)
  exceptionDialogVisible.value = true
}
const inputBlur = () => {
  if (!pageSize.value || Number(pageSize.value) <= 0) {
    pageSize.value = initPageSize.value
  }
  search()
}
const handleExceptionConfirm = async () => {
  try {
    await exceptionFormRef.value.validate()
  } catch {
    return
  }

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

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

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

  if (selectedIds.length === 0) {
    return ElMessage({
      message: '请选择订单',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }
  try {
    await ElMessageBox.confirm('确定排单完成吗?', '提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await arrangeFinishApi(selectedIds)
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    loadTabData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const logList = ref<LogListData[]>([])
const logVisible = ref(false)
const operationLog = async (id: number, e: MouseEvent | null) => {
  e && e.stopPropagation()
  try {
    const res = await getOperationLogApi(id)
    if (res.code !== 200) return
    logList.value = res.data
    logVisible.value = true
  } catch (e) {
    console.error(e)
  }
}
const handleSuccess = () => {
  loadTabData()
  search()
}
const fastClose = () => {
  loadTabData()
  detailVisible.value = false
}
const podOrderVisible = ref(false)
const printPodOrder = async () => {
  const lodop = getCLodop(null, null)
  if (!lodop) return

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

/**
 * @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 handleStockOut = async (row: PodUsOrderListData) => {
  wayDialogTitle.value = `切换物流(当前物流方式：${row.logisticsWayName})`

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

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

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

      changeWayRef.value?.setCurrentRow()

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

const cancelWayDialog = () => {
  changeWayRow.value = {} as LogisticsData
  changeWayRef.value?.setCurrentRow()
  isChangeWay.value = false
}
//确认物流
const changeWaySubmit = async (title: string) => {
  if (!changeWayRow.value?.logisticsWayId) {
    return ElMessage.warning('请选择一条物流方式')
  }
  if (!changeWayRow.value.status) {
    return ElMessage.warning('请选择状态为成功的物流方式')
  }
  let Fn
  if (title !== '创建物流订单') {
    if (
      changeWayRow.value.logisticsWayId === selection.value[0]?.logisticsWayId
    ) {
      return ElMessage.warning('更改的物流方式不能相同')
    }
    Fn = changeLogisticsApi
  } else {
    Fn = createLogisticsOrderApi
  }
  isChangeWayLoading.value = true
  try {
    const params = {
      updateByIdParam: {
        id: selection.value[0]?.id,
        dataVersion: selection.value[0]?.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) => {
  sheetPrinter.value = value
}
const { getCLodop } = useLodop()
const printOrder = async (
  data: OrderData,
  callback: (status: boolean) => void,
) => {
  const lodop = getCLodop(null, null)
  if (!lodop) return
  lodop.PRINT_INIT('打印内容')
  const printerIndex = lodop.SET_PRINTER_INDEX(sheetPrinter.value)
  console.log(
    'printerIndex',
    printerIndex,
    `sheetPrinter.value:${sheetPrinter.value}`,
  )
  if (!printerIndex) {
    ElMessage.error('打印机设置失败')
    callback && callback(false)
    return
  }
  if (data.filePath) {
    const strURL = filePath + data.filePath
    console.log('strURL', strURL, data)
    lodop.ADD_PRINT_PDF(
      0,
      0,
      '100%',
      '100%',
      /(https):\/\/([^/]+)/i.test(strURL) ? downloadPDF(strURL) : strURL,
    )
  } else {
    lodop.SEND_PRINT_RAWDATA(data.fileData || '')
  }
  console.log('lodop.CVERSION', lodop.CVERSION)
  if (lodop.CVERSION) {
    const startTime = Date.now()
    const jobCode = await lodopCall((lodop) => {
      lodop.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
      return lodop.PRINT()
    })
    console.log('jobCode', jobCode)
    // eslint-disable-next-line no-constant-condition
    while (true) {
      const ok = await lodopCall((lodop) =>
        lodop.GET_VALUE('PRINT_STATUS_OK', jobCode),
      )
      console.log('PRINT_STATUS_OK:', jobCode, `ok: ${ok}`)
      if (ok == 1) {
        console.log('打印成功')
        // 打印状态：成功
        callback && callback(true)
        return
      }
      // 如果打印状态表示未成功或者返回了空，继续获取任务是否存在
      const exist = await lodopCall((lodop) =>
        lodop.GET_VALUE('PRINT_STATUS_EXIST', jobCode),
      )
      console.log(
        '[LODOP] PRINT_STATUS OK,EXIST',
        jobCode,
        `ok:${ok}`,
        `exist:${exist}`,
        `jobCode:${jobCode}`,
        `(${Date.now() - startTime}ms)`,
      )
      if (exist == 0) {
        console.log('任务不存在了', `exist:${exist}`)
        // 任务不存在了
        callback && callback(true)
        return
      }

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

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

const loadCraftList = async () => {
  try {
    const res = await getListCraftApi()
    if (res.code !== 200) return
    craftList.value = res.data
  } catch (e) {
    console.error(e)
  }
}
const refreshMaterial = async () => {
  if (status.value === 'PICKING' || status.value === 'TO_BE_REPLENISHMENT') {
    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:
        status.value !== 'PICKING' && status.value !== 'TO_BE_REPLENISHMENT'
          ? selection.value.map((item) => item.id).join(',')
          : undefined,
      productIds:
        status.value === 'PICKING' || status.value === 'TO_BE_REPLENISHMENT'
          ? 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))
}
onMounted(() => {
  loadTabData()
  getUserMark()
  loadProductionClient()
  loadWarehouseList()
  loadCraftList()
})

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

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

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

  .goods-item-img {
    width: 100px;
    height: 100px;

    img {
      width: 100%;
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  .grid-item {
    display: flex;
    overflow: hidden;

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

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

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

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

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

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

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

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

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

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

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

.operate-box-vertical {
  display: flex;
  justify-content: space-around;
  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;
  }
}
</style>
<style lang="scss">
.customize-select-style {
  .el-select-dropdown__list {
    width: 500px;
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
