<script setup lang="ts">
import { OrderCnReceiverAddress } from '@/api/podUsOrder.ts'
import { WarningFilled } from '@element-plus/icons-vue'

defineOptions({
  name: 'OrderTracking',
})
import LogisticsWaySelect from '../../logistics/components/LogisticsWaySelect.tsx'
import {
  factoryWarehouseInfo,
  warehouseInfo,
  warehouseInfoGetAll,
} from '@/api/warehouse.ts'
import {
  getListCraftApi,
  getOrderList,
  getOperationLogApi,
  getOrderTabData,
  getfaceSimplexFileApi,
  exportPodCnInfo,
} from '@/api/podCnOrder'
import {
  SearchForm,
  CraftListData,
  ProductList,
  PodCnOrderListData,
  LogListData,
  Tab,
  ExportParams,
} from '@/types/api/podCnOrder'
import { IAllList } from '@/types/api/podUsOrder'
import platformJson from '../../../json/platform.json'
import dayjs from 'dayjs'
import { getUserMarkList } from '@/api/common'
import { CaretBottom, CaretTop } from '@element-plus/icons-vue'
import SplitDiv from '@/components/splitDiv/splitDiv.vue'
import { BaseRespData } from '@/types/api'
import { showConfirm } from '@/utils/ui'
import { isArray, isString } from '@/utils/validate'
import ResultInfo from '../podUs/components/ResultInfo.vue'
import { filePath } from '@/api/axios'
import { convertToChinaTime } from '@/utils/index'
import { useEnterKeyTrigger } from '@/utils/hooks/useEnterKeyTrigger.ts'

