<template>
  <ElDialog
    v-model="visible"
    title="播种墙配货"
    fullscreen
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="handleClose"
    style="top: 60px"
    modal-class="pod-make-order-dialog"
    @opened="handleOpened"
    @close="onClose"
  >
    <template #header>
      <div class="title">
        <span>播种墙配货</span>
        <span v-if="socketConnect === 'online'" class="online">[在线]</span>
        <span v-else class="offline">[离线]</span>
        <ElButton
          v-if="socketConnect === 'offline'"
          type="success"
          size="small"
          :icon="Refresh"
          @click="reconnectWebSocket"
        >
          刷新
        </ElButton>
      </div>
    </template>
    <div class="pod-make-order-content">
      <div class="left-content">
        <div class="head-form">
          <div class="form-item">
            <ElSelect
              v-model="sheetPrinter"
              placeholder="请选择打印机"
              style="width: 200px"
              @change="handlePrinterChange"
            >
              <ElOption
                v-for="item in printDeviceList"
                :key="item"
                :label="item"
                :value="item"
              />
            </ElSelect>
          </div>
          <div class="form-item">
            <ElSelect
              v-model="warehouseId"
              placeholder="请选择仓库"
              style="width: 200px"
              @change="handleWarehouseChange"
            >
              <ElOption
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </ElSelect>
          </div>
          <div class="form-item" style="flex: 1">
            <ElInput
              ref="productionOrderRef"
              v-model="productionOrder"
              placeholder="请输入生产单号"
              clearable
              style="width: 100%"
              @keyup.enter="handleSearch"
            />
          </div>
          <div class="form-item">
            <ElButton type="primary" @click="handleSearch">查询</ElButton>
          </div>
          <!-- <div class="form-item">
            <ElButton type="danger" @click="clearAllBox">清空所有箱子</ElButton>
          </div> -->
        </div>
        <div class="basic-info">
          <div class="basic-info-item">
            <span>物流跟踪号：</span>
            <span>{{ podOrderDetailsData?.trackingNumber }}</span>
          </div>
          <div class="basic-info-item">
            <span>店铺单号：</span>
            <span>{{ podOrderDetailsData?.shopNumber }}</span>
          </div>
          <div class="basic-info-item">
            <span>商品总数量：</span>
            <span>{{ podOrderDetailsData?.purchaseNumber }}</span>
          </div>
          <div class="basic-info-item">
            <span>拣货数量：</span>
            <span>{{ podOrderDetailsData?.pickingNumber }}</span>
          </div>
          <!-- <div class="basic-info-item">
            <span>物流公司：</span>
            <span></span>
          </div>
          <div class="basic-info-item">
            <span>物流方式：</span>
            <span></span>
          </div> -->
          <div class="basic-info-item">
            <span>发货备注：</span>
            <span>{{ podOrderDetailsData?.remark }}</span>
          </div>
          <div class="basic-info-item">
            <span>订单号：</span>
            <span>{{ podOrderDetailsData?.factoryOrderNumber }}</span>
          </div>
        </div>

        <div class="table-content">
          <TableView
            ref="tableRef"
            :paginated-data="podOrderDetailsData?.productList || []"
            :columns="podOrderDetailsColumns"
            highlight-current-row
            @row-click="handleRowClick"
          >
            <template #image="{ row }">
              <div style="display: flex; flex-wrap: nowrap">
                <div
                  v-for="img in row.productMark !== 'normal' &&
                  row.productMark !== 'custom_normal'
                    ? row.previewImgs
                    : [{ url: row.variantImage }]"
                  :key="img"
                  style="cursor: pointer; margin-right: 5px; flex: 1"
                  @click.stop="handleCurrentChange(img.url)"
                >
                  <img v-if="img.url" :src="img.url" alt="" />
                </div>
              </div>
            </template>
            <template #verifyResult="{ row }">
              <el-icon
                v-if="row.power"
                style="color: #00cc00; font-size: 24px; font-weight: 900"
              >
                <Check />
              </el-icon>
            </template>
          </TableView>
        </div>
      </div>
      <div class="middle-content">
        <div class="box-top">
          <div class="box-top-item">
            <span class="box-top-item-box-index">
              {{ boxIndex }}
            </span>
            <span class="box-top-item-box-index-text">号箱</span>
            <template v-if="pickFlag">
              <strong
                style="
                  font-size: 60px;
                  color: #00ff00;
                  display: inline-block;
                  text-align: center;
                  width: 90px;
                "
              >
                {{ podOrderDetailsData?.purchaseNumber }}
              </strong>
              <span style="font-size: 30px">{{ '件已配齐' }}</span>
            </template>
            <template v-else>
              <span style="font-size: 30px">放入第</span>
              <div class="box-top-item-box-index-number">
                {{ podOrderDetailsData?.pickingNumber }}
              </div>
              <span style="font-size: 30px">件商品</span>
            </template>
          </div>
          <div class="box-top-item-status">
            <span
              v-if="
                podOrderDetailsData?.pickingNumber &&
                podOrderDetailsData?.purchaseNumber &&
                podOrderDetailsData?.pickingNumber ===
                  podOrderDetailsData?.purchaseNumber
              "
            >
              <span v-if="podOrderDetailsData?.printResult">
                面单{{ renderPrintResult(podOrderDetailsData?.printResult) }}
              </span>
              <span v-else>面单打印中。。。</span>
            </span>
            <span v-else>验货中。。。</span>
          </div>
          <div class="box-top-item-btn">
            <ElButton
              type="primary"
              @click="podOrderDetailsData && print(podOrderDetailsData, true)"
              >手动打印
            </ElButton>
            <ElButton type="primary" @click="printNormal">普货拣货 </ElButton>
            <ElButton type="success" @click="handlePrintFinish"
              >打单完成
            </ElButton>
            <ElButton type="danger" @click="handleClearBox">清空箱子</ElButton>
          </div>
          <div
            v-if="
              podOrderDetailsData?.productList?.length &&
              podOrderDetailsData?.productList?.length > 1
            "
            class="multiple-title"
          >
            <span class="multiple-title-text">多</span>
          </div>
        </div>
        <div class="order-image">
          <img :src="coverImage" alt="" />
        </div>
      </div>
      <div class="right-content">
        <div class="box-list">
          <div
            v-for="(item, index) in podBoxList"
            :key="item.box"
            class="box-list-item"
            :class="{
              active: item.box && boxIndex == item.box,
              isNull: !item.data,
              // badge: handleProduct(item.data || {}),
            }"
            @click="handleBoxClick(item)"
          >
            <span style="font-weight: bold" :title="index + 1 + '号箱'">
              {{ index + 1 }}
            </span>
            <span v-if="item.data" class="number">
              {{ item.data.pickingNumber }}/{{ item.data.purchaseNumber }}
            </span>
            <div
              v-if="
                item.data &&
                item.data.productList?.some(
                  (e) =>
                    e.productMark === 'custom_normal' ||
                    e.productMark === 'normal',
                )
              "
              class="cb-product-mark"
            >
              <div class="red-circle"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </ElDialog>
