<template>
  <div class="page card h-100 flex-gap-10 overflow-hidden flex">
    <div class="order-status">
      <ElTree
        ref="treeRef"
        default-expand-all
        :expand-on-click-node="false"
        :default-expanded-keys="['ALL']"
        :highlight-current="true"
        node-key="status"
        :data="statusTree"
        :props="{ children: 'children', label: 'statusName' }"
        class="status-tree"
        @node-click="handleStatusNodeClick"
      >
        <template #default="{ node, data }">
          <div class="tree-node">
            <div class="tree-node-label-wrapper">
              <span class="tree-node-label">{{ data.statusName }}</span>
              <span
                v-if="
                  data.status !== 'ALL' &&
                  (data.quantity || data.quantity === 0)
                "
                class="tree-node-count"
              >
                {{ `(${data.quantity})` }}
              </span>
            </div>
            <span
              v-if="data.children && data.children.length"
              class="tree-node-expand"
              @click.stop="toggleExpand(node)"
            >
              <el-icon
                ><ArrowUp v-if="node.expanded" /><ArrowDown v-else
              /></el-icon>
            </span>
          </div>
        </template>
      </ElTree>
    </div>
    <div class="order-content flex-1 flex-column overflow-hidden">
      <div v-if="!isSpecialLayout" class="header">
        <div class="header-filter-form">
          <ElForm
            class="search-form"
            :model="searchForm"
            :inline="true"
            label-width="70px"
          >
            <ElFormItem label="平台">
              <ElSelect
                v-model="searchForm.platform"
                placeholder="请选择"
                clearable
                filterable
                popper-class="customize-select-style"
                style="width: 140px"
              >
                <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="工艺">
              <LogisticsWaySelect
                v-model="searchForm.craftCode"
                :company-list="craftList"
                :start-width="'150px'"
                search-placeholder="搜索工艺名称"
                start-placeholder="请选择工艺名称"
              ></LogisticsWaySelect>
            </ElFormItem>

            <ElFormItem label="库存SKU">
              <ElInput
                v-model.trim="searchForm.thirdSkuCode"
                placeholder="库存SKU"
                clearable
                style="width: 140px"
              />
            </ElFormItem>

            <ElFormItem label="款号">
              <ElInput
                v-model.trim="searchForm.supplierProductNo"
                placeholder="款号"
                clearable
                style="width: 140px"
              />
            </ElFormItem>

            <ElFormItem label="批次号">
              <ElInput
                v-model.trim="searchForm.batchArrangeNumber"
                placeholder="批次号"
                clearable
                style="width: 140px"
              />
            </ElFormItem>

            <ElFormItem label="操作单号">
              <ElInput
                v-model.trim="searchForm.orderNumber"
                placeholder="操作单号"
                clearable
                style="width: 140px"
              />
            </ElFormItem>

            <ElFormItem label="商品类型">
              <ProductTypeFilter
                v-model="searchForm.productMarkList"
                :options="productTypeGroups"
                :multiple="false"
                placeholder="请选择商品类型"
                width="140px"
              />
            </ElFormItem>

            <ElFormItem label="数量">
              <el-radio-group v-model="searchForm.multi">
                <el-radio-button :value="false" @click="toggleMulti(false)"
                  >单件</el-radio-button
                >
                <el-radio-button :value="true" @click="toggleMulti(true)"
                  >多件</el-radio-button
                >
              </el-radio-group>
            </ElFormItem>

            <ElFormItem>
              <ElPopover placement="bottom" width="600" trigger="click">
                <ElForm
                  ref="searchFormPopoverRef"
                  :model="searchForm"
                  size="default"
                  inline
                  label-width="100px"
                >
                  <ElFormItem style="width: 100%; padding-right: 40px">
                    <div style="width: 100%; display: flex; flex-wrap: nowrap">
                      <el-select
                        v-model="searchForm.timeType"
                        clearable
                        :teleported="false"
                        placeholder="时间类型"
                        style="flex: 1; margin-right: 10px"
                      >
                        <el-option :value="1" label="创建时间"></el-option>
                        <el-option :value="2" label="确认时间"></el-option>
                        <el-option :value="3" label="完成时间"></el-option>
                      </el-select>
                      <el-date-picker
                        v-model="dateRange"
                        :teleported="false"
                        :default-time="[
                          new Date(0, 0, 0, 0, 0, 0),
                          new Date(0, 0, 0, 23, 59, 59),
                        ]"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        type="datetimerange"
                        style="width: 280px"
                        :shortcuts="pickerOptions.shortcuts"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        clearable
                      />
                    </div>
                  </ElFormItem>
                  <ElFormItem label="订单号">
                    <ElInput
                      v-model="searchForm.factoryOrderNumber"
                      placeholder="订单号"
                      clearable
                      style="width: 150px"
                    />
                  </ElFormItem>
                  <ElFormItem label="客户">
                    <el-select
                      v-model="searchForm.userMark"
                      clearable
                      filterable
                      :teleported="false"
                      style="width: 150px"
                      placeholder="客户"
                    >
                      <el-option
                        v-for="item in userMarkList"
                        :key="item"
                        :value="item"
                        :label="item"
                      ></el-option>
                    </el-select>
                  </ElFormItem>
                  <ElFormItem label="Variant SKU">
                    <ElInput
                      v-model.trim="searchForm.sku"
                      placeholder="Variant SKU"
                      clearable
                      style="width: 150px"
                    />
                  </ElFormItem>
                  <ElFormItem label="物流跟踪号">
                    <ElInput
                      v-model.trim="searchForm.trackingNumber"
                      placeholder="物流跟踪号"
                      clearable
                      style="width: 150px"
                    />
                  </ElFormItem>
                  <ElFormItem
                    v-if="!cardLayoutStatuses.includes(status)"
                    label="收件国家"
                  >
                    <ElSelect
                      v-model="searchForm.receiverCountry"
                      placeholder="收件国家"
                      clearable
                      multiple
                      :teleported="false"
                      style="width: 150px"
                      filterable
                      @change="changeReplaceShipment"
                    >
                      <ElOption
                        v-for="item in receiverCountryList"
                        :key="item.countryCode"
                        :value="item.countryCode"
                        :label="item.nameCn + '(' + item.countryCode + ')'"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                  <ElFormItem label="是否代发">
                    <ElSelect
                      v-model="searchForm.replaceShipment"
                      placeholder="是否代发"
                      clearable
                      :teleported="false"
                      style="width: 150px"
                      @change="changeReplaceShipment"
                    >
                      <ElOption
                        v-for="(item, index) in ['不代发', '代发']"
                        :key="index"
                        :value="index"
                        :label="item"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                  <ElFormItem
                    v-if="searchForm.replaceShipment === 0"
                    label="物流类型"
                  >
                    <ElSelect
                      v-model="searchForm.shipmentType"
                      placeholder="物流类型"
                      clearable
                      :teleported="false"
                      style="width: 150px"
                    >
                      <ElOption
                        v-for="(item, index) in ['自提', '快递']"
                        :key="index"
                        :value="index"
                        :label="item"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                  <ElFormItem
                    v-if="searchForm.replaceShipment === 1"
                    label="物流类型"
                  >
                    <ElSelect
                      v-model="searchForm.shipmentType"
                      placeholder="物流类型"
                      clearable
                      :teleported="false"
                      style="width: 150px"
                    >
                      <ElOption
                        v-for="(item, index) in ['自有物流', '工厂物流']"
                        :key="index"
                        :value="index"
                        :label="item"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                  <ElFormItem label="ERP标签">
                    <ElSelect
                      v-model="searchForm.tagsIdArr"
                      placeholder="请选择ERP标签"
                      clearable
                      filterable
                      multiple
                      collapse-tags
                      collapse-tags-tooltip
                      :teleported="false"
                      style="width: 150px"
                    >
                      <ElOption
                        v-for="(item, index) in customTagList"
                        :key="index"
                        :value="item.id"
                        :label="item.name"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                  <ElFormItem label="订单来源">
                    <ElSelect
                      v-model="searchForm.source"
                      placeholder="请选择"
                      clearable
                      :teleported="false"
                      style="width: 150px"
                    >
                      <ElOption
                        v-for="(item, index) in sourceList"
                        :key="index"
                        :value="item.id"
                        :label="item.name"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                  <ElFormItem label="尺码筛选">
                    <ElSelect
                      v-model="searchForm.size"
                      placeholder="请选择"
                      clearable
                      filterable
                      :teleported="false"
                      style="width: 150px"
                    >
                      <ElOption
                        v-for="(item, index) in sizes"
                        :key="index"
                        :value="item"
                        :label="item"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                  <ElFormItem label="自有物流公司">
                    <ElSelect
                      v-model="searchForm.logisticsCompanyCode"
                      placeholder="请选择"
                      clearable
                      filterable
                      :teleported="false"
                      style="width: 150px"
                    >
                      <ElOption
                        v-for="(item, index) in allCodelist"
                        :key="index"
                        :value="item.code"
                        :label="item.basicsName"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                  <ElFormItem v-if="status !== 'CANCELLED'" label="拦截订单">
                    <ElSelect
                      v-model="searchForm.interceptStatus"
                      placeholder="请选择"
                      clearable
                      filterable
                      :teleported="false"
                      style="width: 150px"
                    >
                      <ElOption
                        v-for="(_, index) in ['否', '是']"
                        :key="index"
                        :value="!!index"
                        :label="index === 0 ? '否' : '是'"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                  <ElFormItem label="规范素材">
                    <ElSelect
                      v-model="searchForm.standardDesignImage"
                      placeholder="请选择"
                      clearable
                      filterable
                      style="width: 150px"
                    >
                      <ElOption
                        v-for="(_, index) in ['否', '是']"
                        :key="index"
                        :value="!!index"
                        :label="index === 0 ? '否' : '是'"
                      ></ElOption>
                    </ElSelect>
                  </ElFormItem>
                </ElForm>
                <template #reference>
                  <el-button
                    type="warning"
                    @click="searchVisible = !searchVisible"
                  >
                    <el-icon v-if="searchVisible">
                      <CaretTop />
                    </el-icon>
                    <el-icon v-else>
                      <CaretBottom />
                    </el-icon>
                  </el-button>
                </template>
              </ElPopover>
            </ElFormItem>

            <ElFormItem>
              <ElButton type="primary" @click="() => refreshCurrentView()">
                查询
              </ElButton>
              <ElButton @click="reset"> 重置 </ElButton>
            </ElFormItem>
          </ElForm>
        </div>
      </div>
      <!-- ====== 操作按钮栏 ====== -->
      <div v-if="!isSpecialLayout" class="operation-list">
        <span v-if="status === 'PENDING_RECEIVE'" class="item">
          <ElButton type="success" @click="handleConfirmOrder">
            {{
              pendingAcceptSubTab === 'ACCEPT_FAIL_OUT_OF_STOCK'
                ? '重新接单'
                : '确认接单'
            }}
          </ElButton>
        </span>
        <span
          v-if="status === 'PENDING_RECEIVE' || status === 'SUSPEND'"
          class="item"
        >
          <ElButton type="danger" @click="handleCancelOrder">取消订单</ElButton>
        </span>

        <ElDropdown
          v-if="status === 'PENDING_CREATE_LOGISTICS'"
          trigger="click"
          @command="handleLogisticsCommand"
        >
          <span class="item">
            <ElButton type="warning">
              物流接口 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </ElButton>
          </span>
          <template #dropdown>
            <ElDropdownMenu>
              <ElDropdownItem command="createLogistic"
                >创建物流订单</ElDropdownItem
              >
              <ElDropdownItem command="getTrackingNumber"
                >获取跟踪号</ElDropdownItem
              >
              <ElDropdownItem command="getPrintOrder"
                >获取打印面单</ElDropdownItem
              >
              <ElDropdownItem command="cancelLogistic"
                >取消物流订单</ElDropdownItem
              >
            </ElDropdownMenu>
          </template>
        </ElDropdown>

        <span v-if="status === 'PENDING_CREATE_LOGISTICS'" class="item">
          <ElButton type="success" @click="handleUpdateCustomsInfo"
            >更新报关信息</ElButton
          >
        </span>
        <span v-if="status === 'PENDING_RECEIVE'" class="item">
          <ElButton type="warning" @click="handleTransferOldFlow"
            >转旧流程</ElButton
          >
        </span>
        <span v-if="status === 'PENDING_SCHEDULE'" class="item">
          <ElButton type="primary" @click="handleArrange">排单</ElButton>
        </span>

        <ElDropdown
          v-if="
            status === 'PENDING_PICK' ||
            status === 'PENDING_REPLENISH' ||
            status === 'IN_PRODUCTION'
          "
          trigger="click"
          @command="handleDtfCommand"
        >
          <span class="item">
            <ElButton type="primary">
              DTF排版 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </ElButton>
          </span>
          <template #dropdown>
            <ElDropdownMenu>
              <ElDropdownItem command="tiff_42">TIF(40+2cm)</ElDropdownItem>
              <ElDropdownItem command="tiff_60">TIF(60cm)</ElDropdownItem>
              <ElDropdownItem command="png_42">PNG(40+2cm)</ElDropdownItem>
              <ElDropdownItem command="png_60">PNG(60cm)</ElDropdownItem>
            </ElDropdownMenu>
          </template>
        </ElDropdown>
        <span
          v-if="
            status === 'PENDING_PICK' ||
            status === 'PENDING_REPLENISH' ||
            status === 'IN_PRODUCTION'
          "
          class="item"
        >
          <ElButton type="success" @click="handlePrintProductionOrder"
            >打印生产单</ElButton
          >
        </span>
        <span v-if="status === 'PENDING_PICK'" class="item">
          <ElButton type="warning" @click="handlePrintPickOrder"
            >打印拣胚单</ElButton
          >
        </span>
        <span v-if="status === 'PENDING_PICK'" class="item">
          <ElButton type="success" @click="handlePickComplete"
            >拣胚完成</ElButton
          >
        </span>
        <span v-if="status === 'PENDING_PICK'" class="item">
          <ElButton type="danger" @click="handlePickFail">拣胚失败</ElButton>
        </span>
        <span v-if="status === 'PENDING_REPLENISH'" class="item">
          <ElButton type="success" @click="handleReplenishComplete"
            >补胚完成</ElButton
          >
        </span>
        <span v-if="status === 'PENDING_REPLENISH'" class="item">
          <ElButton type="danger" @click="handleReplenishFail"
            >补胚失败</ElButton
          >
        </span>
        <span v-if="status === 'PENDING_PACKING'" class="item">
          <ElButton type="success" @click="handleSeedingWall"
            >播种墙配货</ElButton
          >
        </span>
        <span v-if="status === 'PENDING_PACKING'" class="item">
          <ElButton type="primary" @click="handleSinglePrint"
            >单件打单</ElButton
          >
        </span>
        <span
          v-if="status === 'IN_PRODUCTION' || status === 'PENDING_PACKING'"
          class="item"
        >
          <ElButton type="warning" @click="handleApplyReplenish"
            >申请补胚</ElButton
          >
        </span>
        <span v-if="status === 'IN_PRODUCTION'" class="item">
          <ElButton type="success" @click="handleQuickProduction"
            >快捷生产</ElButton
          >
        </span>
        <span v-if="status === 'IN_PRODUCTION'" class="item">
          <ElButton type="success" @click="handleProductionComplete"
            >生产完成</ElButton
          >
        </span>

        <!-- 待发货 -->
        <template v-if="status === 'PENDING_DELIVERY'">
          <span class="item">
            <ElButton type="primary" @click="handleWeightSort"
              >称重分拣</ElButton
            >
          </span>
        </template>
        <!-- 已完成 -->
        <template v-if="status === 'COMPLETED'">
          <span class="item">
            <ElButton type="success" @click="handleArchiveOrder"
              >订单归档</ElButton
            >
          </span>
          <span class="item">
            <ElButton type="primary" @click="handleGetTrackingNumber"
              >获取跟踪号</ElButton
            >
          </span>
          <span class="item">
            <ElButton type="warning" @click="handleStatusPush"
              >状态推送</ElButton
            >
          </span>
        </template>
        <!-- 挂起 -->
        <template v-if="status === 'SUSPEND'">
          <span class="item">
            <ElButton type="warning" @click="handleCancelSuspend"
              >取消挂起</ElButton
            >
          </span>
          <span class="item">
            <ElButton type="primary" @click="handleSyncAddress"
              >同步收货地址</ElButton
            >
          </span>
        </template>
        <span
          v-if="
            [
              'PENDING_CREATE_LOGISTICS',
              'PENDING_SCHEDULE',
              'PENDING_DELIVERY',
              'PICKING',
            ].includes(status)
          "
          class="item"
        >
          <ElButton type="danger" @click="handleSuspend">挂起</ElButton>
        </span>
        <span
          v-if="
            status === 'PENDING_SCHEDULE' ||
            status === 'PENDING_REPLENISH' ||
            status === 'IN_PRODUCTION' ||
            status === 'PENDING_DELIVERY' ||
            status === 'SUSPEND' ||
            status === 'PENDING_PICK'
          "
          class="item"
        >
          <ElButton type="success" @click="handleDownloadMaterial"
            >下载素材</ElButton
          >
        </span>
        <span
          v-if="
            [
              'PENDING_RECEIVE',
              'PENDING_CREATE_LOGISTICS',
              'PENDING_SCHEDULE',
              'PENDING_PICK',
              'PENDING_REPLENISH',
              'IN_PRODUCTION',
              'PENDING_PACKING',
            ].includes(status)
          "
          class="item"
        >
          <ElButton type="primary" @click="handleRefreshProductInfo"
            >刷新商品信息</ElButton
          >
        </span>
      </div>
      <div v-if="status === 'SUSPEND'" class="status-subtabs">
        <div
          v-for="tab in suspendedTabs"
          :key="tab.value"
          class="status-subtab"
          :class="{ active: suspendedSubTab === tab.value }"
          @click="suspendedSubTab = tab.value"
        >
          {{ tab.label }}({{ tab.count || 0 }})
        </div>
      </div>

      <div v-if="status === 'PENDING_RECEIVE'" class="status-subtabs">
        <div
          class="status-subtab"
          :class="{ active: pendingAcceptSubTab === 'PENDING_RECEIVE' }"
          @click="handlePendingAcceptTabClick('PENDING_RECEIVE')"
        >
          待接单<span> ({{ pendingAcceptCounts.pendingCount }}) </span>
        </div>
        <div
          class="status-subtab"
          :class="{
            active: pendingAcceptSubTab === 'ACCEPT_FAIL_OUT_OF_STOCK',
          }"
          @click="handlePendingAcceptTabClick('ACCEPT_FAIL_OUT_OF_STOCK')"
        >
          接单失败-缺货<span>
            ({{ pendingAcceptCounts?.acceptedOutOfStockCount || 0 }})
          </span>
        </div>
      </div>
      <!-- 批次管理 -->
      <BatchManageTable v-if="status === 'BATCH_MANAGE'" ref="batchManageRef" />

      <!-- 等待补货 -->
      <WaitingRestockTable
        v-if="status === 'AWAITING_RESTOCK'"
        ref="waitingRestockRef"
      />

      <!-- 到派单、配货中子状态 -->
      <div v-if="isCardLayout" :key="status" class="card-content">
        <CardLayout
          ref="cardLayoutRef"
          :status="status"
          :query-payload="getQueryPayload()"
          @selection-change="handleCardSelectionChange"
        />
      </div>

      <!-- 表格布局 -->
      <div v-if="isTableLayout" class="table-content">
        <splitDiv size="55">
          <template #top>
            <div v-loading="loading" class="table-list flex-1 overflow-hidden">
              <TableView
                ref="tableRef"
                highlight-current-row
                :paginated-data="tableData"
                :columns="mainColumns"
                serial-numberable
                selectionable
                @selection-change="handleMainSelectionChange"
                @row-click="handleRowClick"
              >
                <template #operation="{ row }">
                  <ElButton
                    v-if="status === 'PENDING_RECEIVE'"
                    type="primary"
                    link
                    size="small"
                    @click.stop="handleSingleConfirmOrder(row)"
                  >
                    {{
                      pendingAcceptSubTab === 'ACCEPT_FAIL_OUT_OF_STOCK'
                        ? '重新接单'
                        : '接单'
                    }}
                  </ElButton>
                </template>
              </TableView>
            </div>
            <ElPagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[50, 100, 200, 300]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              style="margin: 10px auto 0"
              @size-change="onPageSizeChange"
              @current-change="onCurrentPageChange"
            />
          </template>
          <template #bottom>
            <el-tabs
              v-model="activeTab"
              class="tabs-wrapper"
              @tab-click="handleTabClick"
            >
              <el-tab-pane name="product" label="包含商品">
                <div v-loading="subLoading" class="sub-table-wrapper">
                  <TableView
                    :paginated-data="productList"
                    :columns="productColumns"
                    serial-numberable
                  />
                </div>
              </el-tab-pane>
              <el-tab-pane name="log" label="操作日志">
                <div v-loading="subLoading" class="detail-table-content">
                  <LogList :log-list="logList" />
                  <div v-if="!logList.length" class="empty-content">
                    暂无数据
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </template>
        </splitDiv>
      </div>
    </div>
    <ConfirmOrderDialog
      ref="confirmOrderDialogRef"
      @success="(data) => openResultInfoDialog(data)"
    />
    <CancelOrderDialog
      ref="cancelOrderDialogRef"
      @success="() => refreshCurrentView({ isRefreshTree: true })"
    />
    <SuspendDialog
      ref="suspendDialogRef"
      @success="() => refreshCurrentView({ isRefreshTree: true })"
    />
    <PickCompleteDialog
      ref="pickCompleteDialogRef"
      @success="() => refreshCurrentView({ isRefreshTree: true })"
    />
    <PickFailDialog
      ref="pickFailDialogRef"
      @success="() => refreshCurrentView({ isRefreshTree: true })"
    />

    <CreateLogisticDialog
      ref="createLogisticDialogRef"
      :new-order-selection="selectedRows"
      @refresh-table="() => refreshCurrentView({ isRefreshTree: true })"
    />
    <UpdateCustomDeclarationInfoDialog
      v-model="updateCustomsDialogVisible"
      :order-selection="selectedRows"
      :is-new-order="true"
      @refresh-table="refreshCurrentView"
    />
    <WeightDialog ref="weightDialogRef" @update-list="refreshCurrentView" />
    <FastProduction
      v-model:detail-visible="detailVisible"
      :detail-data="detailData"
      :fast-key="fastKey"
      :default-auto-sure="true"
      :show-operation-no-row="true"
      not-found-message="操作单不存在"
      pending-order-label="操作单号"
      please-scan-tip="请扫码操作单号"
      search-input-audio-tip="请录入操作单号"
      history-storage-key="historyFactoryOrderNewData"
      tracking-placeholder="扫描枪输入操作单号，录入下一单本单自动生产完成，最后一单扫两次完成生产"
      :query-api="getOperationByNo"
      :complete-api="completeOperationById"
      :download-api="downloadOperationById"
      @on-success="handleFastProductionSuccess"
      @close="fastClose"
    />

    <ArrangeDialog
      ref="arrangeDialogRef"
      @success="() => refreshCurrentView({ isRefreshTree: true })"
    />

    <OperateDetailsDialog
      ref="operateDetailsDialogRef"
      title="申请补胚"
      @success="() => refreshCurrentView({ isRefreshTree: true })"
    />

    <PodMakeOrder
      v-model="podOrderVisible"
      :print-order="printOrder"
      :warehouse-list="warehouseList"
      @set-printer="handlePrinterChange"
      @set-warehouse-id="handleWarehouseIdChange"
      @refresh="() => refreshCurrentView({ isRefreshTree: true })"
    />
    <ResultInfo
      ref="resultRefs"
      :list="resultInfo"
      @confirm="() => refreshCurrentView({ isRefreshTree: true })"
    ></ResultInfo>
  </div>