import { useValue } from '@/utils/hooks/useValue'
import { ElFormItem } from 'element-plus'
const tabValue = ref('1')
const [searchForm, resetSearchForm] = useValue<SearchForm>({
  timeType: 1,
  shopNumber: '',
  shipmentType: '',
  userMark: '',
  processNumber: '',
  baseSku: '',
  factoryOrderNumber: '',
  sku: '',
  factorySubOrderNumber: '',
  status: '',
  // customizedQuantity: '',
  multi: null,
  startTime: null,
  endTime: null,
  exceptionHandling: undefined,
  platform: '',
  // productionClient: '',
  warehouseId: '',
  thirdSkuCode: '',
  supplierProductNo: '',
  batchArrangeNumber: '',
  craftCode: [],
  thirdStockSku: '',
})
const tableColumns = computed(() => {
  return [
    {
      label: '订单号',
      prop: 'factoryOrderNumber',
      width: 160,
      align: 'center',
      slot: 'factoryOrderNumber',
    },
    {
      label: '第三方订单号',
      prop: 'thirdOrderNumber',
      width: 240,
      align: 'center',
    },
    {
      label: '店铺单号',
      prop: 'shopNumber',
      width: 160,
      align: 'center',
    },
    {
      label: '订单状态',
      prop: 'status',
      slot: 'status',
      width: 160,
      align: 'center',
    },
    {
      label: '是否代发',
      slot: 'replaceShipment',
      prop: 'replaceShipment',
      width: 120,
      align: 'center',
    },
    {
      label: '物流类型',
      slot: 'shipmentType',
      prop: 'shipmentType',
      width: 120,
      align: 'center',
    },
    {
      label: '物流跟踪号',
      prop: 'trackingNumber',
      width: 160,
      align: 'center',
    },

    {
      label: '总克重(g)',
      prop: 'weight',
      width: 100,
      align: 'center',
    },
    {
      label: '生产端',
      prop: 'productionClient',
      width: 100,
      align: 'center',
    },
    {
      label: '发货仓库',
      prop: 'warehouseName',
      width: 120,
      align: 'center',
    },
    {
      label: '物流方式',
      prop: 'logisticsWayName',
      width: 120,
      align: 'center',
    },
    {
      label: '收货人',
      prop: 'receiverName',
      width: 100,
      align: 'center',
    },
    {
      label: '收货人电话',
      prop: 'receiverPhone',
      width: 140,
      align: 'center',
    },
    {
      label: '收货人邮编',
      prop: 'receiverPostCode',
      width: 140,
      align: 'center',
    },
    {
      label: '收货地址',
      prop: 'lanshouAddress',
      width: 500,
      align: 'center',
    },
  ]
})
const goodsColumns = computed(() => {
  return [
    {
      label: '商品图片',
      prop: 'productImg',
      slot: 'productImg',
      width: 90,
    },
    {
      label: '商品名称',
      prop: 'productName',
      width: 170,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      label: '数量',
      prop: 'num',
      width: 100,
      align: 'center',
    },
    {
      label: '状态',
      prop: 'subStatus',
      width: 130,
      align: 'center',
      showOverflowTooltip: true,
    },

    {
      label: '生产单号',
      prop: 'factorySubOrderNumber',
      width: 170,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      label: '变体sku',
      prop: 'variantSku',
      width: 170,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      label: '第三方生产单号',
      prop: 'thirdSubOrderNumber',
      width: 170,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      label: '库存SKU',
      prop: 'thirdSkuCode',
      width: 170,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      label: '工厂',
      prop: 'factoryCode',
      width: 100,
      align: 'center',
    },
    {
      label: '货号',
      prop: 'thirdStockSku',
      width: 130,
      align: 'center',
    },
    {
      label: '款号',
      prop: 'supplierProductNo',
      width: 162,
      align: 'center',
    },
    {
      label: '工艺',
      prop: 'craftName',
      width: 140,
      align: 'center',
    },
    {
      label: '价格($)',
      prop: 'productPrice',
      align: 'center',
    },
    {
      label: '模板金额($)',
      prop: 'templatePrice',
      width: 120,
      align: 'center',
    },
    {
      label: '工艺金额($)',
      prop: 'craftPrice',
      width: 120,
      align: 'center',
    },
    {
      label: '付款金额($)',
      prop: 'payAmount',
      width: 120,
      align: 'center',
    },

    {
      label: '未生产数量',
      prop: 'notPassNum',
      width: 100,
      align: 'center',
    },
    {
      label: '补胚数量',
      prop: 'replenishmentSumNum',
      width: 100,
      align: 'center',
    },
    {
      label: '克重(g)',
      prop: 'weight',
      width: 100,
      align: 'center',
    },
    {
      label: '备注',
      prop: 'remark',
      width: 100,
      align: 'center',
    },
  ]
})
const productMarkList = [
  {
    label: '普通商品',
    value: 'normal',
  },
  {
    label: 'pod商品',
    value: 'pod',
  },
  {
    label: '一件定制局部印',
    value: 'custom_part',
  },
  {
    label: '一件定制满印',
    value: 'custom_full',
  },
]
const tableData = ref<PodCnOrderListData[]>([])
const goodsData = ref<ProductList[]>([])
const searchVisible = ref(false)
const goodsLoading = ref(false)
const logList = ref<LogListData[]>([])
const selection = ref<PodCnOrderListData[]>([])

const warehouseList = ref<warehouseInfo[]>([])
const timeRange = ref<string[]>([])
const pickerOptions = {
  shortcuts: [
    {
      text: '今日',
      value: () => getDateRange(0),
    },
    {
      text: '昨天',
      value: () => getDateRange(1),
    },
    {
      text: '最近7天',
      value: () => getDateRange(6),
    },
    {
      text: '最近14天',
      value: () => getDateRange(13),
    },
    {
      text: '最近30天',
      value: () => getDateRange(29),
    },
    {
      text: '本周',
      value: () => getWeekRange(0),
    },
    {
      text: '上周',
      value: () => getWeekRange(1),
    },
    {
      text: '本月',
      value: () => getMonthRange(0),
    },
    {
      text: '上月',
      value: () => getMonthRange(1),
    },
    {
      text: '历史',
      value: () => {
        const end = dayjs().endOf('day').toDate()
        const start = dayjs('2000-01-01').startOf('day').toDate()
        return [start, end]
      },
    },
    {
      text: '转换中国时间',
      value: () => {
        console.log(3469, timeRange.value)
        if (timeRange.value?.length) {
          const end = timeRange.value[1] ?? ''
          const start = timeRange.value[0] ?? ''
          return [convertToChinaTime(start), convertToChinaTime(end)]
        } else {
          return getDateRange(0)
        }
      },
    },
  ],
}