</template>

<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import useLodop from '@/utils/hooks/useLodop'
import TableView from '@/components/TableView.vue'
import type { WebSocketMessage } from '@/utils/websocket'
import {
  OrderData,
  PodMakeOrderData,
  ProductList,
  IorderItem,
} from '@/types/api/podMakeOrder'
import useOrderStore from '@/store/cnOrder'

import {
  getPackingCnDataApi,
  clearBoxApi,
  getPodBoxListApi,
  submitInspectionApi,
  printNormalPdf,
} from '@/api/podCnOrder'
import useUserStore from '@/store/user'
import { Check, Refresh } from '@element-plus/icons-vue'
import socket from '@/utils/cnWebsocket'
import { WarehouseListData } from '@/types/index'
import { ElMessage } from 'element-plus'
import { filePath } from '@/api/axios.ts'

const { getCLodop } = useLodop()

const props = defineProps<{
  modelValue: boolean
  printOrder: (data: OrderData, callback: (status: boolean) => void) => void
  warehouseList: WarehouseListData[]
}>()
const emit = defineEmits([
  'update:modelValue',
  'set-printer',
  'refresh',
  'set-warehouseId',
])
const visible = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  },
})

const printDeviceList = ref<string[]>([])
const sheetPrinter = ref<string>('')
const productionOrder = ref<string>('')
const podOrderDetailsData = ref<OrderData>()
const podOrderDetailsColumns = computed(() => [
  {
    label: '图片',
    prop: 'image',
    width: 250,
    slot: 'image',
    align: 'center',
    fixed: 'left',
  },
  {
    label: '生产单号',
    prop: 'podJomallCnNo',
    showOverflowTooltip: true,
    width: 150,
    align: 'center',
  },

  {
    label: '库存SKU',
    prop: 'thirdSkuCode',
    showOverflowTooltip: true,
    width: 180,
    align: 'center',
  },
  {
    label: 'variant SKU',
    prop: 'variantSku',
    showOverflowTooltip: true,
    width: 150,
    align: 'center',
  },
  {
    label: '商品名称',
    showOverflowTooltip: true,
    width: 200,
    prop: 'productName',
  },

  {
    label: '购买数量',
    prop: 'purchaseNumber',

    width: 90,
    fixed: 'right',
    align: 'center',
  },
  {
    label: '拣货数量',
    prop: 'count',
    width: 90,
    fixed: 'right',
    align: 'center',
  },
  {
    label: '验证结果',
    slot: 'verifyResult',
    width: 90,
    fixed: 'right',
    align: 'center',
  },
])
const boxChange = ref<boolean>(false)
const boxIndex = ref<number | null>(null)
const orderStore = useOrderStore()
const isLock = ref<boolean>(false)
const productionOrderRef = ref()
const socketConnect = computed(() => orderStore.socketConnect)
const podBoxList = computed(() => orderStore.podBoxList)
const coverImage = ref<string>('')
let currentCode = ''
const tableRef = ref()
watch(visible, async (value: boolean) => {
  if (value) {
    podOrderDetailsData.value = {}
    currentCode = ''
    currentItem.value = {}

    const localRaw = sessionStorage.getItem('locaclCnWarehouseId')
    const localId = localRaw ? JSON.parse(localRaw) : ''
    /* 先找一次，确认本地值是否存在于列表 */
    const hit = props.warehouseList.find((w) => w.id === localId)
    warehouseId.value = hit ? localId : props.warehouseList[0].id
    _warehouseId.value = hit ? localId : props.warehouseList[0].id

    if (userStore.user?.factory.id) {
      try {
        await socket.init(
          {
            account: userStore.user?.account.toString(),
            factoryNo: userStore.user?.factory.id.toString(),
          },
          messageChange,
        )
        socket.send({
          code: 'STARTORDERCN',
          factoryNo: userStore.user?.factory.id,
          warehouseId: warehouseId.value,
        })
      } catch (error) {
        console.error(error)
      }
    }
    console.log(
      8888,
      currentItem.value,
      currentCode,
      podOrderDetailsData.value,
      boxIndex.value,
    )

    initOrderDetailBox()
    initPrintDevice()
    const locaclPrinter = localStorage.getItem('sheetPrinter')
    if (locaclPrinter) sheetPrinter.value = JSON.parse(locaclPrinter)
    emit('set-printer', sheetPrinter.value)
  } else {
    if (userStore.user?.factory.id) {
      socket.send({
        code: 'ENDORDERCN',
        factoryNo: userStore.user?.factory.id,
        warehouseId: warehouseId.value,
      })
      socket.close()
    }
  }
})
watch(boxIndex, (value: number | null) => {
  if (value) {
    const bool = !boxChange.value
    boxChange.value = false
    console.log('boxChange', bool, value)
    const item = podBoxList.value?.find((item) => item.box === value)

    currentItem.value = item?.data as OrderData
    console.log('currentItem.value', currentItem.value)

    renderItemBox(bool)
  }
})
watch(
  podBoxList,
  (value) => {
    if (value) {
      const item = value.find((item) => item.box === podBoxIndex.value)
      console.log('podBoxList', value, podBoxIndex.value, item)
      currentItem.value = item?.data as OrderData
      if (item?.data) {
        renderItemBox(true)
      } else {
        if (boxIndex.value === podBoxIndex.value) {
          podOrderDetailsData.value = {}
          boxIndex.value = null
        }
      }
    }
  },
  { deep: true },
)
watch(
  () => podOrderDetailsData.value,
  (val) => {
    if (val && val.productList?.length)
      val.productList.forEach((el) => {
        if (!el.previewImgs) {
          if (
            el.productMark === 'custom_normal' ||
            el.productMark === 'normal'
          ) {
            el.previewImgs = [{ url: el.variantImage || '' }]
          } else {
            el.previewImgs = el.imageAry
              ? JSON.parse(el.imageAry)
              : [{ url: el.variantImage }]
          }
        }
      })
  },
  { deep: true },
)