</template>

<script setup lang="tsx">
import {
  ArrowDown,
  ArrowUp,
  CaretTop,
  CaretBottom,
  Edit,
} from '@element-plus/icons-vue'
import { computed, onMounted, ref } from 'vue'
import splitDiv from '@/components/splitDiv/splitDiv.vue'
import TableView from '@/components/TableView.vue'
import ResultInfo from '@/views/order/components/ResultInfo.vue'
import type { BaseRespData } from '@/types/api'
import type {
  FactoryOrderNewListData,
  ProductListData,
} from '@/types/api/order/factoryOrderNew'
import platformJson from '../../../json/platform.json'
import {
  refreshProductInfoApi,
  transferOldFlowApi,
  cancelSuspendApi,
  archiveOrderApi,
  printPickOrderApi,
  applyReplenishApi,
  getTrackingNumberApi,
  getfaceSimplexFileApi,
  cancelLogisticsOrderApi,
  downloadMaterialApi,
  downloadOperationMaterialApi,
  composingNewPodOrderDesignImages,
  printNewPodOrderProductionOrderApi,
  syncReceiverAddress,
  updateRemarkApi,
  completeDeliveryApi,
  getByOperationNoLogApi,
} from '@/api/factoryOrderNew'
import { filePath } from '@/api/axios'
import { OrderData } from '@/types/api/podMakeOrder'
import useLodop from '@/utils/hooks/useLodop'
import { printWithLodop } from '@/utils/lodopPrinter'
import LogisticsWaySelect from '@/views/logistics/components/LogisticsWaySelect'
import ProductTypeFilter from './component/ProductTypeFilter.vue'
import ConfirmOrderDialog from './component/ConfirmOrderDialog.vue'
import CancelOrderDialog from './component/CancelOrderDialog.vue'
import SuspendDialog from './component/SuspendDialog.vue'
import PickCompleteDialog from './component/PickCompleteDialog.vue'
import PickFailDialog from './component/PickFailDialog.vue'
import CardLayout from './component/CardLayout.vue'
import BatchManageTable from './component/BatchManageTable.vue'
import WaitingRestockTable from './component/WaitingRestockTable.vue'
import ArrangeDialog from './component/ArrangeDialog.vue'
import OperateDetailsDialog from './component/OperateDetailsDialog.vue'
import CreateLogisticDialog from '@/views/order/components/CreateLogisticDialog.vue'
import UpdateCustomDeclarationInfoDialog from '@/views/order/components/UpdateCustomDeclarationInfoDialog.vue'
import WeightDialog from '@/views/order/components/WeightDialog.vue'
import FastProduction from '@/views/order/components/FastProduction.vue'
import PodMakeOrder from '@/views/order/podUs/PodMakeOrder.vue'
import { ResultInfoDataItem } from '@/types/api/order/common'
import { useOrderDictionaries } from './hooks/useOrderDictionaries'
import { useOrderSearchForm } from './hooks/useOrderSearchForm'
import { useOrderStatusTree } from './hooks/useOrderStatusTree'
import { useOrderListAndDetail } from './hooks/useOrderListAndDetail'
import { useOrderBatchActions } from './hooks/useOrderBatchActions'

