<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="code"
        :data="statusTree"
        :props="{ children: 'children', label: 'remark' }"
        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.remark }}</span>
              <span
                v-if="data.code !== 'ALL' && (data.count || data.count === 0)"
                class="tree-node-count"
              >
                {{ `(${data.count})` }}
              </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.stockSku"
                placeholder="库存SKU"
                clearable
                style="width: 140px"
              />
            </ElFormItem>

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

            <ElFormItem label="批次号">
              <ElInput
                v-model.trim="searchForm.batchNo"
                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.productType"
                :options="productTypeGroups"
                :multiple="false"
                placeholder="请选择商品类型"
                width="140px"
              />
            </ElFormItem>

            <ElFormItem label="数量">
              <el-radio-group v-model="searchForm.multi">
                <el-radio-button :value="false">单件</el-radio-button>
                <el-radio-button :value="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.blocking"
                      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="search"> 查询 </ElButton>
              <ElButton @click="reset"> 重置 </ElButton>
            </ElFormItem>
          </ElForm>
        </div>
      </div>
      <!-- ====== 操作按钮栏 ====== -->
      <div v-if="!isSpecialLayout" class="operation-list">
        <span v-if="status === 'PENDING_ACCEPT'" class="item">
          <ElButton type="success" @click="handleConfirmOrder"
            >确认接单</ElButton
          >
        </span>
        <span
          v-if="status === 'PENDING_ACCEPT' || status === 'SUSPENDED'"
          class="item"
        >
          <ElButton type="danger" @click="handleCancelOrder">取消订单</ElButton>
        </span>

        <ElDropdown
          v-if="status === 'PENDING_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_LOGISTICS'" class="item">
          <ElButton type="success" @click="handleUpdateCustomsInfo"
            >更新报关信息</ElButton
          >
        </span>
        <span v-if="status === 'PENDING_ACCEPT'" 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 === 'PRODUCING'
          "
          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 === 'PRODUCING'
          "
          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_DISTRIBUTE'" class="item">
          <ElButton type="success" @click="handleSeedingWall"
            >播种墙配货</ElButton
          >
        </span>
        <span v-if="status === 'PENDING_DISTRIBUTE'" class="item">
          <ElButton type="primary" @click="handleSinglePrint"
            >单件打单</ElButton
          >
        </span>
        <span
          v-if="status === 'PRODUCING' || status === 'PENDING_DISTRIBUTE'"
          class="item"
        >
          <ElButton type="warning" @click="handleApplyReplenish"
            >申请补胚</ElButton
          >
        </span>
        <span v-if="status === 'PRODUCING'" class="item">
          <ElButton type="success" @click="handleQuickProduction"
            >快捷生产</ElButton
          >
        </span>
        <span v-if="status === 'PRODUCING'" class="item">
          <ElButton type="success" @click="handleProductionComplete"
            >生产完成</ElButton
          >
        </span>

        <!-- 待发货 -->
        <template v-if="status === 'PENDING_SHIP'">
          <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 === 'SUSPENDED'">
          <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_LOGISTICS',
              'PENDING_SCHEDULE',
              'PENDING_SHIP',
              'DISTRIBUTING',
            ].includes(status)
          "
          class="item"
        >
          <ElButton type="danger" @click="handleSuspend">挂起</ElButton>
        </span>
        <span
          v-if="
            status === 'PENDING_SCHEDULE' ||
            status === 'PENDING_REPLENISH' ||
            status === 'PRODUCING' ||
            status === 'PENDING_SHIP' ||
            status === 'SUSPENDED' ||
            status === 'PENDING_PICK'
          "
          class="item"
        >
          <ElButton type="success" @click="handleDownloadMaterial"
            >下载素材</ElButton
          >
        </span>
        <span
          v-if="
            [
              'PENDING_ACCEPT',
              'PENDING_LOGISTICS',
              'PENDING_SCHEDULE',
              'PENDING_PICK',
              'PENDING_REPLENISH',
              'PRODUCING',
              'PENDING_DISTRIBUTE',
            ].includes(status)
          "
          class="item"
        >
          <ElButton type="primary" @click="handleRefreshProductInfo"
            >刷新商品信息</ElButton
          >
        </span>
      </div>
      <!-- ====== 挂起状态 Tab ====== -->
      <div v-if="status === 'SUSPENDED'" 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 }}
        </div>
      </div>

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

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

      <!-- 到派单、配货中子状态 -->
      <div v-if="isCardLayout" class="card-content">
        <CardLayout
          ref="cardLayoutRef"
          :data="(tableData as { id: number | string; [key: string]: unknown }[])"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize"
          @selection-change="handleCardSelectionChange"
          @page-size-change="handlePageSizeChange"
          @current-page-change="handleCurrentPageChange"
        />
      </div>

      <!-- 表格布局 -->
      <div v-if="isTableLayout" class="table-content">
        <splitDiv v-loading="loading" size="55">
          <template #top>
            <div class="table-list flex-1 overflow-hidden">
              <TableView
                ref="mainTableRef"
                :paginated-data="tableData"
                :columns="mainColumns"
                serial-numberable
                selectionable
                @selection-change="handleMainSelectionChange"
                @row-click="handleMainRowClick"
              />
            </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="handlePageSizeChange"
              @current-change="handleCurrentPageChange"
            />
          </template>
          <template #bottom>
            <el-tabs v-model="activeTab" class="tabs-wrapper">
              <el-tab-pane name="product" label="包含商品">
                <div class="sub-table-wrapper">
                  <TableView
                    :paginated-data="productList"
                    :columns="productColumns"
                    serial-numberable
                  />
                </div>
              </el-tab-pane>
              <el-tab-pane name="log" label="操作日志">
                <div 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="refreshCurrentView"
    />
    <CancelOrderDialog
      ref="cancelOrderDialogRef"
      @success="refreshCurrentView"
    />
    <SuspendDialog ref="suspendDialogRef" @success="refreshCurrentView" />
    <PickCompleteDialog
      ref="pickCompleteDialogRef"
      @success="refreshCurrentView"
    />
    <PickFailDialog ref="pickFailDialogRef" @success="refreshCurrentView" />

    <CreateLogisticDialog
      ref="createLogisticDialogRef"
      @refresh-table="refreshCurrentView"
    />
    <UpdateCustomDeclarationInfoDialog
      v-model="updateCustomsDialogVisible"
      :order-selection="selectedRows"
      @refresh-table="refreshCurrentView"
    />
    <WeightDialog ref="weightDialogRef" @update-list="refreshCurrentView" />

    <ArrangeDialog ref="arrangeDialogRef" @success="refreshCurrentView" />

    <PodMakeOrder
      v-model="podOrderVisible"
      :print-order="printOrder"
      :warehouse-list="warehouseList"
      @set-printer="handlePrinterChange"
      @set-warehouse-id="handleWarehouseIdChange"
      @refresh="refreshCurrentView"
    />
  </div>