const podBoxIndex = computed(() => orderStore.podBoxIndex)
const pickFlag = computed(() => {
  if (podOrderDetailsData.value?.productList) {
    return podOrderDetailsData.value?.productList.every((item) => item.power)
  }
  return false
})
let renderLock = false

const renderItemBox = (bool: boolean) => {
  if (
    !podBoxList.value ||
    podBoxList.value.length === 0 ||
    !boxIndex.value ||
    (bool && boxIndex.value !== podBoxIndex.value)
  )
    return
  if (renderLock) return
  renderLock = true
  let boxItem = podBoxList.value.find((item) => item.box === boxIndex.value)
  if (!boxItem) boxItem = { data: { productList: [] } }
  const { data } = boxItem
  data?.productList?.forEach((el) => {
    if (!el.previewImgs || !el.previewImgs.length) {
      if (el.productMark === 'custom_normal' || el.productMark === 'normal') {
        el.previewImgs = [{ url: el.variantImage || '' }]
      } else {
        try {
          el.previewImgs = JSON.parse(el.imageAry || '[]')
        } catch {
          console.log('生产订单：', el)

          // 只有是有效URL才创建对象
          el.previewImgs = el.imageAry?.startsWith?.('http')
            ? [{ url: el.imageAry, sort: 1, title: '正' }]
            : []
        }
      }
    }
  })
  if (!data) {
    renderLock = false
    currentCode = ''
    podOrderDetailsData.value = {}
    return
  }
  const { productList = [] } = data

  const pickingNumber = productList.reduce((prev, product) => {
    return prev + (product.count || 0)
  }, 0)
  data.pickingNumber = pickingNumber
  // coverImage.value = productList[0].previewImgs?.[0]?.url || ''
  for (const product of productList) {
    if (product.count === product.purchaseNumber) {
      product.power = true
    }
  }
  if (currentCode) {
    if (!currentCode.startsWith('JM')) {
      const parts = currentCode.split('_')
      currentCode =
        parts.length > 3 && parts[3].startsWith('CNPSC')
          ? parts[3]
          : parts.length > 1
          ? currentCode
          : parts[0]
    }

    console.log(540, currentCode)

    for (const product of productList) {
      if (
        product.podJomallCnNo === currentCode ||
        product.thirdSkuCode === currentCode
      ) {
        coverImage.value = product.previewImgs?.[0]?.url || ''
        nextTick(() => {
          tableRef.value?.setCurrentRow(product)
        })
        break
      }
    }
    currentCode = ''
  }

  podOrderDetailsData.value = data
  if (productList.every((item) => item.power)) {
    print(data, false, () => {
      renderLock = false
    })
  } else {
    renderLock = false
  }
}
const messageChange = (data: WebSocketMessage) => {
  if (!data) return
  const { code, ...more } = data

  if (code === 'FACTORY_POD_CN_PRINT_ORDER') {
    try {
      if (typeof more.txt === 'string') {
        console.log(
          '%conWebSocketMessage',
          'font-size: 20px; color: red;',
          JSON.parse(more.txt),
        )
      }
    } catch (e) {
      console.error(e)
    }
    setPodBoxList(more)
  }
}
const setPodBoxList = (data: WebSocketMessage) => {
  const obj = data.txt
  if (obj && typeof obj === 'string') {
    const parsedData = JSON.parse(obj)
    orderStore.setPodBoxList(parsedData)
  }
}