const resultInfo = ref<ResultInfoDataItem[]>([])
const resultRefs = ref()

const batchManageRef = ref<InstanceType<typeof BatchManageTable>>()
const waitingRestockRef = ref<InstanceType<typeof WaitingRestockTable>>()
const cardLayoutRef = ref<InstanceType<typeof CardLayout>>()

const {
  userMarkList,
  receiverCountryList,
  customTagList,
  allCodelist,
  craftList,
  warehouseList,
  sourceList,
  sizes,
  productTypeGroups,
  loadAllDictionaries,
} = useOrderDictionaries()

const refreshCurrentViewProxy = ref<() => void>(() => {})
const {
  searchForm,
  dateRange,
  searchVisible,
  pickerOptions,
  toggleMulti,
  changeReplaceShipment,
  getQueryPayload,
  reset,
} = useOrderSearchForm(() => refreshCurrentViewProxy.value())

const statusCurrentPageRef = ref(1)
const statusPageSizeRef = ref(50)
const {
  cardLayoutStatuses,
  statusTree,
  status,
  pendingAcceptSubTab,
  pendingAcceptCounts,
  suspendedTabs,
  suspendedSubTab,
  treeRef,
  isCardLayout,
  isSpecialLayout,
  isTableLayout,
  getListPageAcceptedSubStatus,
  getPendingReceiveCounts,
  loadStatusTreeCounts,
  handlePendingAcceptTabClick: handlePendingAcceptTabClickRaw,
  toggleExpand,
} = useOrderStatusTree({
  getQueryPayload,
  currentPage: statusCurrentPageRef,
  pageSize: statusPageSizeRef,
  onClearTableState: () => {},
  onRefreshCurrentView: () => {},
})