</template>

<script setup lang="ts">
import {
  ArrowDown,
  ArrowUp,
  CaretTop,
  CaretBottom,
} from '@element-plus/icons-vue'
import { computed, onMounted, ref, watch } from 'vue'
import {
  ElForm,
  ElFormItem,
  ElMessage,
  ElMessageBox,
  ElTree,
} from 'element-plus'
import splitDiv from '@/components/splitDiv/splitDiv.vue'
import TableView from '@/components/TableView.vue'
import usePageList from '@/utils/hooks/usePageList'
import type { CustomColumn } from '@/types/table'
import type {
  FactoryOrderNewListData,
  LogListData,
  ProductListData,
  SearchForm,
  StatusTreeNode,
} from '@/types/api/factoryOrderNew'
import platformJson from '../../../json/platform.json'
import {
  getFactoryOrderNewDetailApi,
  getFactoryOrderNewListApi,
  getFactoryOrderNewLogApi,
  refreshProductInfoApi,
  transferOldFlowApi,
  cancelSuspendApi,
  archiveOrderApi,
  printPickOrderApi,
  applyReplenishApi,
} from '@/api/factoryOrderNew'
import {
  getListCraftApi,
  getCustomTagListCnApi,
  allErpCodeListApi,
  downloadMaterialApi,
  composingDesignImages,
  printProductionOrderApi,
  updateToWaitShipmentApi,
  syncReceiverAddress,
  getTrackingNumberApi,
  getfaceSimplexFileApi,
  cancelLogisticsOrderApi,
} from '@/api/podCnOrder'
import { getUserMarkList, loadWarehouseListApi } from '@/api/common'
import { getAllCountryApi } from '@/api/logistics'
import { filePath } from '@/api/axios'
import { OrderData } from '@/types/api/podMakeOrder'
import type { WarehouseListData } from '@/types'
import useLodop, { LODOPObject } from '@/utils/hooks/useLodop'
import LogisticsWaySelect from '@/views/logistics/components/LogisticsWaySelect'
import { IAllList } from '@/types/api/podUsOrder'
import { CraftListData } from '@/types/api/podCnOrder'
import ProductTypeFilter from './component/ProductTypeFilter.vue'
import type { ProductTypeGroup } from './component/productTypeFilterTypes'

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 CreateLogisticDialog from '@/views/order/podCN/components/CreateLogisticDialog.vue'
import UpdateCustomDeclarationInfoDialog from '@/views/order/podCN/components/UpdateCustomDeclarationInfoDialog.vue'
import WeightDialog from '@/views/order/podCN/components/WeightDialog.vue'
import PodMakeOrder from '@/views/order/podUs/PodMakeOrder.vue'