const printNormal = async () => {
  const arr: (number | undefined)[] = []
  ;(podBoxList.value || []).forEach((item: PodMakeOrderData) => {
    if (item.data) {
      if (item.data.productList && item.data.productList.length > 0) {
        const flag = item.data.productList.some((item1) => {
          return (
            item1.productMark == 'normal' ||
            item1.productMark == 'custom_normal'
          )
        })
        if (flag) {
          arr?.push(item.data?.id)
        }
      }
    }
  })
  if (!arr.length) {
    ElMessage.warning('暂无可打印的普货拣货单')
    return
  }
  const res = await printNormalPdf(arr.join())
  ElMessage.success('操作成功')
  window.open(filePath + res.message)
}
const initPrintDevice = () => {
  const lodop = getCLodop(null, null)
  if (!lodop) return
  const arr = []
  // 获取打印机数量
  const length = lodop.GET_PRINTER_COUNT()
  for (let i = 0; i < length; i++) {
    // 根据设备序号获取设备名
    const name = lodop.GET_PRINTER_NAME(i)
    arr.push(name)
  }
  console.log('arr', arr, lodop.GET_PRINTER_NAME(1))
  // 获取默认打印机
  sheetPrinter.value = lodop.GET_PRINTER_NAME(0)
  printDeviceList.value = arr
}
// const handleProduct = (val: OrderData) => {
//   if (val && val.productList && val.productList.length > 0) {
//     return val.productList?.some((item) => {
//       return item.productMark == 'normal'
//     })
//   } else {
//     return false
//   }
// }
const handleSearch = () => {
  const code = productionOrder.value
  if (!code) {
    ElMessage.warning('请输入生产单号')
    productionOrderRef.value.focus()
    return
  }
  if (isLock.value) {
    ElMessage.warning('请稍后再试')
    productionOrderRef.value.focus()
    return
  }
  productionOrder.value = ''
  isLock.value = true
  const everyPower = podOrderDetailsData.value?.productList?.every(
    (item) => item.power,
  )
  if (everyPower) {
    /**
     * printSuccess 打印成功
     * printFail 打印失败
     * printIng 打印中
     * notPrintSuccess 未能获取打印状态
     */
    if (podOrderDetailsData.value?.printResult === 'printSuccess') {
      submitInspection(() => {
        getPackingData(code)
      })
    } else {
      ElMessage.warning('未获取到打印结果')
      isLock.value = false
    }
  } else {
    getPackingData(code)
  }
}
const userStore = useUserStore()
const getPackingData = async (code: string) => {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  currentCode = code
  try {
    const factoryNo = userStore.user?.factory.id
    if (!factoryNo) {
      isLock.value = false
      productionOrder.value = ''
      return
    }
    const res = await getPackingCnDataApi(
      code,
      factoryNo,
      boxIndex.value,
      warehouseId.value,
    )
    if (res.code !== 200) {
      ElMessage.warning(res.message)
      isLock.value = false
      productionOrder.value = ''
      return
    }
    const { box } = res.data

    if (box) {
      boxIndex.value = box
    }
  } catch (error) {
    console.log(error)
  } finally {
    isLock.value = false
    productionOrder.value = ''
    loading.close()
    productionOrderRef.value.focus()
  }
}
// 提交打单
const submitInspection = async (callback: () => void) => {
  const factoryNo = userStore.user?.factory.id
  if (!factoryNo) {
    return
  }
  // const data = podOrderDetailsData.value?.id
  //   ? [
  //       {
  //         id: podOrderDetailsData.value.id,
  //         version: podOrderDetailsData.value?.version,
  //       },
  //     ]
  //   : []
  const data = (podOrderDetailsData.value?.orderParamList ?? []).map(
    (item: IorderItem) => ({
      id: item.id,
      version: item.dataVersion,
    }),
  )
  try {
    const res = await submitInspectionApi(
      data,
      warehouseId.value,
      boxIndex.value,
    )
    if (res.code !== 200) return
    ElMessage.warning(res.message)
    isLock.value = false
    coverImage.value = ''
    podOrderDetailsData.value = {}
    productionOrderRef.value.focus()

    callback && callback()
  } catch (error) {
    isLock.value = false
    productionOrderRef.value.focus()
    console.error(error)
  }
}
const isBillLading = ref<boolean>(false)
const initOrderDetailBox = async () => {
  const factoryNo = userStore.user?.factory.id
  if (!factoryNo) {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await getPodBoxListApi(factoryNo, warehouseId.value)
    if (res.code !== 200) {
      ElMessage.warning(res.message)
      return
    }
    console.log(res.data)
    res.data.forEach((r) => {
      r.data?.productList?.forEach((d) => {
        if (d.productMark === 'normal' || d.productMark === 'custom_normal') {
          d.previewImgs = [{ url: d.variantImage || '' }]
        } else {
          if (!d.previewImgs) {
            try {
              d.previewImgs = JSON.parse(d.imageAry || '[]')
            } catch {
              console.log('生产订单：', d)

              // 只有是有效URL才创建对象
              d.previewImgs = d.imageAry?.startsWith?.('http')
                ? [{ url: d.imageAry, sort: 1, title: '正' }]
                : []
            }
          }
        }
      })
    })
    console.log(res.data)
    orderStore.setPodBoxList({
      boxList: res.data,
      factoryNo,
      warehouseId: warehouseId.value,
    })
    const boxList = res.data.map((item) => {
      if (item.data) {
        if (!item.data.filePath) {
          isBillLading.value = true
        } else {
          isBillLading.value = false
        }
        const productList = item?.data?.productList || []
        const pickingNumber = productList.reduce((prev, product) => {
          if (product.count === product.purchaseNumber) {
            product.power = true
          }
          if (product.count) {
            return prev + product.count
          }
          return prev
        }, 0)

        item.data.pickingNumber = pickingNumber
      }
      return item
    })
    podOrderDetailsData.value =
      boxList.find((item) => item.data)?.data || undefined
    boxIndex.value = boxList.find((item) => item.data)?.box || null
    coverImage.value =
      podOrderDetailsData.value?.productList?.[0]?.previewImgs?.[0].url || ''

    if (
      podOrderDetailsData.value &&
      podOrderDetailsData.value.pickingNumber ===
        podOrderDetailsData.value.purchaseNumber
    ) {
      podOrderDetailsData.value.printResult = 'notPrintSuccess'
    }
    const pickFinished = boxList.filter((item) => {
      return item.data?.productList?.every((product) => product.power)
    })
    const boxs = pickFinished.map((item) => item.box)
    if (boxs.length > 0) {
      nextTick(async () => {
        try {
          await ElMessageBox.alert(
            `检测到${boxs.join(',')}号箱验货完成，请及时处理`,
            '提示',
            {
              confirmButtonText: '确定',
            },
          )
          productionOrderRef.value.focus()
        } catch (error) {
          productionOrderRef.value.focus()
          console.error(error)
        }
      })
    }

    renderLock = false
    productionOrder.value = ''
    isLock.value = false
    productionOrderRef.value.focus()
  } catch (error) {
    console.error(error)
  } finally {
    loading.close()
  }
}
const renderPrintResult = (printResult: string) => {
  switch (printResult) {
    case 'printSuccess':
      return '打印成功'
    case 'printFail':
      return '打印失败'
    case 'printIng':
      return '打印中'
    case 'notPrintSuccess':
      return '未能获取打印状态'
    default:
      return '未知'
  }
}
const handleOpened = () => {
  productionOrderRef.value.focus()
}
const handleClose = (done: () => void) => {
  console.log(999, currentItem.value)

  nextStep(() => {
    done()
  }, currentItem.value)
}
const onClose = () => {
  // orderStore.clearPodBox()
  emit('refresh')
}
// 下一步
const nextStep = async (callback: () => void, data?: OrderData) => {
  const everyPicked = podOrderDetailsData.value?.productList?.every(
    (item) => item.count === item.purchaseNumber,
  )
  console.log(854, data)

  if (
    everyPicked &&
    (podOrderDetailsData.value?.printResult === 'printSuccess' ||
      podOrderDetailsData.value?.printResult === 'notPrintSuccess')
  ) {
    try {
      await ElMessageBox.alert(
        `当前订单验货完成并打印面单成功，是否转至${
          data?.replaceShipment == 1 ? '待称重' : '已完成'
        }`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        },
      )
      submitInspection(() => {
        callback && callback()
      })
    } catch (error) {
      productionOrderRef.value.focus()
      console.error(error)
    }
  } else {
    callback && callback()
  }
}
const currentItem = ref<OrderData>({})
const handleBoxClick = (item: PodMakeOrderData) => {
  const { box, data } = item
  console.log('data11111111', data)

  currentItem.value = item as OrderData
  isBillLading.value = !data?.filePath
  nextStep(() => {
    if (!data) {
      ElMessage.warning('暂无数据')
      return
    }
    boxIndex.value = box || null
    boxChange.value = true
    productionOrderRef.value.focus()
  }, currentItem.value)
}
const handleClearBox = async () => {
  try {
    await ElMessageBox.alert('确定清空当前箱子吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
  } catch {
    return
  }
  const factoryNo = userStore.user?.factory.id
  if (!factoryNo) {
    return
  }
  try {
    const res = await clearBoxApi(
      factoryNo,
      boxIndex.value || null,
      warehouseId.value,
    )
    if (res.code !== 200) {
      ElMessage.warning(res.message)
      return
    }
    ElMessage.success('清空成功')
    orderStore.setPodBoxList({
      boxList: null,
      factoryNo,
      box: boxIndex.value || undefined,
      warehouseId: warehouseId.value,
    })
    boxIndex.value = null
    podOrderDetailsData.value = {}
    coverImage.value = ''
    productionOrderRef.value.focus()
  } catch (error) {
    productionOrderRef.value.focus()
    console.error(error)
  }
}
const handlePrintFinish = async () => {
  try {
    await ElMessageBox.alert('确定打单完成吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    submitInspection(() => {
      productionOrderRef.value.focus()
    })
  } catch {
    productionOrderRef.value.focus()
    return
  }
}
const handlePrinterChange = (value: string) => {
  emit('set-printer', value)
}