const {
  subLoading,
  activeTab,
  productList,
  logList,
  tableRef,
  selectedRows,
  cardSelectList,
  loading,
  currentPage,
  pageSize,
  total,
  tableData,
  onCurrentPageChange,
  onPageSizeChange,
  refreshTableList,
  getSelectedIds,
  clearTableState,
  handleMainSelectionChange,
  handleCardSelectionChange,
  getOrderDetailsById,
  handleRowClick,
  handleTabClick,
} = useOrderListAndDetail({
  status,
  isCardLayout,
  isTableLayout,
  getQueryPayload,
  getListPageAcceptedSubStatus,
})
statusCurrentPageRef.value = currentPage.value
statusPageSizeRef.value = pageSize.value

const refreshCurrentView = (options?: { isRefreshTree?: boolean }) => {
  if (options?.isRefreshTree) void loadStatusTreeCounts()
  if (isSpecialLayout.value) {
    if (status.value === 'BATCH_MANAGE') batchManageRef.value?.refresh()
    if (status.value === 'AWAITING_RESTOCK') waitingRestockRef.value?.refresh()
    return
  }
  if (isCardLayout.value) {
    cardLayoutRef.value?.clearSelection()
    cardLayoutRef.value?.refresh(true)
    return
  }
  if (status.value === 'PENDING_RECEIVE') {
    statusCurrentPageRef.value = currentPage.value
    statusPageSizeRef.value = pageSize.value
    void getPendingReceiveCounts()
  }
  refreshTableList()
}
refreshCurrentViewProxy.value = () => refreshCurrentView()