const cardLayoutStatuses = [
  'PENDING_SCHEDULE',
  'PENDING_PICK',
  'PENDING_REPLENISH',
  'PRODUCING',
  'PENDING_DISTRIBUTE',
]
const specialLayoutStatuses = ['BATCH_MANAGE', 'WAITING_RESTOCK']
const isCardLayout = computed(() => cardLayoutStatuses.includes(status.value))
const isSpecialLayout = computed(() =>
  specialLayoutStatuses.includes(status.value),
)
const isTableLayout = computed(
  () => !isCardLayout.value && !isSpecialLayout.value,
)
const defaultStatusTree: StatusTreeNode[] = [
  {
    code: 'ALL',
    remark: '全部',
    count: 0,
    children: [
      { code: 'PENDING_ACCEPT', remark: '待接单', count: 0 },
      { code: 'PENDING_LOGISTICS', remark: '待创建物流', count: 0 },
      { code: 'PENDING_SCHEDULE', remark: '待排单', count: 0 },
      { code: 'BATCH_MANAGE', remark: '批次管理', count: 0 },
      { code: 'WAITING_RESTOCK', remark: '等待补货', count: 0 },
      {
        code: 'DISTRIBUTING',
        remark: '配货中',
        count: 0,
        children: [
          { code: 'PENDING_PICK', remark: '待拣胚', count: 0 },
          { code: 'PENDING_REPLENISH', remark: '待补胚', count: 0 },
          { code: 'PRODUCING', remark: '生产中', count: 0 },
          { code: 'PENDING_DISTRIBUTE', remark: '待配货', count: 0 },
        ],
      },
      { code: 'PENDING_SHIP', remark: '待发货', count: 0 },
      { code: 'COMPLETED', remark: '已完成', count: 0 },
      { code: 'SUSPENDED', remark: '挂起', count: 0 },
      { code: 'CANCELLED', remark: '已取消', count: 0 },
      { code: 'ARCHIVED', remark: '已归档', count: 0 },
    ],
  },
]

const statusTree = ref<StatusTreeNode[]>(defaultStatusTree)
const status = ref<string>('PENDING_ACCEPT')
const pendingAcceptSubTab = ref<'PENDING_ACCEPT' | 'ACCEPT_FAIL_OUT_OF_STOCK'>(
  'PENDING_ACCEPT',
)
const suspendedTabs = [
  { label: '客户拦截', value: 'CUSTOMER_INTERCEPT' },
  { label: '地址异常', value: 'ADDRESS_EXCEPTION' },
  { label: '其他', value: 'OTHER' },
]
const suspendedSubTab = ref('CUSTOMER_INTERCEPT')

const treeRef = ref<InstanceType<typeof ElTree>>()
const searchForm = ref<SearchForm>({})
const dateRange = ref<string[]>([])
const craftCode = ref<string>('')
const searchVisible = ref(false)
const searchFormPopoverRef = ref()

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

interface LogisticsCodeItem {
  code: string
  basicsName: string
  apiData: unknown
}
const allCodelist = ref<LogisticsCodeItem[]>([])

const sourceList = [
  { name: 'erp推送', id: 'jomall-erp' },
  { name: '第三方推送', id: 'third-party' },
]
const sizes = ['FS', 'XS', 'S', 'M', 'L', 'XL', 'XXL', '3XL', '4XL', '5XL']

const productTypeGroups = ref<ProductTypeGroup[]>([
  {
    label: '普品',
    value: 'NORMAL_ALL',
    children: [{ label: '普品', value: 'NORMAL' }],
  },
  {
    label: '胚衣',
    value: 'GREIGE_ALL',
    children: [{ label: '胚衣', value: 'GREIGE' }],
  },
  {
    label: 'POD商品',
    value: 'POD_ALL',
    children: [
      { label: '单面', value: 'POD_SINGLE' },
      { label: '多面', value: 'POD_MULTI' },
    ],
  },
  {
    label: '一件定制局部印',
    value: 'CUSTOM_PART_ALL',
    children: [
      { label: '单面', value: 'CUSTOM_PART_SINGLE' },
      { label: '多面', value: 'CUSTOM_PART_MULTI' },
    ],
  },
])

const changeReplaceShipment = () => {
  searchForm.value.shipmentType = ''
}

// ========== 数据加载 ==========
const getUserMark = async () => {
  try {
    const res = await getUserMarkList()
    userMarkList.value = res.data
  } catch (_e) {
    /* empty */
  }
}