const print = (data: OrderData, forcePrint = false, callback?: () => void) => {
  const _boxIndex = boxIndex.value

  if (!forcePrint && data.printResult) {
    callback && callback()
    return
  }

  props.printOrder(data, (status: boolean) => {
    callback && callback()
    const item = podBoxList.value?.find((item) => item.box === _boxIndex)
    if (item && item.data) {
      if (status) {
        item.data.printResult = 'printSuccess'
      } else {
        item.data.printResult = 'printFail'
      }
    }
    const factoryNo = userStore.user?.factory.id
    if (!factoryNo) return
    orderStore.setPodBoxList({
      boxList: item ? item.data : null,
      factoryNo,
      box: _boxIndex || undefined,
      warehouseId: warehouseId.value,
    })
  })
}
// const clearAllBox = async () => {
//   try {
//     await ElMessageBox.alert('确定清空所有箱子吗？', '提示', {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//     })
//   } catch {
//     productionOrderRef.value.focus()
//     return
//   }
//   try {
//     const res = await clearAllBoxApi()
//     if (res.code !== 200) return
//     orderStore.setPodBoxList({
//       boxList: res.data,
//       factoryNo: userStore.user?.factory.id || '',
//       warehouseId: warehouseId.value,
//     })
//     productionOrderRef.value.focus()
//     podOrderDetailsData.value = {}
//     coverImage.value = ''
//     boxIndex.value = null
//   } catch (error) {
//     productionOrderRef.value.focus()
//     console.error(error)
//   }
// }
const handleRowClick = (row: ProductList) => {
  console.log(907, row)
  const previewImages =
    row.productMark !== 'normal' && row.productMark !== 'custom_normal'
      ? row.previewImgs
      : [{ url: row.variantImage }]
  coverImage.value = previewImages?.[0]?.url || ''
  productionOrderRef.value.focus()
}
const handleCurrentChange = (url: string) => {
  if (url) {
    coverImage.value = url || ''
  }
}
const warehouseId = ref<string | number>('')
const _warehouseId = ref<string | number>('')
const handleWarehouseChange = (value: string | number) => {
  if (!value) return
  if (_warehouseId.value !== warehouseId.value) {
    socket.send({
      code: 'ENDORDERCN',
      factoryNo: userStore.user?.factory.id,
      warehouseId: _warehouseId.value,
    })
  }
  warehouseId.value = value
  emit('set-warehouseId', value)
  socket.send({
    code: 'STARTORDERCN',
    factoryNo: userStore.user?.factory.id,
    warehouseId: warehouseId.value,
  })
  _warehouseId.value = value
  initOrderDetailBox()
}
const reconnectWebSocket = async () => {
  if (!userStore.user?.factory.id) return

  try {
    await socket.init(
      {
        account: userStore.user?.account.toString(),
        factoryNo: userStore.user?.factory.id.toString(),
      },
      messageChange,
    )
    socket.send({
      code: 'STARTORDERCN',
      factoryNo: userStore.user?.factory.id,
      warehouseId: warehouseId.value,
    })
  } catch (error) {
    console.error('WebSocket 重连失败:', error)
    ElMessage.error('WebSocket 重连失败，请稍后重试')
  }
}
</script>