const handleStatusNodeClick = (node: { status: string }) => {
  status.value = node.status
  if (node.status !== 'PENDING_RECEIVE') {
    pendingAcceptSubTab.value = 'PENDING_RECEIVE'
  }
  if (node.status !== 'SUSPEND') {
    suspendedSubTab.value = 'CUSTOMER_INTERCEPT'
  }
  clearTableState()
  if (!isSpecialLayout.value) {
    refreshCurrentView()
  }
}
const handlePendingAcceptTabClick = (
  tab: 'PENDING_RECEIVE' | 'ACCEPT_FAIL_OUT_OF_STOCK',
) => handlePendingAcceptTabClickRaw(tab, refreshTableList)
const mainColumns = [
  {
    prop: 'factoryOrderNumber',
    label: '订单编号',
    minWidth: 160,
    align: 'center',
  },
  {
    prop: 'thirdOrderNumber',
    label: '客户单号',
    minWidth: 160,
    align: 'center',
  },
  {
    prop: 'shopNumber',
    label: '店铺单号',
    minWidth: 160,
  },
  {
    prop: 'statusName',
    label: '订单状态',
    minWidth: 120,
    align: 'center',
  },
  {
    prop: 'tagsIdList',
    label: '客户标签',
    minWidth: 160,
  },
  {
    prop: 'logisticsWayName',
    label: '物流方式',
    minWidth: 140,
    align: 'center',
  },
  {
    prop: 'trackingNumber',
    label: '物流跟踪号',
    minWidth: 160,
    align: 'center',
  },
  { prop: 'weight', label: '总克重', minWidth: 120, align: 'right' },
  {
    prop: 'productNum',
    label: '商品总数量',
    minWidth: 120,
    align: 'right',
  },
  { prop: 'receiverName', label: '收货人', align: 'center', minWidth: 120 },
  {
    prop: 'receiverPhone',
    label: '收货人电话',
    minWidth: 140,
    align: 'center',
  },
  {
    prop: 'receiverPostCode',
    label: '收货人邮编',
    minWidth: 140,
    align: 'center',
  },
  {
    label: '收货地址',
    minWidth: 220,
    align: 'left',
    render: ({ row }: { row: FactoryOrderNewListData }) => {
      return (
        <div>
          <span>{row?.receiverCountry || ''}</span>
          <span>{row?.receiverProvince || ''}</span>
          <span>{row?.receiverCity || ''}</span>
          <span>{row?.receiverDistrict || ''}</span>
        </div>
      )
    },
  },
  { prop: 'createTime', label: '创建时间', minWidth: 180, align: 'center' },
  {
    prop: 'startStockingTime',
    label: '接单时间',
    sortable: true,
    minWidth: 180,
    align: 'center',
  },
  {
    prop: 'finishTime',
    label: '完成时间',
    sortable: true,
    minWidth: 180,
  },
  {
    prop: 'operation',
    label: '操作',
    minWidth: 120,
    align: 'center',
    slot: 'operation',
    fixed: 'right',
  },
]