const getReceiverCountryList = async () => {
  try {
    const res = await getAllCountryApi()
    if (res.code !== 200) return
    receiverCountryList.value = res.data
  } catch (_e) {
    /* empty */
  }
}

const getCustomTagList = async () => {
  try {
    const res = await getCustomTagListCnApi()
    if (res.code !== 200) return
    customTagList.value = res.data
  } catch (_e) {
    /* empty */
  }
}

const getLogisticsCompanyAllCodelist = async () => {
  try {
    const res = await allErpCodeListApi()
    if (res.code !== 200) return
    allCodelist.value = res.data
  } catch (_e) {
    /* empty */
  }
}

const processTypeMap: Record<string, string> = {
  TH: '烫画',
  ZP: '直喷',
  CX: '刺绣',
  DK: '雕刻',
  BP: '白胚',
  QT: '其他',
}
const craftList = ref<IAllList[]>([])
const loadCraftList = async () => {
  try {
    const res = await getListCraftApi()
    if (res.code !== 200) return
    const data: CraftListData[] = res.data
    craftList.value = data.map((item) => ({
      id: item.craftCode,
      name: item.craftName,
      warehouseName: processTypeMap[item.craftType] ?? '其他',
    }))
  } catch (_e) {
    /* empty */
  }
}

const pickerOptions = {
  shortcuts: [
    {
      text: '今日',
      value: () => {
        const start = new Date()
        start.setHours(0, 0, 0, 0)
        const end = new Date()
        end.setHours(23, 59, 59, 999)
        return [start, end]
      },
    },
    {
      text: '最近7天',
      value: () => {
        const end = new Date()
        end.setHours(23, 59, 59, 999)
        const start = new Date()
        start.setDate(start.getDate() - 6)
        start.setHours(0, 0, 0, 0)
        return [start, end]
      },
    },
    {
      text: '最近30天',
      value: () => {
        const end = new Date()
        end.setHours(23, 59, 59, 999)
        const start = new Date()
        start.setDate(start.getDate() - 29)
        start.setHours(0, 0, 0, 0)
        return [start, end]
      },
    },
  ],
}

// ========== 表格数据 ==========
const activeTab = ref<'product' | 'log'>('product')
const productList = ref<ProductListData[]>([])
const currentRow = ref<FactoryOrderNewListData | null>(null)
const selectedRowIds = ref<(number | string)[]>([])
const selectedRows = ref<FactoryOrderNewListData[]>([])
const cardSelectedIds = ref<(number | string)[]>([])
const logList = ref<LogListData[]>([])
const mainTableRef = ref()

const mainColumns: CustomColumn<FactoryOrderNewListData>[] = [
  { key: 'orderNumber', prop: 'orderNumber', label: '订单编号', minWidth: 160 },
  {
    key: 'customerOrderNumber',
    prop: 'customerOrderNumber',
    label: '客户单号',
    minWidth: 160,
  },
  {
    key: 'shopOrderNumber',
    prop: 'shopOrderNumber',
    label: '店铺单号',
    minWidth: 160,
  },
  { key: 'statusName', prop: 'statusName', label: '订单状态', minWidth: 120 },
  {
    key: 'customerTags',
    prop: 'customerTags',
    label: '客户标签',
    minWidth: 160,
  },
  {
    key: 'logisticsWayName',
    prop: 'logisticsWayName',
    label: '物流方式',
    minWidth: 140,
  },
  {
    key: 'logisticsSourceNo',
    prop: 'logisticsSourceNo',
    label: '物流跟踪号',
    minWidth: 160,
  },
  { key: 'totalWeight', prop: 'totalWeight', label: '总克重', minWidth: 120 },
  {
    key: 'totalProductNum',
    prop: 'totalProductNum',
    label: '商品总数量',
    minWidth: 120,
  },
  { key: 'receiverName', prop: 'receiverName', label: '收货人', minWidth: 120 },
  {
    key: 'receiverPhone',
    prop: 'receiverPhone',
    label: '收货人电话',
    minWidth: 140,
  },
  {
    key: 'receiverCode',
    prop: 'receiverCode',
    label: '收货人邮编',
    minWidth: 140,
  },
  {
    key: 'receiverAddress',
    prop: 'receiverAddress',
    label: '收货地址',
    minWidth: 220,
    showOverflowTooltip: true,
  },
  {
    key: 'createTime',
    prop: 'createTime',
    label: '创建时间',
    minWidth: 180,
    sortable: true,
  },
  {
    key: 'acceptTime',
    prop: 'acceptTime',
    label: '接单时间',
    sortable: true,
    minWidth: 180,
  },
  {
    key: 'finishTime',
    prop: 'finishTime',
    label: '完成时间',
    sortable: true,
    minWidth: 180,
  },
  {
    key: 'operation',
    prop: 'operation',
    label: '操作',
    minWidth: 120,
    slot: 'operation',
    fixed: 'right',
  },
]