<style scoped lang="scss">
.title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.online {
  color: green;
  font-size: 14px;
  font-weight: 600;
}

.offline {
  color: red;
  font-size: 14px;
  font-weight: 600;
}

.pod-make-order-content {
  display: flex;
  height: 100%;
  overflow: hidden;
  gap: 10px;
}

.left-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: calc(100% - 900px - 20px);
}

.head-form {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-content {
  flex: 1;
  overflow: hidden;
}

.middle-content {
  width: 500px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.right-content {
  width: 400px;
  overflow-y: auto;
  overflow-x: hidden;
}

.basic-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;

  .basic-info-item {
    display: flex;
    align-items: center;

    span:last-child {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

.box-top {
  position: relative;
  border: 1px solid #ddd;
  background: rgb(50 50 50);
  border-radius: 5px;
  padding: 10px 15px;
  box-sizing: border-box;
  font-size: 16px;
  color: #fff;
  overflow: hidden;
}

.multiple-title {
  position: absolute;
  top: 0;
  right: 0;

  &::after {
    position: absolute;
    top: -31px;
    right: -30px;
    content: '';
    border-width: 30px;
    border-style: solid;
    border-color: transparent transparent red transparent;
    transform: rotate(45deg);
  }

  .multiple-title-text {
    position: absolute;
    z-index: 2;
    color: #fff;
    left: -20px;
  }
}

.box-top-item {
  display: flex;
  height: 80px;
  align-items: center;
  margin-bottom: 10px;
}

.box-top-item-box-index {
  font-size: 60px;
  color: red;
  text-align: center;
  width: 120px;
  font-weight: 600;
}

.box-top-item-box-index-text {
  margin-right: 15px;
  font-size: 30px;
}

.box-top-item-box-index-number {
  font-size: 60px;
  color: red;
  display: inline-block;
  text-align: center;
  width: 90px;
  font-weight: 600;
}

.box-top-item-status {
  margin-bottom: 15px;
}

.order-image {
  flex: 1;
  overflow: hidden;
  border: 1px solid #ddd;
  background: #eee;
}

.box-list {
  display: grid;
  grid-template-columns: repeat(7, 50px);
  gap: 8px;
  position: relative;
}

.box-list-item {
  position: relative;
  border: 1px solid #ddd;
  cursor: pointer;
  font-size: 18px;
  line-height: 30px;
  height: 46px;
  text-align: center;
  box-sizing: border-box;
  border-radius: 5px;

  &:not(.isNull) {
    background: #819aff;
    color: #fff;
  }

  &.active {
    background: #ff9900;
    color: #fff;
  }

  &.badge::after {
    position: absolute;
    content: '';
    right: 4px;
    top: 4px;
    width: 7px;
    height: 7px;
    border-radius: 50%;
    background-color: red;
  }

  .number {
    position: absolute;
    bottom: 3px;
    right: 0;
    left: 0;
    text-align: center;
    font-size: 12px;
    line-height: 14px;
    color: #ddd;
  }
}
.cb-product-mark {
  position: absolute;
  top: 0;
  right: 0;
  .red-circle {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: red;
  }
}
</style>
<style lang="scss">
.pod-make-order-dialog {
  .el-dialog {
    display: flex;
    flex-direction: column;
    height: calc(100% - 60px);
  }

  .el-dialog__body {
    flex: 1;
    overflow: hidden;
  }
}
</style>