const baseProductColumns = [
  {
    key: 'variantImage',
    prop: 'variantImage',
    label: '商品图片',
    minWidth: 90,
    align: 'center',
    render: (row: ProductListData) => {
      return (
        <div>
          <el-image
            src={row?.variantImage ?? ''}
            previewSrcList={[row?.variantImage ?? '']}
            style="width: 50px; height: 50px"
            previewTeleported
          />
        </div>
      )
    },
  },
  {
    key: 'productName',
    prop: 'productName',
    label: '商品名称',
    minWidth: 200,
    showOverflowTooltip: true,
  },
  {
    key: 'variantSku',
    prop: 'variantSku',
    label: '变体SKU',
    minWidth: 160,
    align: 'center',
  },
  {
    key: 'thirdSkuCode',
    prop: 'thirdSkuCode',
    label: '库存SKU',
    minWidth: 160,
    align: 'center',
  },
  {
    key: 'craftCode',
    prop: 'craftCode',
    label: '工艺',
    minWidth: 100,
    align: 'center',
  },
  {
    key: 'styleNo',
    prop: 'styleNo',
    label: '款号',
    minWidth: 100,
    align: 'center',
  },
  { key: 'price', prop: 'price', label: '价格', minWidth: 100, align: 'right' },
  {
    prop: 'num',
    label: '数量',
    minWidth: 100,
    align: 'right',
  },
  {
    prop: 'weight',
    label: '克重',
    minWidth: 100,
    align: 'right',
  },
  {
    key: 'availableQuantity',
    prop: 'availableQuantity',
    label: '可用数量',
    minWidth: 100,
    align: 'right',
  },
  {
    key: 'stockQuantity',
    prop: 'stockQuantity',
    label: '库存数量',
    minWidth: 100,
    align: 'right',
  },
  {
    key: 'occupiedQuantity',
    prop: 'occupiedQuantity',
    label: '占用数量',
    minWidth: 100,
    align: 'right',
  },
  {
    key: 'customsNameEnglish',
    prop: 'customsNameEnglish',
    label: '英文报关名称',
    width: 160,
    align: 'center',
  },
  {
    key: 'customsNameChinese',
    prop: 'customsNameChinese',
    label: '中文报关名称',
    width: 160,
    align: 'center',
  },
  {
    key: 'customsWeight',
    prop: 'customsWeight',
    label: '申报重量(g)',
    width: 100,
    align: 'right',
  },
  {
    key: 'customsValue',
    prop: 'customsValue',
    label: '申报价值($)',
    width: 100,
    align: 'right',
  },
  {
    key: 'remark',
    prop: 'remark',
    label: '备注',
    width: 160,
    align: 'center',
    render: (row: ProductListData) => {
      return (
        <div style="display:flex;align-items:center;justify-content:center;gap:4px">
          <span>{row?.remark ?? ''}</span>
          <el-icon
            style="cursor:pointer;color:#409eff;flex-shrink:0"
            onClick={(e: Event) => {
              e.stopPropagation()
              handleEditRemark(row)
            }}
          >
            <Edit />
          </el-icon>
        </div>
      )
    },
  },
]

const productColumns = computed(() => {
  if (status.value === 'PENDING_DELIVERY') {
    return [
      ...baseProductColumns,
      {
        key: 'operation',
        prop: 'operation',
        label: '操作',
        width: 120,
        fixed: 'center',
        render: ({ row }: { row: ProductListData }) => {
          return (
            <el-button
              type="warning"
              link
              size="small"
              onClick={(e: Event) => {
                e.stopPropagation()
                handleSubApplyReplenish(row)
              }}
            >
              申请补胚
            </el-button>
          )
        },
      },
    ]
  }
  return baseProductColumns
})

const confirmOrderDialogRef = ref<InstanceType<typeof ConfirmOrderDialog>>()
const cancelOrderDialogRef = ref<InstanceType<typeof CancelOrderDialog>>()
const suspendDialogRef = ref<InstanceType<typeof SuspendDialog>>()
const pickCompleteDialogRef = ref<InstanceType<typeof PickCompleteDialog>>()
const pickFailDialogRef = ref<InstanceType<typeof PickFailDialog>>()
const operateDetailsDialogRef = ref()
const arrangeDialogRef = ref<InstanceType<typeof ArrangeDialog>>()
const createLogisticDialogRef = ref()
const updateCustomsDialogVisible = ref(false)
const weightDialogRef = ref()
const detailVisible = ref(false)
const fastKey = ref('')
const detailData = ref<Record<string, unknown>>({})
const { ensureSelection, executeBatchAction } = useOrderBatchActions({
  getIds: getSelectedIds,
  refreshCurrentView,
})