const pagination = ref<factoryWarehouseInfo>({
  pageSize: 50,
  currentPage: 1,
  total: 0,
})
const search = () => {
  goodsData.value = []
  logList.value = []
  getOrderListFn()
  if (tabValue.value === '2') {
    zoneType.value = 'Asia/Shanghai'
    operationLog()
  }
}

const getDateRange = (days = 0, type: 'past' | 'future' = 'past') => {
  const end = dayjs()
  const start =
    type === 'past' ? end.subtract(days, 'day') : end.add(days, 'day')
  return [start.startOf('day').toDate(), end.endOf('day').toDate()]
}
const getMonthRange = (months = 0, type: 'past' | 'future' = 'past') => {
  const now = dayjs()
  const start =
    type === 'past' ? now.subtract(months, 'month') : now.add(months, 'month')
  return [start.startOf('month').toDate(), start.endOf('month').toDate()]
}
const getWeekRange = (weeks = 0, type: 'past' | 'future' = 'past') => {
  const now = dayjs()
  const start =
    type === 'past' ? now.subtract(weeks, 'week') : now.add(weeks, 'week')
  return [start.startOf('week').toDate(), start.endOf('week').toDate()]
}
const exportLoading = ref(false)
const exportVisible = ref(false)
const exportForm = ref({
  resource: '',
})

const exportData = () => {
  exportVisible.value = true
}
const submitExportForm = async () => {
  if (exportForm.value.resource === '') {
    return ElMessage.error('请选择导出类型')
  }
  exportLoading.value = true
  const resourceType = Number(exportForm.value.resource)
  const params: ExportParams = {
    exportAll: false,
    idList: [],
  }
  // 使用函数封装映射逻辑
  const mapIds = (items: PodCnOrderListData[]) =>
    items.map((el) => Number(el.id))
  switch (resourceType) {
    case 0:
      params.idList = mapIds(tableData.value as PodCnOrderListData[])
      break
    case 1:
      params.idList = mapIds(selection.value)
      break
    case 2:
      params.exportAll = true
      params.idList = undefined
      break
    default:
      console.error('未知的资源类型:', resourceType)
  }
  try {
    await exportPodCnInfo({
      ...params,
      ...(resourceType === 2
        ? {
            ...searchForm.value,
            startTime: timeRange.value?.[0] || null,
            endTime: timeRange.value?.[1] || null,
          }
        : {}),
    })
    ElMessage.success('请求成功，请稍后到右上角[我的下载]中查看')
    exportVisible.value = false
    exportLoading.value = false
  } catch (e) {
    exportVisible.value = false
    exportLoading.value = false
  }
}
const handleSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize
  getOrderListFn()
}
const handleCurrentChange = (currentPage: number) => {
  pagination.value.currentPage = currentPage
  getOrderListFn()
}

const getWarehouse = async () => {
  const { data } = await warehouseInfoGetAll()
  warehouseList.value = data
}
const userMarkList = ref<string[]>([])
const getUserMark = async () => {
  try {
    const res = await getUserMarkList()
    userMarkList.value = res.data
  } catch (error) {
    //showError(error)
  }
}

