<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    top="140px"
    :fullscreen="true"
    :close-on-click-modal="false"
    @opened="onOpened"
    @close="emit('close')"
  >
    <div class="detail-div">
      <div class="detail-content">
        <div class="left">
          <div class="left-images">
            <el-carousel
              v-if="detail?.imgList.length > 0"
              style="height: 100%"
              :autoplay="false"
              indicator-position="none"
            >
              <el-carousel-item
                v-for="(item, index) in detail?.imgList"
                :key="index"
                style="height: 100%"
              >
                <div class="left-image">
                  <b v-show="item?.title && item?.url">
                    {{ item?.title }}
                    <span
                      v-if="item?.id"
                      style="
                        text-decoration: underline;
                        cursor: pointer;
                        color: blue;
                      "
                    >
                      （DID：{{ item?.id }}）
                    </span>
                  </b>
                  <img :src="item.url" alt="" />
                </div>
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>
        <div class="right">
          <div
            v-if="
              [
                'fastProduction',
                'fastReceipt',
                'productionScan',
                'qualityScan',
              ].includes(fastKey)
            "
            class="input"
          >
            <el-input
              ref="trackingNumberRef"
              v-model="TrackingNumber"
              :placeholder="placeholderText"
              style="width: 660px; margin-right: 10px"
              clearable
              @keydown.enter="trackCodeInput()"
            />
            <el-button type="primary" @click="trackCodeInput()">
              查询
            </el-button>
          </div>
          <div v-if="fastKey === 'qualityScan'" class="input">
            <el-select
              v-model="printDevice"
              placeholder="请选择打印机"
              clearable
              filterable
              @change="handlePrinterChange"
            >
              <el-option
                v-for="(item, i) in printList"
                :key="i"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-button
              style="margin-left: 5px"
              type="primary"
              @click="printPdf"
            >
              打印操作单
            </el-button>
            <el-checkbox
              v-model="isPrint"
              :disabled="!printDevice"
              style="margin-left: 10px"
            >
              自动打印
            </el-checkbox>
          </div>

          <div class="div-text">
            <div v-if="fastKey !== 'qualityScan'" class="div-content">
              <div :title="String(detail?.userMark)" class="div-item">
                <span class="div-item-label" style="font-size: 18px"
                  >客户：</span
                >
                <div class="div-item-value" style="color: red; font-size: 30px">
                  {{ detail?.userMark }}
                </div>
              </div>
              <div :title="String(detail?.factoryOrderNumber)" class="div-item">
                <span class="div-item-label" style="font-size: 18px"
                  >订单号：</span
                >
                <div class="div-item-value" style="color: red; font-size: 22px">
                  {{ detail?.factoryOrderNumber }}
                </div>
              </div>
              <div
                v-if="fastKey === 'fastReceipt'"
                :title="String(detail?.shopNumber)"
                class="div-item"
              >
                <span class="div-item-label" style="font-size: 18px"
                  >店铺单号：</span
                >
                <div class="div-item-value" style="color: red; font-size: 22px">
                  {{ detail?.shopNumber }}
                </div>
              </div>
            </div>
          </div>
          <div class="div-text">
            <b v-if="showOperationNoRow">操作单信息</b>
            <b v-else>生产单信息</b>
            <div class="div-content">
              <div
                v-if="showOperationNoRow"
                :title="String(operationNoDisplay)"
                class="div-item"
              >
                <span class="div-item-label">操作单号：</span>
                <div class="div-item-value with-copy">
                  <span class="div-item-value-text">{{
                    operationNoDisplay
                  }}</span>
                  <el-icon
                    v-if="operationNoDisplay"
                    class="copy-icon"
                    @click="copy(operationNoDisplay)"
                  >
                    <DocumentCopy />
                  </el-icon>
                </div>
              </div>
              <div
                v-else
                :title="detail?.factorySubOrderNumber"
                class="div-item"
              >
                <span class="div-item-label">生产单号：</span>
                <div class="div-item-value">
                  {{ detail?.factorySubOrderNumber }}
                </div>
              </div>
              <div
                v-if="fastKey !== 'fastReceipt'"
                :title="detail?.shopNumber ?? ''"
                class="div-item"
              >
                <span class="div-item-label">店铺单号：</span>
                <div class="div-item-value with-copy">
                  <span class="div-item-value-text">{{
                    detail?.shopNumber ?? ''
                  }}</span>
                  <el-icon
                    v-if="detail?.shopNumber"
                    class="copy-icon"
                    @click="copy(String(detail.shopNumber))"
                  >
                    <DocumentCopy />
                  </el-icon>
                </div>
              </div>
              <div
                v-if="fastKey === 'qualityScan'"
                :title="String(detail?.batchArrangeNumber) || ''"
                class="div-item"
              >
                <span class="div-item-label">批次号：</span>
                <div class="div-item-value">
                  {{ detail?.batchArrangeNumber }}
                </div>
              </div>
              <div
                v-if="fastKey === 'fastReceipt'"
                :title="String(detail.productName) || ''"
                class="div-item"
              >
                <span class="div-item-label">商品名称：</span>
                <div class="div-item-value">
                  {{ detail.productName || '' }}
                </div>
              </div>
              <div
                v-if="fastKey === 'fastReceipt'"
                :title="String(detail.statusName || '')"
                class="div-item"
              >
                <span class="div-item-label">挂起前状态：</span>
                <div class="div-item-value">
                  <ElTag v-if="detail.statusName" type="primary">{{
                    detail.statusName || ''
                  }}</ElTag>
                </div>
              </div>
              <div
                v-if="fastKey === 'fastReceipt'"
                :title="String(detail.thirdSkuCode)"
                class="div-item"
              >
                <span class="div-item-label">库存SKU：</span>
                <div class="div-item-value">{{ detail.thirdSkuCode }}</div>
              </div>
              <div
                v-if="!showOperationNoRow"
                :title="detail?.thirdSubOrderNumber || ''"
                class="div-item"
              >
                <span class="div-item-label">第三方生产单号：</span>
                <div class="div-item-value">
                  {{ detail?.thirdSubOrderNumber }}
                </div>
              </div>
              <div :title="String(detail?.craftName)" class="div-item">
                <span class="div-item-label">生产工艺：</span>
                <div class="div-item-value">
                  {{ detail?.craftName }}
                </div>
              </div>
              <div
                v-if="fastKey !== 'fastReceipt' && fastKey !== 'qualityScan'"
                :title="detail?.baseSku"
                class="div-item"
              >
                <span class="div-item-label">基版：</span>
                <div class="div-item-value">{{ detail?.baseSku }}</div>
              </div>
              <div
                v-if="fastKey === 'qualityScan'"
                :title="detail?.baseSku"
                class="div-item"
              >
                <span class="div-item-label">库存SKU：</span>
                <div class="div-item-value">{{ detail?.baseSku }}</div>
              </div>
              <div v-else :title="detail?.variantSku" class="div-item">
                <span class="div-item-label">变体SKU：</span>
                <div class="div-item-value">{{ detail?.variantSku }}</div>
              </div>
              <div
                v-if="fastKey !== 'fastReceipt' && fastKey !== 'qualityScan'"
                :title="
                  String(showOperationNoRow ? detail?.quantity : detail?.num)
                "
                class="div-item"
              >
                <span class="div-item-label">数量：</span>
                <div class="div-item-value">
                  {{ showOperationNoRow ? detail?.quantity : detail?.num }}
                </div>
              </div>

              <div
                v-if="fastKey !== 'fastReceipt' && fastKey !== 'qualityScan'"
                :title="String(detail?.size || '')"
                class="div-item"
              >
                <span class="div-item-label">尺寸：</span>
                <div class="div-item-value">{{ detail?.size }}</div>
              </div>
              <div
                v-if="detail?.sizeType && fastKey !== 'fastReceipt'"
                :title="String(detail?.sizeType || '')"
                class="div-item"
              >
                <span class="div-item-label">尺码类型：</span>
                <div class="div-item-value">
                  {{ sizeList.find((i) => i.value === detail.sizeType)?.name }}
                </div>
              </div>
              <div
                v-if="fastKey === 'qualityScan'"
                :title="String(detail?.statusName || '')"
                class="div-item"
              >
                <span class="div-item-label">操作单状态：</span>
                <div class="div-item-value" style="color: red">
                  {{ detail?.statusName }}
                </div>
              </div>
              <div :title="detail?.createTime" class="div-item">
                <span class="div-item-label">创建时间：</span>
                <div class="div-item-value">{{ detail?.createTime }}</div>
              </div>
            </div>
          </div>

          <div class="btn">
            <div
              :style="{
                visibility: [
                  'fastProduction',
                  'fastReceipt',
                  'productionScan',
                  'qualityScan',
                ].includes(fastKey)
                  ? 'visible'
                  : 'hidden',
              }"
              class="btn-sure"
            >
              <el-button
                style="width: 100%; height: 100%; font-size: 18px"
                size="large"
                type="success"
                @click="
                  fastKey === 'qualityScan'
                    ? handleQuality(true)
                    : changeStatus()
                "
              >
                {{ sureButtonText }}
              </el-button>
              <div class="check">
                <el-checkbox v-model="isAutoSure"> 自动完成上一单 </el-checkbox>
              </div>
            </div>
            <div v-if="fastKey === 'qualityScan'" class="btn-down">
              <el-button
                style="width: 100%; height: 100%; font-size: 18px"
                type="danger"
                size="large"
                @click="handleQuality(false)"
              >
                质检不通过
              </el-button>
            </div>
            <div v-else-if="fastKey !== 'fastReceipt'" class="btn-down">
              <div class="check">
                <el-checkbox v-model="isDownloadImage" size="large">
                  扫码下载素材
                </el-checkbox>
              </div>
              <el-button
                style="width: 100%; height: 100%; font-size: 18px"
                type="primary"
                size="large"
                @click="handleDownload"
              >
                下载素材
              </el-button>
            </div>
          </div>
          <div
            class="div-text"
            style="
              flex: 1;
              flex-shrink: 0;
              display: flex;
              flex-direction: column;
            "
          >
            <div
              v-if="Array.isArray(detail?.note) && detail.note.length"
              style="height: 100%"
              class="div-content"
            >
              <b style="position: absolute; top: -12px">客户留言信息</b>
              <div
                v-for="(item, index) in detail?.note"
                :key="index"
                class="div-item"
              >
                <span>{{ item.prop }}:</span>
                <p>
                  {{ item.value }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <QualityFailDialog
      v-if="fastKey === 'qualityScan'"
      ref="qualityFailDialogRef"
      @success="handleQualitySuccess"
    />
  </el-dialog>
</template>
<script setup lang="tsx">
import {
  productionQueryApi,
  getSubOrderBySubOrderNumber,
  downloadMaterialApi,
} from '@/api/podCnOrder'
import { cardImages, PodOrderRes } from '@/types/api/podCnOrder'
import {
  checkInventoryApi,
  qualityPodOrderOperationApi,
} from '@/api/factoryOrderNew'
import { showConfirm } from '@/utils/ui'
import { filePath } from '@/api/axios'
import { computed, ref, watch } from 'vue'
import { BaseRespData } from '@/types/api'
import useLodop from '@/utils/hooks/useLodop'
import { print } from '@/components/print'
import { DocumentCopy } from '@element-plus/icons-vue'
import QualityFailDialog from '@/views/order/factoryOrderNew/component/QualityFailDialog.vue'
interface HistoryDataItem {
  orderNumber: string
  finished: boolean
}
const title = computed(() => {
  switch (props.fastKey) {
    case 'fastProduction':
    case 'productionScan':
      return '快捷生产'
    case 'fastReceipt':
      return props.dialogTitle
    case 'qualityScan':
      return '快捷质检'
    default:
      return '查看详情'
  }
})
const sureButtonText = computed(() => {
  switch (props.fastKey) {
    case 'fastProduction':
    case 'productionScan':
      return '生产完成'
    case 'qualityScan':
      return '质检通过'
    default:
      return '快捷入库'
  }
})
export type FastProductionDetail = PodOrderRes & {
  operationNo?: string | null
  quantity?: number | null
  podOrderNo?: string | null
  podOrderProductId?: number | null
  statusName?: string | null
  productMark?: string | null
  pause?: 0 | 1
  status?: string | null
}
const trackingNumberRef = ref()
const historyData = ref<HistoryDataItem[]>([])
const placeholderText = ref('')
const sendNum = ref(0)
const isDownloadImage = ref(false)
const isAutoSure = ref(true)
const printDevice = ref('')
const isPrint = ref(false)
const printList = ref<string[]>([])
const { getCLodop } = useLodop()
const emptyDetail = (): FastProductionDetail => ({
  id: -1,
  podJomallOrderCnId: -1,
  imgList: [] as cardImages[],
})
const detail = ref<FastProductionDetail>(emptyDetail())
const dialogVisible = ref(false)
// 尺码类型表
const sizeList = ref<{ name: string; value: number }[]>([
  { name: '正常码', value: 1 },
  { name: '大码', value: 2 },
])
// 通过import动态导入音频文件
const audios = {
  weight_warning: new URL('@/assets/audio/weight_warning.mp3', import.meta.url)
    .href,
  weight_success: new URL('@/assets/audio/weight_success.mp3', import.meta.url)
    .href,
  weight_repeat: new URL('@/assets/audio/weight_repeat.mp3', import.meta.url)
    .href,
  weight_search_error: new URL(
    '@/assets/audio/weight_search_error.mp3',
    import.meta.url,
  ).href,
  weight_search_success: new URL(
    '@/assets/audio/weight_search_success.mp3',
    import.meta.url,
  ).href,
}
const TrackingNumber = ref('')
const props = withDefaults(
  defineProps<{
    type?: number
    detailVisible?: boolean
    detailData?: Record<string, unknown> | null
    fastKey?: string
    historyStorageKey?: string
    trackingPlaceholder?: string
    isNewOrder?: boolean
    queryApi?: (orderNumber: string) => Promise<{ data?: unknown }>
    completeApi?: (
      ids: number[],
      detail: Record<string, unknown>,
      trigger?: 'manual' | 'auto',
    ) => Promise<unknown>
    downloadApi?: (
      ids: number[],
    ) => Promise<{ code?: number; message?: string }>
    printApi?: (ids: number[]) => Promise<{ code?: number; message?: string }>
    defaultAutoSure?: boolean
    showOperationNoRow?: boolean
    notFoundMessage?: string
    pendingOrderLabel?: string
    pleaseScanTip?: string
    searchInputAudioTip?: string
    /** 是否限制扫码 */
    isLimitScan?: boolean
    /** 限制扫码的提示 */
    limitScanMessage?: string
    dialogTitle?: string
  }>(),
  {
    type: 0,
    detailVisible: false,
    detailData: null,
    fastKey: '',
    isNewOrder: false,
    historyStorageKey: 'historyCnData',
    trackingPlaceholder:
      '扫描枪输入生产单号，录入下一单本单自动生产完成，最后一单扫两次完成生产',
    defaultAutoSure: true,
    showOperationNoRow: false,
    notFoundMessage: '生产单不存在',
    pendingOrderLabel: '生产单号',
    pleaseScanTip: '请扫码生产单号',
    searchInputAudioTip: '请录入生产单号???',
    isLimitScan: false,
    queryApi: (orderNumber: string) => getSubOrderBySubOrderNumber(orderNumber),
    completeApi: (ids: number[], detailData: Record<string, unknown>) =>
      productionQueryApi(ids[0], Number(detailData.podJomallOrderCnId || -1)),
    downloadApi: (ids: number[]) => downloadMaterialApi(ids),
    printApi: undefined,
    dialogTitle: '',
  },
)
const emit = defineEmits(['update:detailVisible', 'close', 'onSuccess'])

// 获取自动完成上一单勾选缓存
const getCachedQualityAutoSure = (fallback: boolean) => {
  const cached = localStorage.getItem('qualityScanAutoSure')
  if (cached === null) return fallback
  return cached === 'true'
}

// 缓存自动完成上一单勾选
watch(isAutoSure, (val) => {
  if (props.fastKey === 'qualityScan') {
    localStorage.setItem('qualityScanAutoSure', String(val))
  }
})

const qualityFailDialogRef = ref<InstanceType<typeof QualityFailDialog>>()

const historyKeyFromDetail = (d: FastProductionDetail): string => {
  const raw = d as unknown as Record<string, unknown>
  const op = raw.operationNo
  if (op !== undefined && op !== null && String(op).trim() !== '') {
    return String(op)
  }
  return String(d.factorySubOrderNumber ?? '')
}

const operationNoDisplay = computed(() => {
  const raw = detail.value as unknown as Record<string, unknown>
  const v = raw.operationNo
  if (v === undefined || v === null) return ''
  return String(v)
})

const copy = (text: string) => {
  if (!text) return
  navigator.clipboard.writeText(text)
  ElMessage.success('复制成功')
}

const parseImages = (value: unknown): cardImages[] => {
  if (!value) return []
  if (Array.isArray(value)) {
    return value
      .filter((item) => !!item?.url)
      .map((item, index) => ({
        title: String(item?.title || ''),
        url: String(item?.url || ''),
        sort: Number(item?.sort ?? index + 1),
        id: item?.id,
      }))
  }
  if (typeof value === 'string') {
    const source = value.trim()
    if (!source) return []
    if (source.startsWith('http')) {
      return source.split(',').map((url, index) => ({
        title: '',
        url: url.trim(),
        sort: index + 1,
      }))
    }
    try {
      const parsed = JSON.parse(source)
      if (Array.isArray(parsed)) {
        return parsed
          .filter((item) => !!item?.url)
          .map((item, index) => ({
            title: String(item?.title || ''),
            url: String(item?.url || ''),
            sort: Number(item?.sort ?? index + 1),
            id: item?.id,
          }))
      }
    } catch (_e) {
      return []
    }
  }
  return []
}

const normalizeDetail = (value: unknown): FastProductionDetail => {
  const raw = (value || {}) as Record<string, unknown>
  const d = JSON.parse(JSON.stringify(raw)) as Record<string, unknown>
  if (typeof d.note === 'string') {
    try {
      d.note = JSON.parse(d.note)
    } catch (_e) {
      d.note = []
    }
  }
  if (!Array.isArray(d.note)) d.note = []
  const imageSource =
    d.imageAry || d.designImages || d.imgList || d.variantImage
  d.imgList = parseImages(imageSource)
  return d as unknown as FastProductionDetail
}

watch(
  () => props.detailVisible,
  (newVal: boolean) => {
    dialogVisible.value = newVal
    detail.value = { id: -1, podJomallOrderCnId: -1, imgList: [] }
    if (newVal) {
      const history = localStorage.getItem(props.historyStorageKey)
      historyData.value = history ? JSON.parse(history) : []

      const len = historyData.value
      if (
        len.length > 0 &&
        ['fastProduction', 'fastReceipt', 'productionScan'].includes(
          props.fastKey,
        )
      ) {
        confirmQuery(len, 0)
      }
      placeholderText.value = props.trackingPlaceholder

      trackingNumberRef.value && trackingNumberRef.value.focus()

      TrackingNumber.value = ''
      isAutoSure.value =
        props.fastKey === 'qualityScan'
          ? getCachedQualityAutoSure(props.defaultAutoSure)
          : props.defaultAutoSure
      sendNum.value = 0
      if (props.fastKey === 'qualityScan') {
        initPrintDevice()
      }
    }
  },
)

const initPrintDevice = () => {
  const lodop = getCLodop(null, null)
  if (!lodop) {
    printList.value = []
    return
  }
  const arr: string[] = []
  const length = lodop.GET_PRINTER_COUNT()
  for (let i = 0; i < length; i++) {
    const name = lodop.GET_PRINTER_NAME(i)
    if (name) arr.push(name)
  }
  printList.value = arr
}

const getPrintData = async () => {
  if (!detail.value || detail.value.id === -1 || !props.printApi) return
  const res = await props.printApi([detail.value.id])
  if (!res.message) return
  print(filePath + res.message, printDevice.value)
}

const printPdf = () => {
  if (!printDevice.value) return ElMessage.warning('请选择打印机')
  if (!detail.value || detail.value.id === -1) {
    return ElMessage.warning(props.pleaseScanTip)
  }
  getPrintData()
}

const handlePrinterChange = (value: string) => {
  printDevice.value = value
  if (!value) isPrint.value = false
}
watch(
  () => props.detailData,
  (newVal) => {
    detail.value = {
      id: -1,
      podJomallOrderCnId: -1,
      imgList: [],
    }
    if (newVal && Object.keys(newVal).length > 0) {
      detail.value = normalizeDetail(newVal)
    }
  },
  { deep: true },
)
const confirmQuery = (len: HistoryDataItem[], i: number) => {
  const el = len[i]
  const pendingText = (() => {
    switch (props.fastKey) {
      case 'fastProduction':
      case 'productionScan':
        return '未生产'
      case 'qualityScan':
        return '未质检'
      default:
        return '未入库'
    }
  })()
  const successText = (() => {
    switch (props.fastKey) {
      case 'fastProduction':
      case 'productionScan':
        return '生产完成'
      case 'qualityScan':
        return '质检通过'
      default:
        return '入库完成'
    }
  })()
  showConfirm(
    `${props.pendingOrderLabel} ${el.orderNumber} ${pendingText}完成，取消则不提醒?`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(async () => {
      TrackingNumber.value = el.orderNumber
      await trackCodeInput()
      await setData(el.orderNumber)
      ElMessage.success(successText)
      if (len[i + 1]) {
        confirmQuery(len, i + 1)
      }
    })
    .catch(() => {
      const index = historyData.value.findIndex(
        (item: HistoryDataItem) => item.orderNumber === el.orderNumber,
      )
      if (index >= 0) {
        historyData.value.splice(index, 1)
        localStorage.setItem(
          props.historyStorageKey,
          JSON.stringify(historyData.value),
        )
      }
      if (len[i + 1]) {
        confirmQuery(len, i + 1)
      }
      trackingNumberRef.value && trackingNumberRef.value.focus()
    })
}

const changeStatus = async () => {
  if (!detail.value || Object.keys(detail.value).length <= 1) {
    return ElMessage.warning(props.pleaseScanTip)
  }
  const confirmText = (() => {
    switch (props.fastKey) {
      case 'fastProduction':
      case 'productionScan':
        return '生产完成'
      case 'qualityScan':
        return '质检通过'
      default:
        return '入库完成'
    }
  })()
  showConfirm(`确定${confirmText}？`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    setData(historyKeyFromDetail(detail.value))
  })
}
const setData = async (
  orderNumber: string,
  trigger: 'manual' | 'auto' = 'manual',
) => {
  if (!detail.value || detail.value?.id === -1) return
  try {
    const id = detail.value.id
    if (props.fastKey === 'qualityScan') {
      const res = await qualityPodOrderOperationApi({
        updateParams: [{ id, version: detail.value.version }],
        qualityIssues: '',
        qualify_problem_type: '',
        qualityPassed: true,
        source: 1,
      })
      if (res.code !== 200) return
      emit('onSuccess', [{ id, status: true }])
    } else {
      const res = (await props.completeApi(
        [id],
        detail.value as unknown as Record<string, unknown>,
        trigger,
      )) as unknown as BaseRespData<
        {
          factoryOrderNumber?: number
          id: number
          message?: string
          status?: boolean
        }[]
      >
      emit('onSuccess', res.data)
    }
    if (orderNumber) {
      const index = historyData.value.findIndex(
        (el: HistoryDataItem) => el.orderNumber === orderNumber,
      )
      if (index >= 0) {
        // 扫单完成删除
        historyData.value.splice(index, 1)
        localStorage.setItem(
          props.historyStorageKey,
          JSON.stringify(historyData.value),
        )
      }
    }
    playAudio('weight_success')

    if (trigger === 'auto') {
      // new 快捷生产：扫码后直接将订单流转至生产中
      localStorage.setItem(props.historyStorageKey, JSON.stringify([]))
    } else {
      detail.value = {
        id: -1,
        podJomallOrderCnId: -1,
        imgList: [] as cardImages[],
      }
    }
    TrackingNumber.value = ''
    isDownloadImage.value = false
    trackingNumberRef.value && trackingNumberRef.value.focus()
  } catch (e) {
    console.error(e)
    const err = e as BaseRespData<{
      inventory: number
      producingQuantity: number
      availableInventory: number
      thirdSkuCode?: string
    }>
    if (err?.code === 301) {
      await ElMessageBox.alert(
        `${err.data?.thirdSkuCode}库存不足，无法进入生产！请联系仓库管理人员核对库存。<br/>
        库存数量：${err.data?.inventory}，生产中的数量：${err.data?.producingQuantity}，
        <span style="color: red">可调配库存：${err.data?.availableInventory}</span>`,
        '提示',
        {
          type: 'warning',
          dangerouslyUseHTMLString: true,
        },
      ).then(() => {
        localStorage.setItem(props.historyStorageKey, JSON.stringify([]))
      })
    }

    detail.value = {
      id: -1,
      podJomallOrderCnId: -1,
      imgList: [] as cardImages[],
    }
    trackingNumberRef.value && trackingNumberRef.value.focus()
    playAudio('weight_search_error')
  }
}

const handleDownload = () => {
  if (
    !detail.value ||
    Object.keys(detail.value).length <= 1 ||
    detail.value.id == -1
  ) {
    return ElMessage.warning(props.pleaseScanTip)
  }
  download()
}

const handleQuality = (passed: boolean) => {
  if (
    !detail.value ||
    Object.keys(detail.value).length <= 1 ||
    detail.value.id == -1
  ) {
    return ElMessage.warning(props.pleaseScanTip)
  }
  qualityFailDialogRef.value?.open(
    [{ id: detail.value.id, version: detail.value.version }],
    passed,
    1,
  )
}

const handleQualitySuccess = () => {
  const orderNumber = historyKeyFromDetail(detail.value)
  if (orderNumber) {
    const index = historyData.value.findIndex(
      (el: HistoryDataItem) => el.orderNumber === orderNumber,
    )
    if (index >= 0) {
      historyData.value.splice(index, 1)
      localStorage.setItem(
        props.historyStorageKey,
        JSON.stringify(historyData.value),
      )
    }
  }
  detail.value = emptyDetail()
  TrackingNumber.value = ''
  trackingNumberRef.value && trackingNumberRef.value.focus()
  emit('onSuccess', [{ id: 0, status: true }])
}
const download = async () => {
  if (detail.value && detail.value?.id != -1) {
    try {
      const id = props.isNewOrder
        ? (detail.value.podOrderProductId as number)
        : detail.value.id
      if (id !== undefined) {
        try {
          const res = await props.downloadApi([id])
          if (res.code !== 200) return
          // window.open(filePath + res.message)
          const a = document.createElement('a')
          a.href = filePath + res.message
          a.download = res.message!
          a.target = '_blank'
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        } catch (e) {
          console.error(e)
        }
      }
    } catch (e) {
      // showError(e)
      console.error(e)
    }
  }
}
type AudioKey = keyof typeof audios // 创建一个类型，确保 key 只能是 audios 对象的键之一
const playAudio = (key: AudioKey, message?: string) => {
  let text = ''
  switch (key) {
    case 'weight_search_success':
      text = ''
      break
    case 'weight_search_error':
      text = props.searchInputAudioTip
      break
    case 'weight_success':
      text = ''
      break
    case 'weight_repeat':
      text = '称重复录入'
      break
    default:
      text = '请录入跟踪号或重量'
      break
  }
  if (message || text) ElMessage.warning(message || text)
  const audio = new Audio()
  if (audios[key]) {
    audio.src = audios[key] // 获取对应 key 的音频路径
    audio.play().catch((err) => console.error('Audio play failed:', err)) // 捕获音频播放失败的错误
  } else {
    console.error(`No audio found for key: ${key}`)
  }
}

const trackCodeInput = async () => {
  if (!TrackingNumber.value) {
    playAudio('weight_search_error', props.searchInputAudioTip)
    trackingNumberRef.value && trackingNumberRef.value.focus()
    return
  }

  const orderNumber = TrackingNumber.value

  if (isAutoSure.value) {
    await setData(historyKeyFromDetail(detail.value), 'manual')
  }

  try {
    const res = await props.queryApi(orderNumber)
    if (!res.data) {
      return ElMessage.error(props.notFoundMessage)
    }
    detail.value = normalizeDetail(res.data)
    if (detail.value.pause || detail.value.status == 'CANCEL') {
      detail.value = {
        id: -1,
        podJomallOrderCnId: -1,
        imgList: [] as cardImages[],
      }

      ElMessage.warning(
        `订单：${TrackingNumber.value}已挂起或者已取消，无法生产`,
      )
      throw new Error()
    }
    // 扫码后限制
    if (props.isLimitScan) {
      if (
        detail.value.productMark &&
        ['custom_normal', 'normal'].includes(detail.value.productMark)
      ) {
        detail.value = { id: -1, podJomallOrderCnId: -1, imgList: [] }
        localStorage.setItem(props.historyStorageKey, JSON.stringify([]))
        trackingNumberRef.value && trackingNumberRef.value.focus()
        TrackingNumber.value = ''

        return showConfirm(props.limitScanMessage || '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
      }
    }

    // 工厂订单new 校验库存 生产扫码
    if (props.fastKey === 'productionScan') {
      try {
        await checkInventoryApi(
          detail.value.id,
          String(detail.value.status ?? ''),
        )
      } catch (inventoryErr) {
        const err = inventoryErr as BaseRespData<{
          inventory: number
          producingQuantity: number
          availableInventory: number
          thirdSkuCode?: string
        }>
        if (err?.code === 301) {
          historyData.value = []
          localStorage.setItem(props.historyStorageKey, JSON.stringify([]))
          detail.value = emptyDetail()
          playAudio('weight_search_error', props.searchInputAudioTip)
          trackingNumberRef.value && trackingNumberRef.value.focus()
          TrackingNumber.value = ''
          await ElMessageBox.alert(
            `${err.data?.thirdSkuCode}库存不足，无法进入生产！请联系仓库管理人员核对库存。<br/>
            库存数量：${err.data?.inventory}，生产中的数量：${err.data?.producingQuantity}，
            <span style="color: red">可调配库存：${err.data?.availableInventory}</span>`,
            '提示',
            {
              type: 'warning',
              dangerouslyUseHTMLString: true,
            },
          )

          return
        }
        throw inventoryErr
      }
    }

    // 查询成功后再写入缓存
    const item = historyData.value.find(
      (el: HistoryDataItem) => el.orderNumber === orderNumber,
    )
    if (!item) {
      historyData.value.push({
        orderNumber,
        finished: false,
      })
      localStorage.setItem(
        props.historyStorageKey,
        JSON.stringify(historyData.value),
      )
    }

    if (isDownloadImage.value) {
      download()
    }

    if (props.fastKey === 'qualityScan' && printDevice.value && isPrint.value) {
      await getPrintData()
    }

    if (props.fastKey === 'productionScan') {
      await setData(detail.value.id.toString(), 'auto')
    }
    playAudio('weight_search_success')

    trackingNumberRef.value && trackingNumberRef.value.focus()
    TrackingNumber.value = ''
  } catch (e) {
    console.error(e)
    trackingNumberRef.value && trackingNumberRef.value.focus()
    TrackingNumber.value = ''
  }
}
const onOpened = () => {
  trackingNumberRef.value && trackingNumberRef.value.focus()
  if (!isAutoSure.value && ['qualityScan'].includes(props.fastKey)) {
    ElMessageBox.confirm('请注意自动完成上一单未勾选', '提示', {
      type: 'warning',
      confirmButtonText: '跳过提示',
      cancelButtonText: '取消',
    }).catch(() => {})
  }
}
// function setProductMark(productMark: string) {
//   if (!productMark) return ''
//   if (productMark === 'custom_normal') return 'CB'
//   if (productMark === 'normal') return 'G'
//   return ''
// }
</script>
<style lang="scss" scoped>
.detail-div {
  display: flex;
  height: 100%;
  flex-direction: column;
  justify-content: space-between;

  .detail-content {
    display: flex;
    width: 100%;
  }

  .right {
    width: 730px;
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 30px;
    padding: 30px 0;

    .btn {
      margin: 20px 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 50px;
      width: 100%;

      .btn-sure,
      .btn-down {
        width: 49%;
        position: relative;

        .check {
          position: absolute;
          width: 144px;
          height: 100%;
          background: transparent;
          display: flex;
          align-items: center;
          justify-content: center;
          right: 0;
          top: 1px;
        }
      }
    }

    .div-text {
      .div-content {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        align-items: flex-start;
        padding: 15px 10px;
        box-sizing: border-box;
        position: relative;
        border: 1px solid #ececec;

        .div-item {
          width: 50%;
          margin-bottom: 10px;
          display: flex;
          align-items: center;
          height: 36px;
          line-height: 36px;

          .div-item-label {
            display: inline-block;
            text-align: right;
            width: 120px;
          }
          .div-item-value {
            flex: 1;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;

            &.with-copy {
              display: flex;
              align-items: center;
              min-width: 0;
            }

            .div-item-value-text {
              flex: 1;
              min-width: 0;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .copy-icon {
              flex-shrink: 0;
              margin-left: 6px;
              cursor: pointer;
              color: #909399;
            }
          }
        }
      }

      b {
        position: relative;
        background: white;
        top: 9px;
        left: 13px;
        padding: 0 10px;
        font-size: 18px;
        color: black;
        z-index: 3;
      }
    }

    .input {
      display: flex;
      align-items: center;
    }
  }

  .left {
    flex: 1;
    flex-shrink: 0;
    margin-right: 20px;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;

    .left-image {
      display: flex;
      height: 100%;
      flex-direction: column;
      justify-content: center;

      img {
        height: auto;
        width: 100%;
        max-height: 90%;
        object-fit: contain;
      }

      b {
        color: black;
        font-size: 18px;
        margin-bottom: 15px;
      }
    }

    .left-images {
      display: flex;
      width: 95%;
      height: 100%;
      flex-direction: column;

      b {
        color: black;
        text-align: center;
        margin-bottom: 15px;
      }
    }
  }
}

.left-images {
  :deep(.el-carousel__container) {
    height: 100%;
  }
}

.btn {
  position: relative;

  .btn-sure,
  .btn-down {
    &:has(.check) {
      :deep(.el-button span) {
        position: relative;
        left: -30px;
      }
    }
  }

  .check {
    :deep(.el-checkbox__inner) {
      background-color: transparent !important;
      border-color: white !important;
      width: 12px;
      height: 12px;
    }

    :deep(.el-checkbox__inner::after) {
      left: 3px;
    }

    :deep(.el-checkbox__label) {
      padding-left: 5px;
      font-size: 12px;
      color: white !important;
    }
  }
}
</style>