const handleEditRemark = async (row: ProductListData) => {
  try {
    const { value } = await ElMessageBox.prompt('请输入备注', '提示', {
      inputValue: row.remark || '',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '请输入备注',
    })
    try {
      const res = await updateRemarkApi(row.id, value)
      if (res.code !== 200) return
      ElMessage.success('备注修改成功')
      getOrderDetailsById('product')
    } catch (e) {
      console.error(e)
    }
  } catch {
    // cancelled
  }
}

const handleSubApplyReplenish = (row: ProductListData) => {
  operateDetailsDialogRef.value?.open({ ids: [row.id], url: '' })
}

const handleConfirmOrder = () => {
  if (!ensureSelection()) return
  confirmOrderDialogRef.value?.open(getSelectedIds())
}
const openResultInfoDialog = (data: ResultInfoDataItem[]) => {
  nextTick(() => {
    const isSuccess = data.every((item) => item.status)
    if (!isSuccess) {
      resultInfo.value = data.filter((item) => !item.status)
      resultRefs.value?.showDialog()
    } else {
      refreshCurrentView({ isRefreshTree: true })
    }
  })
}
const handleCancelOrder = () => {
  if (!ensureSelection()) return
  cancelOrderDialogRef.value?.open(getSelectedIds())
}
const handleRefreshProductInfo = async () =>
  executeBatchAction({
    getIds: getSelectedIds,
    api: refreshProductInfoApi,
    confirmText: '确定刷新商品信息吗？',
    successText: '刷新商品信息成功',
  })
const handleTransferOldFlow = async () => {
  try {
    await executeBatchAction({
      getIds: getSelectedIds,
      api: transferOldFlowApi,
      confirmText: '确定转旧流程吗？',
      successText: '转旧流程成功',
      refreshTree: true,
    })
  } catch (e: unknown) {
    ElMessage.error((e as Error)?.message || '转旧流程失败')
  }
}
const handleLogisticsCommand = async (command: string) => {
  if (!ensureSelection()) return
  const ids = getSelectedIds()
  if (command === 'createLogistic') {
    createLogisticDialogRef.value?.showDialog(ids)
    return
  }
  const apiMap: Record<
    string,
    (data: (number | string)[]) => Promise<BaseRespData<unknown>>
  > = {
    getTrackingNumber: getTrackingNumberApi,
    getPrintOrder: getfaceSimplexFileApi,
    cancelLogistic: cancelLogisticsOrderApi,
  }
  const labelMap: Record<string, string> = {
    getTrackingNumber: '获取跟踪号',
    getPrintOrder: '获取打印面单',
    cancelLogistic: '取消物流订单',
  }
  const api = apiMap[command]
  if (!api) return
  try {
    await ElMessageBox.confirm(`确定${labelMap[command]}吗？`, '提示', {
      type: 'warning',
    })
  } catch {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await api(ids)
    if (res.code === 200) {
      if (Array.isArray(res.data)) {
        const isSuccess = res.data.every((item) => item.status)
        if (!isSuccess) {
          resultInfo.value = res.data.filter((item) => !item.status)

          resultRefs.value?.showDialog()
        } else {
          refreshCurrentView()
        }
      } else if (typeof res.data === 'string') {
        window.open(filePath + res.data)
      }
    }
  } catch (e: unknown) {
    resultInfo.value = []
    console.error(e)
  } finally {
    loading.close()
  }
}
const handleSuspend = () => {
  if (!ensureSelection()) return
  suspendDialogRef.value?.open(getSelectedIds())
}
const handleUpdateCustomsInfo = () => {
  if (!ensureSelection()) return
  updateCustomsDialogVisible.value = true
}
const handleArrange = async () => {
  if (!ensureSelection()) return
  const productIdList = getSelectedIds()
    .map((v) => Number(v))
    .filter((n) => Number.isFinite(n)) as number[]
  arrangeDialogRef.value?.open({
    productIdList,
    requestUrl: 'factory/podOrderOperation/arrangeFinish',
    showAutoSwitch: true,
  })
}
const handleSingleConfirmOrder = (row: FactoryOrderNewListData) => {
  confirmOrderDialogRef.value?.open([row.id])
}
const podOrderVisible = ref(false)
const sheetPrinter = ref('')
const handlePrinterChange = (value: string) => {
  sheetPrinter.value = value
  localStorage.setItem('sheetPrinter', JSON.stringify(value))
}
const handleWarehouseIdChange = (value: string) => {
  localStorage.setItem('locaclWarehouseId', JSON.stringify(value))
}
const handleSeedingWall = () => {
  const lodop = getCLodop(null, null)
  if (!lodop) return
  sheetPrinter.value = lodop.GET_PRINTER_NAME(0)
  podOrderVisible.value = true
}
const { getCLodop } = useLodop()