const processType = ref([
  {
    label: '烫画',
    value: 'TH',
  },
  {
    label: '直喷',
    value: 'ZP',
  },
  {
    label: '刺绣',
    value: 'CX',
  },
  {
    label: '雕刻',
    value: 'DK',
  },
  {
    label: '白胚',
    value: 'BP',
  },
  {
    label: '其他',
    value: 'QT',
  },
])
// 获取工艺列表
const craftList = ref<IAllList[]>([])
const processTypeMap = processType.value.reduce((acc, cur) => {
  acc[cur.value] = cur.label
  return acc
}, {} as Record<string, string>)
const loadCraftList = async () => {
  try {
    const res = await getListCraftApi()
    if (res.code !== 200) return
    const data: CraftListData[] = res.data
    craftList.value = data.map((item) => ({
      id: item.craftCode,
      name: item.craftName,
      warehouseName: processTypeMap[item.craftType] ?? '其他', // craftType 对应中文
    })) as IAllList[]
  } catch (e) {
    console.error(e)
  }
}

const tableRef = ref()
const getOrderListFn = async () => {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  const { currentPage, pageSize } = pagination.value
  try {
    const { data } = await getOrderList(
      {
        ...searchForm.value,
        startTime:
          timeRange.value && timeRange.value.length > 0
            ? timeRange.value[0]
            : null,
        endTime:
          timeRange.value && timeRange.value.length > 0
            ? timeRange.value[1]
            : null,
      },
      currentPage,
      pageSize,
      true,
    )
    tableData.value = data.records.flat()
    pagination.value.total = data.total
    if (tableData.value?.length) {
      nextTick(async () => {
        await tableRef.value?.setCurrentRow(tableData.value[0])
        rowClick(tableData.value[0] as unknown as PodCnOrderListData)
      })
    }
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}
const currentRowId = ref<number>()

function rowClick(row: PodCnOrderListData) {
  currentRowId.value = row.id
  goodsLoading.value = true
  goodsData.value = row.productList as ProductList[]
  const timer = setTimeout(() => {
    goodsLoading.value = false
    clearTimeout(timer)
  }, 500)
}

const logLoading = ref(false)
const operationLog = async () => {
  logLoading.value = true
  try {
    if (currentRowId.value) {
      const res = await getOperationLogApi(currentRowId.value as number)
      if (res.code !== 200) return
      logList.value = res.data.map((el) => {
        return {
          ...el,
          local: 'BeiJing',
        }
      })
      tempChinaLogs.value = [...logList.value]
    }
  } catch (e) {
    console.error(e)
  } finally {
    const timer = setTimeout(() => {
      logLoading.value = false
      clearTimeout(timer)
    }, 500)
  }
}

const tabsNav = ref<Tab[]>([])
const loadTabData = async () => {
  try {
    const res = await getOrderTabData()
    tabsNav.value = res.data.filter((el) => el.status !== 'BATCH_DOWNLOAD')
  } catch (error) {
    // showError(error)
  }
}

function getStatus(status: string) {
  const item = tabsNav.value.find((el) => el.status === status)

  if (item) {
    return item.statusName
  }
  return ''
}

const resultInfo = ref<
  {
    id: string | number
    status: boolean
    factoryOrderNumber?: string
    message: string
  }[]
>([])
const resultRefs = ref<InstanceType<typeof ResultInfo> | null>(null)

const refreshAddress = async () => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  await ElMessageBox.confirm('是否刷新地址?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await OrderCnReceiverAddress(
      selection.value.map((item) => item.id),
    )
    if (res.code !== 200) return
    ElMessage.success('操作成功')
    search()
    await loadTabData()
    if (tabValue.value === '2') {
      zoneType.value = 'Asia/Shanghai'
      await operationLog()
    }
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

/**
 * @description: 获取打印面单
 */
const getOrderByIdApi = async (type: string) => {
  if (selection.value.length === 0) {
    return ElMessage.warning('请选择数据')
  }

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

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

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

      const res = await operation.Fn(ids)
      if (res.code === 200) {
        if (isArray(res.data)) {
          resultInfo.value =
            (res.data as {
              id: string | number
              status: boolean
              factoryOrderNumber?: string
              message: string
            }[]) || []

          resultRefs.value?.showDialog()
          console.log(33)
        } else if (isString(res.data)) {
          window.open(filePath + res.data)
        }
      } else {
        ElMessage.error(res.message)
      }
    } catch (e) {
      resultInfo.value = []
      console.error(e)
    } finally {
      loading && loading.close()
    }
  } else {
    ElMessage.warning('未知操作类型')
  }
}

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

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