const productColumns: CustomColumn<ProductListData>[] = [
  {
    key: 'productImage',
    prop: 'productImage',
    label: '商品图片',
    minWidth: 90,
    align: 'center',
    slot: 'productImage',
  },
  {
    key: 'productName',
    prop: 'productName',
    label: '商品名称',
    minWidth: 200,
    showOverflowTooltip: true,
  },
  { key: 'variantSku', prop: 'variantSku', label: '变体SKU', minWidth: 160 },
  { key: 'stockSku', prop: 'stockSku', label: '库存SKU', minWidth: 160 },
  { key: 'craftCode', prop: 'craftCode', label: '工艺', minWidth: 100 },
  { key: 'styleNo', prop: 'styleNo', label: '款号', minWidth: 100 },
  { key: 'price', prop: 'price', label: '价格', minWidth: 100 },
  { key: 'quantity', prop: 'quantity', label: '数量', minWidth: 100 },
  { key: 'weight', prop: 'weight', label: '克重', minWidth: 100 },
  {
    key: 'availableQuantity',
    prop: 'availableQuantity',
    label: '可用数量',
    minWidth: 100,
  },
  {
    key: 'stockQuantity',
    prop: 'stockQuantity',
    label: '库存数量',
    minWidth: 100,
  },
  {
    key: 'occupiedQuantity',
    prop: 'occupiedQuantity',
    label: '占用数量',
    minWidth: 100,
  },
  {
    key: 'customsNameEnglish',
    prop: 'customsNameEnglish',
    label: '英文报关名称',
    width: 160,
  },
  {
    key: 'customsNameChinese',
    prop: 'customsNameChinese',
    label: '中文报关名称',
    width: 160,
  },
  {
    key: 'customsWeight',
    prop: 'customsWeight',
    label: '申报重量(g)',
    width: 100,
  },
  {
    key: 'customsValue',
    prop: 'customsValue',
    label: '申报价值($)',
    width: 100,
  },
  { key: 'remark', prop: 'remark', label: '备注', width: 160 },
]

// ========== 分页数据 ==========
const {
  loading,
  currentPage,
  pageSize,
  total,
  data: tableData,
  onCurrentPageChange,
  onPageSizeChange,
  refresh,
} = usePageList<FactoryOrderNewListData>({
  query: (page, size) =>
    getFactoryOrderNewListApi(
      {
        ...searchForm.value,
        craftCode: craftCode.value,
        startTime: dateRange.value?.[0] || null,
        endTime: dateRange.value?.[1] || null,
      },
      page,
      size,
      getStatusCodeForQuery(),
    ).then((res) => res.data),
})

const getStatusCodeForQuery = () => {
  if (status.value === 'ALL') return undefined
  if (status.value === 'PENDING_ACCEPT') return pendingAcceptSubTab.value
  if (status.value === 'SUSPENDED') return `SUSPENDED_${suspendedSubTab.value}`
  return status.value
}

const search = () => {
  onCurrentPageChange(1)
  refresh()
}

const reset = () => {
  searchForm.value = {}
  dateRange.value = []
  craftCode.value = ''
  search()
}

// ========== 组件 Ref ==========
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 cardLayoutRef = ref<InstanceType<typeof CardLayout>>()
const batchManageRef = ref<InstanceType<typeof BatchManageTable>>()
const waitingRestockRef = ref<InstanceType<typeof WaitingRestockTable>>()
const arrangeDialogRef = ref<InstanceType<typeof ArrangeDialog>>()
const createLogisticDialogRef = ref()
const updateCustomsDialogVisible = ref(false)
const weightDialogRef = ref()

// ========== 通用工具 ==========
const getSelectedIds = (): (number | string)[] => {
  if (isCardLayout.value) return cardSelectedIds.value
  return selectedRowIds.value
}

const ensureSelection = (msg = '请先选择订单'): boolean => {
  const ids = getSelectedIds()
  if (!ids.length) {
    ElMessage.warning(msg)
    return false
  }
  return true
}

const refreshCurrentView = () => {
  if (isSpecialLayout.value) {
    if (status.value === 'BATCH_MANAGE') batchManageRef.value?.refresh()
    if (status.value === 'WAITING_RESTOCK') waitingRestockRef.value?.refresh()
    return
  }
  refresh()
  if (isCardLayout.value) cardLayoutRef.value?.clearSelection()
}