const printOrder = async (
  data: OrderData,
  callback: (status: boolean) => void,
) => {
  await printWithLodop({
    getCLodop: () => getCLodop(null, null),
    printer: sheetPrinter.value,
    data,
    callback,
    baseUrl: filePath,
  })
}
const handleDownloadMaterial = async () => {
  if (!ensureSelection()) return
  const usePodOrderDownloadStatuses = ['PENDING_DELIVERY', 'SUSPEND']
  const usePodOrderDownload = usePodOrderDownloadStatuses.includes(status.value)
  const ids = usePodOrderDownload
    ? selectedRows.value.map((row) => row.id)
    : cardSelectList.value.map((row) => row.podOrderProductId)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = usePodOrderDownload
      ? await downloadMaterialApi(ids as number[])
      : await downloadOperationMaterialApi(ids as number[])
    if (res.message) {
      const a = document.createElement('a')
      a.href = filePath + res.message
      a.download = ''
      a.click()
    }
    ElMessage.success('下载素材成功')
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const handleDtfCommand = async (command: string) => {
  if (!ensureSelection()) return
  const ids = getSelectedIds()
  const [type, widthStr] = command.split('_')
  const templateWidth = Number(widthStr)
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await composingNewPodOrderDesignImages(
      ids as number[],
      type,
      templateWidth,
    )
    if (res.message) {
      const filePathUrl =
        type === 'tiff'
          ? res.message?.startsWith('/temp')
            ? `https://factory.jomalls.com/upload/factory` + res.message
            : `https://ps.jomalls.com/tiff/` + res.message
          : filePath + res.message
      window.open(filePathUrl, '_blank')
    }
    ElMessage.success('DTF排版成功')
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const handlePrintProductionOrder = async () => {
  if (!ensureSelection()) return
  const ids = getSelectedIds()
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await printNewPodOrderProductionOrderApi(ids as number[])
    if (res.message) {
      window.open(filePath + res.message, '_blank')
    }
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const handlePrintPickOrder = async () => {
  await executeBatchAction({
    getIds: getSelectedIds,
    api: printPickOrderApi,
    successText: '打印拣胚单成功',
  })
}
const handlePickComplete = () => {
  if (!ensureSelection()) return
  pickCompleteDialogRef.value?.open(getSelectedIds())
}
const handlePickFail = () => {
  if (!ensureSelection()) return
  pickFailDialogRef.value?.open(getSelectedIds())
}
const handleApplyReplenish = async () => {
  await executeBatchAction({
    getIds: getSelectedIds,
    api: applyReplenishApi,
    confirmText: '确定申请补胚吗?',
    successText: '申请补胚成功',
    refreshTree: true,
  })
}
const handleProductionComplete = async () => {
  await executeBatchAction({
    getIds: getSelectedIds,
    api: completeDeliveryApi,
    confirmText: '确定生产完成吗？',
    refreshTree: true,
    onSuccess: (res) => {
      const data = Array.isArray(res.data) ? (res.data as ResultInfoDataItem[]) : []
      const hasFailed = data.some((item) => !item.status)
      if (hasFailed) {
        resultInfo.value = data.filter((item) => !item.status)
        resultRefs.value?.showDialog()
      }
    },
  })
}
const handleWeightSort = () => {
  weightDialogRef.value?.open()
}
const handleArchiveOrder = async () => {
  await executeBatchAction({
    getIds: getSelectedIds,
    api: archiveOrderApi,
    confirmText: '确定订单归档吗？',
    successText: '订单归档成功',
    refreshTree: true,
  })
}
const handleCancelSuspend = async () => {
  await executeBatchAction({
    getIds: getSelectedIds,
    api: cancelSuspendApi,
    confirmText: '确定取消挂起吗?',
    successText: '取消挂起成功',
    refreshTree: true,
  })
}
const handleSyncAddress = async () => {
  await executeBatchAction({
    getIds: getSelectedIds,
    api: (ids) => syncReceiverAddress(ids as number[]),
    confirmText: '确定同步收货地址吗?',
    successText: '同步收货地址成功',
    refreshTree: true,
  })
}
const handleReplenishComplete = () => {
  if (!ensureSelection()) return
  pickCompleteDialogRef.value?.open(getSelectedIds(), undefined, undefined, {
    title: '补胚完成',
    submitType: 'replenish',
  })
}
const handleReplenishFail = () => {
  if (!ensureSelection()) return
  ElMessage.info('补胚失败功能待集成')
}
const getOperationByNo = (operationNo: string) =>
  getByOperationNoLogApi(operationNo) as Promise<{ data?: unknown }>
const completeOperationById = (ids: number[]) => completeDeliveryApi(ids)
const downloadOperationById = (ids: number[]) =>
  downloadOperationMaterialApi(ids)
const handleFastProductionSuccess = (data: ResultInfoDataItem[]) => {
  const isSuccess = data.every((item) => item.status)
  if (!isSuccess) {
    resultInfo.value = data.filter((item) => !item.status)
    resultRefs.value?.showDialog()
  }
}
const fastClose = () => {
  detailVisible.value = false
  refreshCurrentView({ isRefreshTree: true })
}
const handleQuickProduction = () => {
  detailVisible.value = true
  fastKey.value = 'fastProduction'
  detailData.value = {}
}
const handleSinglePrint = () => {
  if (!ensureSelection()) return
  ElMessage.info('单件打单功能待集成')
}
const handleGetTrackingNumber = async () => {
  await executeBatchAction({
    getIds: getSelectedIds,
    api: (ids) => getTrackingNumberApi(ids as number[]),
    confirmText: '确定获取跟踪号吗？',
    successText: '获取跟踪号成功',
  })
}
const handleStatusPush = () => {
  if (!ensureSelection()) return
  ElMessage.info('状态推送功能待集成')
}
onMounted(() => {
  loadStatusTreeCounts()
  loadAllDictionaries()
  if (status.value === 'PENDING_RECEIVE') {
    getPendingReceiveCounts()
  }
})
</script>

<style scoped lang="scss">
.page {
  display: flex;
}

.order-status {
  width: 180px;

  :deep(.el-tree-node__content) {
    height: 30px;
    line-height: 30px;
  }

  :deep(.el-tree-node__expand-icon) {
    display: none;
  }

  :deep(.status-tree .el-tree-node.is-current > .el-tree-node__content) {
    background-color: #ecf5ff !important;
    color: #409eff !important;

    .tree-node-label,
    .tree-node-count {
      color: #409eff !important;
    }
    .el-icon {
      color: #409eff !important;
    }
  }
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
  width: 100%;
  justify-content: space-between;
}

.tree-node-label {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tree-node-count {
  flex-shrink: 0;
}

.tree-node-expand {
  flex-shrink: 0;
  cursor: pointer;
  display: inline-flex;

  &:hover {
    color: #409eff;
  }
}

.status-subtabs {
  display: flex;
  align-items: center;
  gap: 10px;
  border-top: 1px solid #e5e6eb;
  border-bottom: 1px solid #e5e6eb;
  margin-top: 10px;
}

.status-subtab {
  font-size: 14px;
  line-height: 32px;
  padding: 0 12px;
  cursor: pointer;
  user-select: none;
  color: #333;
  position: relative;

  &.active {
    background: #ecf5ff;
    color: #409eff;
    border-bottom: 2px solid #409eff;
  }
}

.operation-list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.table-content {
  flex: 1;
  margin-top: 10px;
  overflow: hidden;
  :deep(#top) {
    height: 100%;
  }
}

.card-content {
  flex: 1;
  margin-top: 10px;
  overflow: hidden;
}

.header-filter-form {
  width: 100%;
  min-width: 0;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0;
  min-width: 0;

  :deep(.el-form-item) {
    margin-right: 10px;
    margin-bottom: 10px;
  }

  :deep(.el-form-item__content) {
    min-width: 0;
  }
}

.tabs-wrapper {
  height: 100%;

  :deep(.el-tabs__content) {
    height: calc(100% - 40px);
  }

  :deep(.el-tab-pane) {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.sub-table-wrapper,
.log-table-wrapper {
  flex: 1;
  overflow: hidden;
}
</style>
<style lang="scss">
.customize-select-style {
  .el-select-dropdown__list {
    width: 500px;
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