const resultConfirm = () => {
  search()
  loadTabData()
}

const handleSelectionChange = (val: PodCnOrderListData[]) => {
  selection.value = val
}

// 获取行类名方法
const getRowClassName = ({ row }: { row: PodCnOrderListData }) => {
  return selection.value.some((item) => item.id === row.id)
    ? 'row-selected'
    : ''
}

const handleRadioGroupClick = (event: Event) => {
  const target = event.target as HTMLElement
  const radioButton = target.closest('.el-radio-button')

  if (radioButton) {
    const input = radioButton.querySelector(
      'input[type="radio"]',
    ) as HTMLInputElement
    if (input) {
      const value = input.value
      if (searchForm.value.customizedQuantity === value) {
        event.preventDefault()
        event.stopPropagation()
        searchForm.value.customizedQuantity = ''
      }
    }
  }
}

const handleMultiRadioGroupClick = (event: Event) => {
  const target = event.target as HTMLElement
  const radioButton = target.closest('.el-radio-button')

  if (radioButton) {
    const input = radioButton.querySelector(
      'input[type="radio"]',
    ) as HTMLInputElement
    if (input) {
      const value = input.value === 'true' ? true : false
      if (searchForm.value.multi === value) {
        event.preventDefault()
        event.stopPropagation()
        searchForm.value.multi = null
      }
    }
  }
}

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

useEnterKeyTrigger({
  formRef: searchFormRef,
  btnRef: searchBtnRef,

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

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

watch(
  () => currentRowId.value,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      operationLog()
    }
  },
)
loadTabData()
getUserMark()
loadCraftList()
getWarehouse()

onMounted(() => {
  getOrderListFn()
})
</script>