// ========== 状态切换 ==========
const handleStatusNodeClick = (node: StatusTreeNode) => {
  if (status.value === node.code) return
  status.value = node.code
  if (node.code !== 'PENDING_ACCEPT') {
    pendingAcceptSubTab.value = 'PENDING_ACCEPT'
  }
  if (node.code !== 'SUSPENDED') {
    suspendedSubTab.value = 'CUSTOMER_INTERCEPT'
  }
  selectedRowIds.value = []
  selectedRows.value = []
  cardSelectedIds.value = []
  currentRow.value = null
  productList.value = []
  logList.value = []
  // if (!isSpecialLayout.value) {
  //   onCurrentPageChange(1)
  //   refresh()
  // }
}

const toggleExpand = (node: { expanded?: boolean }) => {
  node.expanded = !node.expanded
}

const handlePageSizeChange = (size: number) => {
  onPageSizeChange(size)
}

const handleCurrentPageChange = (page: number) => {
  onCurrentPageChange(page)
}

const handleMainSelectionChange = (rows: FactoryOrderNewListData[]) => {
  selectedRowIds.value = rows.map((row) => row.id)
  selectedRows.value = rows
}

const handleCardSelectionChange = (items: { id: number | string }[]) => {
  cardSelectedIds.value = items.map((i) => i.id)
}

const loadSubTables = async () => {
  if (!currentRow.value) {
    productList.value = []
    logList.value = []
    return
  }
  try {
    const [productRes, logRes] = await Promise.all([
      getFactoryOrderNewDetailApi(currentRow.value.id),
      getFactoryOrderNewLogApi(currentRow.value.id),
    ])
    productList.value = productRes.data || []
    logList.value = logRes.data || []
  } catch (e) {
    console.error(e)
  }
}

const handleMainRowClick = (row: FactoryOrderNewListData) => {
  currentRow.value = row
  loadSubTables()
}

// ========== 待接单 操作 ==========
const handleConfirmOrder = () => {
  if (!ensureSelection()) return
  confirmOrderDialogRef.value?.open(getSelectedIds())
}

const handleCancelOrder = () => {
  // if (!ensureSelection()) return
  cancelOrderDialogRef.value?.open(getSelectedIds())
}

const handleRefreshProductInfo = async () => {
  if (!ensureSelection()) return
  try {
    await refreshProductInfoApi(getSelectedIds())
    ElMessage.success('刷新商品信息成功')
    refresh()
  } catch (e: unknown) {
    ElMessage.error((e as Error)?.message || '刷新商品信息失败')
  }
}

const handleTransferOldFlow = async () => {
  if (!ensureSelection()) return
  await ElMessageBox.confirm('确定转旧流程吗？', '提示', { type: 'warning' })
  try {
    await transferOldFlowApi(getSelectedIds())
    ElMessage.success('转旧流程成功')
    refresh()
  } 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<{ code: number; message?: string }>
  > = {
    getTrackingNumber: getTrackingNumberApi,
    getPrintOrder: getfaceSimplexFileApi,
    cancelLogistic: cancelLogisticsOrderApi,
  }
  const labelMap: Record<string, string> = {
    getTrackingNumber: '获取跟踪号',
    getPrintOrder: '获取打印面单',
    cancelLogistic: '取消物流订单',
  }
  const api = apiMap[command]
  if (!api) return
  await ElMessageBox.confirm(`确定${labelMap[command]}吗？`, '提示', {
    type: 'warning',
  })
  try {
    const res = await api(ids)
    if (command === 'getPrintOrder' && res.message) {
      window.open(filePath + res.message, '_blank')
    }
    ElMessage.success(`${labelMap[command]}成功`)
    refresh()
  } catch (e: unknown) {
    ElMessage.error((e as Error)?.message || `${labelMap[command]}失败`)
  }
}

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

const podOrderVisible = ref(false)
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 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 { getCLodop } = useLodop()
const handleSeedingWall = () => {
  const lodop = getCLodop(null, null)
  if (!lodop) return
  sheetPrinter.value = lodop.GET_PRINTER_NAME(0)
  podOrderVisible.value = true
}

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)
  if (!printerIndex) {
    ElMessage.error('打印机设置失败')
    callback(false)
    return
  }
  if (data.filePath) {
    const strURL = filePath + data.filePath
    lodop.ADD_PRINT_PDF(
      0,
      0,
      '100%',
      '100%',
      /(https):\/\/([^/]+)/i.test(strURL) ? downloadPDF(strURL) : strURL,
    )
  } else {
    lodop.SEND_PRINT_RAWDATA(data.fileData || '')
  }
  if (lodop.CVERSION) {
    const startTime = Date.now()
    const jobCode = await lodopCall((lodop) => {
      lodop.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
      return lodop.PRINT()
    })
    // eslint-disable-next-line no-constant-condition
    while (true) {
      const ok = await lodopCall((lodop) =>
        lodop.GET_VALUE('PRINT_STATUS_OK', jobCode),
      )
      if (ok == '1') {
        callback(true)
        return
      }
      const exist = await lodopCall((lodop) =>
        lodop.GET_VALUE('PRINT_STATUS_EXIST', jobCode),
      )
      if (exist == '0') {
        callback(true)
        return
      }
      await new Promise((r) => setTimeout(r, 500))
      if (Date.now() - startTime >= 30000) {
        ElMessage.error('打印超时(30秒)')
        callback(false)
        return
      }
    }
  } else {
    lodop.PRINT()
    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) => {
      const cb = _lodopCallback[id]
      if (!cb) return
      delete _lodopCallback[id]
      cb(value)
    }
  }

  return new Promise((resolve) => {
    if (!_lodop) return
    const id = fn(_lodop)
    _lodopCallback[id] = resolve
  })
}

const downloadPDF = (url: string) => {
  if (!/^https?:/i.test(url)) return url
  const xhr = new XMLHttpRequest()
  let arrybuffer = false
  xhr.open('GET', url, false)
  if (xhr.overrideMimeType) {
    try {
      xhr.responseType = 'arraybuffer'
      arrybuffer = true
    } catch {
      xhr.overrideMimeType('text/plain; charset=x-user-defined')
    }
  }
  xhr.send(null)
  const data = (xhr.response || (xhr as unknown as { responseBody?: unknown }).responseBody) as
    | ArrayBuffer
    | string
  let dataArray: Uint8Array
  if (arrybuffer) {
    dataArray = new Uint8Array(data as ArrayBuffer)
  } else {
    const text = data as string
    dataArray = new Uint8Array(text.length)
    for (let i = 0; i < dataArray.length; i++) dataArray[i] = text.charCodeAt(i)
  }
  const digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  let strData = ''
  for (let i = 0, ii = dataArray.length; i < ii; i += 3) {
    const b1 = dataArray[i] & 0xff
    const b2 = dataArray[i + 1] & 0xff
    const b3 = dataArray[i + 2] & 0xff
    const d1 = b1 >> 2
    const 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.charAt(d1) + digits.charAt(d2) + digits.charAt(d3) + digits.charAt(d4)
  }
  return 'data:application/pdf;base64,' + strData
}

const handleDownloadMaterial = async () => {
  if (!ensureSelection()) return
  const ids = getSelectedIds()
  try {
    const res = await downloadMaterialApi(ids as number[])
    if (res.message) {
      const a = document.createElement('a')
      a.href = filePath + res.message
      a.download = ''
      a.click()
    }
    ElMessage.success('下载素材成功')
  } catch (e: unknown) {
    ElMessage.error((e as Error)?.message || '下载素材失败')
  }
}

// ========== 待拣胚/待补胚 操作 ==========
const handleDtfCommand = async (command: string) => {
  if (!ensureSelection()) return
  const ids = getSelectedIds()
  const [type, widthStr] = command.split('_')
  const templateWidth = Number(widthStr)
  const url =
    status.value === 'PENDING_REPLENISH'
      ? 'factory/podJomallOrderCn/replenishmentComposingDesignImages'
      : 'factory/podJomallOrderProductCn/composingDesignImages'
  try {
    const res = await composingDesignImages(
      url,
      ids as number[],
      type,
      templateWidth,
    )
    if (type === 'tiff' && res.message) {
      window.open(filePath + res.message, '_blank')
    }
    ElMessage.success('DTF排版成功')
  } catch (e: unknown) {
    ElMessage.error((e as Error)?.message || 'DTF排版失败')
  }
}

const handlePrintProductionOrder = async () => {
  if (!ensureSelection()) return
  const ids = getSelectedIds()
  const url =
    status.value === 'PENDING_REPLENISH'
      ? 'factory/podJomallOrderProductCn/replenishmentPrintProducePdf'
      : 'factory/podJomallOrderProductCn/printProducePdf'
  try {
    const res = await printProductionOrderApi(url, ids as number[])
    if (res.message) {
      window.open(filePath + res.message, '_blank')
    }
  } catch (e: unknown) {
    ElMessage.error((e as Error)?.message || '打印生产单失败')
  }
}

const handlePrintPickOrder = async () => {
  if (!ensureSelection()) return
  const ids = getSelectedIds()
  try {
    await printPickOrderApi(ids)
    ElMessage.success('打印拣胚单成功')
    refreshCurrentView()
  } catch (e: unknown) {
    ElMessageBox.alert(
      (e as Error)?.message || '打印拣胚单失败',
      '打印拣胚单失败',
      { type: 'error' },
    )
  }
}