<template>
  <split-div other-size="35">
    <template #top>
      <el-card>
        <ElForm
          ref="searchFormRef"
          :model="searchForm"
          size="default"
          inline
          class="search-form"
          label-position="right"
          label-width="90px"
        >
          <ElFormItem label="仓库">
            <ElSelect
              v-model="searchForm.warehouseId"
              clearable
              filterable
              placeholder="请输入"
              style="width: 180px"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="平台">
            <ElSelect
              v-model="searchForm.platform"
              value-key=""
              placeholder="请选择"
              clearable
              filterable
              popper-class="customize-select-style"
              style="width: 150px"
            >
              <ElOption
                v-for="(item, index) in platformJson"
                :key="index"
                :label="item.type"
                :value="item.type"
                style="width: 160px"
              >
                <img
                  :src="`/images/icon/${item.icon.split('/').pop()}`"
                  style="height: 20px; margin: 5px 10px 0 0"
                />
                <span :title="item.type">{{ item.type }}</span>
              </ElOption>
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="订单号">
            <ElInput
              v-model="searchForm.factoryOrderNumber"
              placeholder="订单号"
              clearable
              style="width: 150px"
            />
          </ElFormItem>

          <ElFormItem label="物流跟踪号">
            <ElInput
              v-model.trim="searchForm.trackingNumber"
              placeholder="物流跟踪号"
              clearable
              style="width: 150px"
            ></ElInput>
          </ElFormItem>

          <ElFormItem label="店铺单号">
            <ElInput
              v-model="searchForm.shopNumber"
              placeholder="店铺单号"
              clearable
              style="width: 150px"
            />
          </ElFormItem>
          <ElFormItem label="生产单号">
            <ElInput
              v-model="searchForm.factorySubOrderNumber"
              placeholder="生产单号"
              clearable
              style="width: 150px"
            />
          </ElFormItem>
          <ElFormItem label="状态">
            <ElSelect
              v-model="searchForm.status"
              clearable
              filterable
              placeholder="请输入"
              style="width: 150px"
            >
              <el-option
                v-for="item in tabsNav"
                :key="item.status"
                :label="item.statusName"
                :value="item.status"
              ></el-option>
            </ElSelect>
          </ElFormItem>

          <ElFormItem label="印刷">
            <el-radio-group
              v-model="searchForm.customizedQuantity"
              @click.stop="(e: Event) => handleRadioGroupClick(e)"
            >
              <el-radio-button value="single">单面</el-radio-button>
              <el-radio-button value="multiple">多面</el-radio-button>
              <el-radio-button value="normal">普品</el-radio-button>
              <el-radio-button value="custom_normal">胚衣</el-radio-button>
            </el-radio-group>
          </ElFormItem>
          <ElFormItem label="数量">
            <el-radio-group
              v-model="searchForm.multi"
              @click.stop="(e: Event) => handleMultiRadioGroupClick(e)"
            >
              <el-radio-button :value="false" class="radioBtn"
                >单件</el-radio-button
              >
              <el-radio-button :value="true" class="radioBtn"
                >多件</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="timeRange"
                      :teleported="false"
                      :default-time="[
                        new Date(0, 0, 0, 0, 0, 0),
                        new Date(0, 0, 0, 23, 59, 59),
                      ]"
                      placeholder="收货人"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetimerange"
                      style="width: 280px"
                      :shortcuts="pickerOptions.shortcuts"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      clearable
                    >
                    </el-date-picker>
                  </div>
                </ElFormItem>

                <ElFormItem label="工艺">
                  <!-- <ElSelect
                    v-model="searchForm.craftCode"
                    clearable
                    filterable
                    placeholder="请输入工艺"
                    style="width: 150px"
                  >
                    <el-option
                      v-for="item in craftList"
                      :key="item.craftCode"
                      :label="item.craftName"
                      :value="item.craftCode"
                    ></el-option>
                  </ElSelect> -->
                  <LogisticsWaySelect
                    v-model="searchForm.craftCode"
                    :company-list="craftList"
                    :start-width="'150px'"
                    search-placeholder="搜索工艺名称"
                    start-placeholder="请选择工艺名称"
                  ></LogisticsWaySelect>
                </ElFormItem>
                <ElFormItem label="款号">
                  <ElInput
                    v-model="searchForm.supplierProductNo"
                    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="批次号">
                  <ElInput
                    v-model="searchForm.batchArrangeNumber"
                    placeholder="批次号"
                    clearable
                    style="width: 150px"
                  />
                </ElFormItem>
                <ElFormItem label="库存SKU">
                  <ElInput
                    v-model.trim="searchForm.thirdSkuCode"
                    placeholder="库存SKU"
                    clearable
                    style="width: 150px"
                  ></ElInput>
                </ElFormItem>
                <ElFormItem label="Variant SKU">
                  <ElInput
                    v-model.trim="searchForm.sku"
                    placeholder="Variant SKU"
                    clearable
                    style="width: 150px"
                  ></ElInput>
                </ElFormItem>
                <ElFormItem label="是否代发">
                  <ElSelect
                    v-model="searchForm.replaceShipment"
                    placeholder="是否代发"
                    clearable
                    :teleported="false"
                    style="width: 150px"
                  >
                    <ElOption
                      v-for="(item, index) in ['不代发', '代发']"
                      :key="index"
                      :value="index"
                      :label="item"
                    ></ElOption>
                  </ElSelect>
                </ElFormItem>
                <ElFormItem label="商品类型">
                  <ElSelect
                    v-model="searchForm.productMark"
                    placeholder="请选择商品类型"
                    clearable
                    filterable
                    collapse-tags
                    collapse-tags-tooltip
                    :teleported="false"
                    style="width: 150px"
                  >
                    <ElOption
                      v-for="(item, index) in productMarkList"
                      :key="index"
                      :value="item.value"
                      :label="item.label"
                    ></ElOption>
                  </ElSelect>
                </ElFormItem>
                <ElFormItem
                  v-if="
                    searchForm.replaceShipment ||
                    searchForm.replaceShipment === 0
                  "
                  label="物流类型"
                >
                  <ElSelect
                    v-model="searchForm.shipmentType"
                    placeholder="物流类型"
                    clearable
                    style="width: 150px"
                  >
                    <ElOption
                      v-for="(item, index) in searchForm.replaceShipment === 0
                        ? ['自提', '快递']
                        : ['自有物流', '工厂物流']"
                      :key="index"
                      :value="index"
                      :label="item"
                    ></ElOption>
                  </ElSelect>
                </ElFormItem>
                <!-- <ElFormItem label="Base SKU">
                <ElInput
                  v-model.trim="searchForm.baseSku"
                  placeholder=" Base SKU"
                  clearable
                  style="width: 150px"
                ></ElInput>
              </ElFormItem> -->
              </ElForm>
              <template #reference>
                <el-button
                  type="warning"
                  @click="searchVisible = !searchVisible"
                >
                  <el-icon v-if="searchVisible">
                    <CaretTop />
                  </el-icon>
                  <el-icon v-else>
                    <CaretBottom />
                  </el-icon>
                </el-button>
              </template>
            </ElPopover>
          </ElFormItem>
          <ElFormItem>
            <span>
              <ElButton link style="font-size: 12px" @click="resetSearchForm"
                ><span title="重置查询条件">重置</span></ElButton
              >
            </span>
          </ElFormItem>
          <ElFormItem>
            <span>
              <ElButton ref="searchBtnRef" type="primary" @click="search"
                >查询</ElButton
              >
            </span>
          </ElFormItem>
          <ElFormItem>
            <span>
              <ElButton type="primary" @click="getOrderByIdApi('getPrintOrder')"
                >获取打印面单</ElButton
              >
            </span>
          </ElFormItem>
          <ElFormItem>
            <span>
              <ElButton type="success" @click="refreshAddress"
                >刷新地址</ElButton
              >
            </span>
          </ElFormItem>
          <ElFormItem>
            <ElButton type="success" @click="exportData">导出</ElButton>
          </ElFormItem>
        </ElForm>
      </el-card>
    </template>
    <template #bottom>
      <el-card style="height: 100%">
        <div class="manage">
          <div class="table-flex">
            <div class="top-table">
              <div class="table-container">
                <TableView
                  ref="tableRef"
                  :row-click-select="true"
                  :columns="tableColumns"
                  :serial-numberable="true"
                  :selectionable="true"
                  :paginated-data="tableData"
                  :row-class-name="getRowClassName"
                  @row-click="rowClick"
                  @selection-change="handleSelectionChange"
                >
                  <template #factoryOrderNumber="{ row }">
                    <div style="display: flex; align-items: center">
                      {{ row.factoryOrderNumber }}
                      <el-tooltip
                        effect="light"
                        content="该订单已拦截"
                        placement="bottom"
                      >
                        <el-icon
                          v-if="
                            row.interceptStatus &&
                            (row.interceptStatus === 1 ||
                              row.interceptStatus === 3)
                          "
                          style="margin-left: 5px; cursor: pointer"
                          color="#E6A23C"
                        >
                          <WarningFilled />
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <template #status="{ row }">
                    <div>{{ getStatus(row.status) }}</div>
                  </template>
                  <template #shipmentType="{ row }">
                    {{
                      (row.replaceShipment === 0
                        ? ['自提', '快递']
                        : ['自有物流', '工厂物流'])[row.shipmentType]
                    }}
                  </template>
                  <template #replaceShipment="{ row }">
                    {{ ['不代发', '代发'][row.replaceShipment] }}
                  </template>
                </TableView>
              </div>
              <div class="pagination">
                <el-pagination
                  v-model:current-page="pagination.currentPage"
                  v-model:page-size="pagination.pageSize"
                  size="small"
                  :page-sizes="[50, 100, 150, 200]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="pagination.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </template>
    <template #other>
      <div class="bottom-table">
        <el-tabs v-model="tabValue">
          <el-tab-pane name="1" label="商品明细">
            <TableView
              ref="goodsRef"
              v-loading="goodsLoading"
              :columns="goodsColumns"
              :serial-numberable="true"
              :paginated-data="goodsData"
            >
              <template #productImg="{ row }">
                <ImageView :src="row.variantImage" width="30px" height="30px" />
              </template>
            </TableView>
          </el-tab-pane>
          <el-tab-pane name="2" label="操作日志" @tab-click="operationLog">
            <div>
              <el-button
                :type="zoneType === 'Asia/Shanghai' ? 'primary' : ''"
                size="small"
                link
                style="margin-left: 10px"
                @click="changeChinaTime('Asia/Shanghai')"
                >北京时间
              </el-button>
              <el-button
                :type="zoneType === 'America/New_York' ? 'primary' : ''"
                size="small"
                link
                style="margin-left: 10px"
                @click="changeChinaTime('America/New_York')"
                >新泽西时间
              </el-button>
              <el-button
                :type="zoneType === 'America/Los_Angeles' ? 'primary' : ''"
                size="small"
                link
                style="margin-left: 10px"
                @click="changeChinaTime('America/Los_Angeles')"
                >洛杉矶时间
              </el-button>
            </div>

            <LogList
              v-loading="logLoading"
              :log-list="logList"
              style="font-size: 14px; height: 100%"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </template>
  </split-div>
  <ElDialog
    v-model="exportVisible"
    title="导出选项"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form :model="exportForm" label-width="80px">
      <el-form-item label="" prop="resource">
        <el-radio-group v-model="exportForm.resource">
          <el-radio :label="0">导出本页</el-radio>
          <el-radio :label="1">导出选中</el-radio>
          <el-radio :label="2">全部</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportVisible = false">取消</el-button>
        <el-button
          :loading="exportLoading"
          type="primary"
          @click="submitExportForm"
          >确认</el-button
        >
      </span>
    </template>
  </ElDialog>
  <ResultInfo
    ref="resultRefs"
    :list="resultInfo"
    @confirm="resultConfirm"
  ></ResultInfo>
</template>

<style scoped lang="scss">
::v-deep(.search-form) {
  .el-form-item {
    margin-bottom: 10px;
    margin-right: 14px;
  }
}

.el-card {
  ::v-deep(.el-card__body) {
    padding: 10px;
    padding-bottom: 0;
    height: 100%;
  }
}

.manage {
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    margin-bottom: 10px;
  }

  .table-flex {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .right-table {
    flex: 1;
    margin-left: 10px;
    flex-shrink: 0;
  }

  .top-table {
    height: 100%;
    display: flex;
    width: 100%;
    flex-direction: column;

    .pagination {
      display: flex;
      margin: 10px 0;
      justify-content: center;
    }

    .table-container {
      flex: 1;
      flex-shrink: 0;
      overflow: hidden;
    }
  }
}

.bottom-table {
  height: 100%;
  background: white;
  box-sizing: border-box;
  padding: 10px;

  ::v-deep(.el-tabs) {
    height: 100%;
    display: flex;

    .el-tabs__content {
      flex: 1;
      flex-shrink: 0;

      .el-tab-pane {
        height: 100%;

        ul {
          height: 100%;
        }
      }
    }
  }
}
.radioBtn {
  ::v-deep .el-radio-button__inner {
    width: 75px;
  }
}

// 设置选中行的背景色
:deep(.el-table__body) {
  .el-table__row:hover {
    td {
      background-color: #e1ebf5 !important;
    }
  }
  .el-table__row.row-selected {
    td {
      background-color: #faecd8 !important;
    }
  }
  // 确保选中行的背景色在 hover 时也保持
  .el-table__row.row-selected:hover {
    td {
      background-color: #faecd8 !important;
    }
  }
}
</style>