const handlePickComplete = () => {
  if (!ensureSelection()) return
  pickCompleteDialogRef.value?.open(getSelectedIds())
}

const handlePickFail = () => {
  // if (!ensureSelection()) return
  pickFailDialogRef.value?.open(getSelectedIds())
}

const handleApplyReplenish = async () => {
  if (!ensureSelection()) return
  await ElMessageBox.confirm('确定申请补胚吗?', '提示', { type: 'warning' })
  try {
    await applyReplenishApi(getSelectedIds())
    ElMessage.success('申请补胚成功')
    refreshCurrentView()
  } catch (e: unknown) {
    ElMessageBox.alert(
      (e as Error)?.message || '申请补胚失败',
      '申请补胚失败',
      { type: 'error' },
    )
  }
}

const handleProductionComplete = async () => {
  if (!ensureSelection()) return
  await ElMessageBox.confirm('确定生产完成吗？', '提示', { type: 'warning' })
  try {
    const params = getSelectedIds().map((id) => ({
      id,
      podJomallOrderCnId: id,
      factorySubOrderNumber: '',
      version: 0,
    }))
    await updateToWaitShipmentApi({ cnUpdateParams: params })
    ElMessage.success('生产完成')
    refreshCurrentView()
  } catch (e: unknown) {
    ElMessage.error((e as Error)?.message || '生产完成失败')
  }
}

const handleWeightSort = () => {
  weightDialogRef.value?.open()
}

const handleArchiveOrder = async () => {
  if (!ensureSelection()) return
  await ElMessageBox.confirm('确定订单归档吗？', '提示', { type: 'warning' })
  try {
    await archiveOrderApi(getSelectedIds())
    ElMessage.success('订单归档成功')
    refresh()
  } catch (e: unknown) {
    ElMessageBox.alert(
      (e as Error)?.message || '订单归档失败',
      '订单归档失败',
      { type: 'error' },
    )
  }
}

const handleCancelSuspend = async () => {
  if (!ensureSelection()) return
  try {
    await cancelSuspendApi(getSelectedIds())
    ElMessage.success('取消挂起成功')
    refresh()
  } catch (e: unknown) {
    ElMessage.error((e as Error)?.message || '取消挂起失败')
  }
}

const handleSyncAddress = async () => {
  if (!ensureSelection()) return
  await ElMessageBox.confirm('确定同步收货地址吗?', '提示', { type: 'warning' })
  try {
    await syncReceiverAddress(getSelectedIds() as number[])
    ElMessage.success('同步收货地址成功')
    refresh()
  } catch (e: unknown) {
    ElMessage.error((e as Error)?.message || '同步收货地址失败')
  }
}

const handleReplenishComplete = () => {
  if (!ensureSelection()) return
  ElMessage.info('补胚完成功能待集成')
}

const handleReplenishFail = () => {
  if (!ensureSelection()) return
  ElMessage.info('补胚失败功能待集成')
}

const handleQuickProduction = () => {
  if (!ensureSelection()) return
  ElMessage.info('快捷生产功能待集成')
}

const handleSinglePrint = () => {
  if (!ensureSelection()) return
  ElMessage.info('单件打单功能待集成')
}

const handleGetTrackingNumber = async () => {
  if (!ensureSelection()) return
  await ElMessageBox.confirm('确定获取跟踪号吗？', '提示', { type: 'warning' })
  try {
    await getTrackingNumberApi(getSelectedIds() as number[])
    ElMessage.success('获取跟踪号成功')
    refreshCurrentView()
  } catch (e: unknown) {
    ElMessage.error((e as Error)?.message || '获取跟踪号失败')
  }
}

const handleStatusPush = () => {
  if (!ensureSelection()) return
  ElMessage.info('状态推送功能待集成')
}
watch(
  () => pendingAcceptSubTab.value,
  () => {
    if (status.value === 'PENDING_ACCEPT') {
      onCurrentPageChange(1)
      refresh()
    }
  },
)

watch(
  () => suspendedSubTab.value,
  () => {
    if (status.value === 'SUSPENDED') {
      onCurrentPageChange(1)
      refresh()
    }
  },
)

watch(
  () => activeTab.value,
  () => {
    if (currentRow.value) {
      loadSubTables()
    }
  },
)
onMounted(() => {
  if (treeRef.value) {
    treeRef.value.setCurrentKey(status.value, true)
  }
  loadCraftList()
  getUserMark()
  getCustomTagList()
  getLogisticsCompanyAllCodelist()
  getReceiverCountryList()
  loadWarehouseList()
})
</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>
