<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>{{ props.title }}</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-if="props.wallType === 'sort'"
              v-model="sortingAreaId"
              placeholder="请选择配货区"
              style="width: 250px"
              @change="handleSortingAreaChange"
            >
              <ElOption
                v-for="item in sortingAreaList"
                :key="item.id"
                :label="item.areaName + ' - ' + item.warehouseName"
                :value="item.id"
              />
            </ElSelect>
            <ElSelect
              v-else
              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="
                props.wallType === 'us'
                  ? '请输入生产单号'
                  : props.wallType === 'sort'
                  ? '请输入操作单号/生产单号'
                  : '请输入操作单号'
              "
              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
                v-if="row.previewImgs?.length"
                style="display: flex; flex-wrap: nowrap"
              >
                <div
                  v-for="img in row.previewImgs"
                  :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="right-panel">
        <div v-if="props.wallType === 'sort'" class="sorting-area-content">
          {{
            (sortingAreaList.find((item) => item.id === sortingAreaId)
              ?.areaName || '') +
            ' - ' +
            (sortingAreaList.find((item) => item.id === sortingAreaId)
              ?.warehouseName || '')
          }}
        </div>
        <div class="flex right-panel-body">
          <div class="middle-content">
            <div class="box-top">
              <div v-if="boxIndex !== 0" class="box-top-item">
                <span class="box-top-item-box-index">
                  {{ boxIndex }}
                </span>

                <span class="box-top-item-box-index-text">号箱</span>

                <span style="font-size: 30px; white-space: nowrap">放入第</span>
                <div
                  class="box-top-item-box-index-number"
                  :style="{
                    color:
                      podOrderDetailsData?.pickingNumber ===
                      podOrderDetailsData?.purchaseNumber
                        ? 'rgb(0, 255, 0)'
                        : '',
                  }"
                >
                  {{ podOrderDetailsData?.pickingNumber }}
                </div>
                <span
                  v-if="
                    podOrderDetailsData?.pickingNumber != null &&
                    podOrderDetailsData?.purchaseNumber != null &&
                    podOrderDetailsData.pickingNumber ===
                      podOrderDetailsData.purchaseNumber
                  "
                  style="font-size: 30px; white-space: nowrap"
                  >件已配齐</span
                >
                <span v-else style="font-size: 30px">件商品</span>
              </div>
              <div v-else class="box-top-item-box-index-text">
                单件商品<span style="color: rgb(0, 255, 0)">(配齐)</span
                >，不占用播种墙
              </div>
              <div class="box-top-item-status">
                <span
                  v-if="
                    ((props.wallType === 'sort' && isAutoPrint) ||
                      props.wallType !== 'sort') &&
                    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
                  v-if="wallType === 'us'"
                  type="primary"
                  @click="printNormal"
                  >普货拣货
                </ElButton>
                <ElButton type="success" @click="handlePrintFinish"
                  >打单完成</ElButton
                >
                <ElButton
                  :disabled="boxIndex === 0"
                  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,
                }"
                @click="handleBoxClick(item)"
              >
                <span style="font-weight: bold" :title="index + 1 + '号箱'">
                  {{ index + 1 }}
                </span>

                <span v-if="item.data?.pickingNumber" 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>
      </div>
    </div>
  </ElDialog>
</template>

<script setup lang="tsx">
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,
} from '@/types/api/podMakeOrder'
import useOrderStore from '@/store/order'
import {
  clearBoxApi,
  clearAllBoxApi,
  getPackingDataApi,
  getPodBoxListApi,
  submitInspectionApi,
  printNormalPickPdfApi,
} from '@/api/podUsOrder'
import { getSortingRuleListApi } from '@/api/order'
import useUserStore from '@/store/user'
import { Check, Refresh } from '@element-plus/icons-vue'
import socket from '@/utils/websocket'
import { WarehouseListData } from '@/types/index'
import { filePath } from '@/api/axios.ts'
import { ElButton, ElIcon, ElTag } from 'element-plus'
import { BaseRespData } from '@/types/api'
import type { SortingList } from '@/types/api/order'

const { getCLodop } = useLodop()

const props = withDefaults(
  defineProps<{
    modelValue: boolean
    printOrder: (data: OrderData, callback: (status: boolean) => void) => void
    warehouseList: WarehouseListData[]
    isNewOrder?: boolean
    wsOpenCode?: string
    wsCloseCode?: string
    initUrl?: string
    wallType?: 'print' | 'sort' | 'us'
    title?: string
  }>(),
  {
    isNewOrder: false,
    wsOpenCode: 'STARTORDER',
    wsCloseCode: 'ENDORDER',
    initUrl: 'factory/podJomallOrderUs/local/getPodBoxOrderDetails',
    wallType: 'us',
    title: '播种墙配货',
  },
)
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 operationStatusMap: Record<string, string> = {
  PENDING_PACKING: '待配货',
  PENDING_SCHEDULE: '待排单',
  PENDING_REPLENISH: '待补胚',
  PENDING_PICK: '待拣胚',
  IN_PRODUCTION: '生产中',
  PACKING_COMPLETED: '配货完成',
  COMPLETED: '已完成',
  CANCELLED: '已取消',
  ARCHIVE: '已归档',
}
const operationStatusTagMap: Record<
  string,
  {
    type?: 'success' | 'warning' | 'info' | 'danger' | 'primary'
    style?: { backgroundColor: string; color: string; borderColor: string }
  }
> = {
  PENDING_PACKING: { type: 'warning' },
  PENDING_SCHEDULE: { type: 'info' },
  PENDING_REPLENISH: {
    style: {
      backgroundColor: '#E6A23C',
      color: '#FFFFFF',
      borderColor: '#E6A23C',
    },
  },
  PENDING_PICK: {
    style: {
      backgroundColor: '#409EFF',
      color: '#FFFFFF',
      borderColor: '#409EFF',
    },
  },
  IN_PRODUCTION: { type: 'primary' },
  PACKING_COMPLETED: { type: 'success' },
  COMPLETED: { type: 'success' },
  CANCELLED: { type: 'danger' },
  ARCHIVE: {
    style: {
      backgroundColor: '#909399',
      color: '#FFFFFF',
      borderColor: '#909399',
    },
  },
}
const parseOperationNo = (operationNoWithStatus: string) => {
  const match = operationNoWithStatus.match(/^([^_]+)_(.+)$/)
  if (!match)
    return { operationNo: operationNoWithStatus, status: '', statusText: '' }
  const [, operationNo, status] = match
  const statusText = operationStatusMap[status] || status
  return { operationNo, status, statusText }
}
const podOrderDetailsColumns = computed(() => [
  {
    label: '图片',
    prop: 'image',
    width: 250,
    slot: 'image',
    align: 'center',
  },
  {
    label: props.wallType === 'us' ? '生产单号' : '操作单号',
    prop: props.wallType === 'us' ? 'podJomallUsNo' : 'operationNos',
    width: props.wallType === 'us' ? 150 : 180,
    align: 'center',
    render: (row: ProductList) => {
      return (
        <div>
          {props.wallType !== 'us' &&
            row.operationNos?.split(',').map((item) => {
              const { operationNo, status, statusText } = parseOperationNo(item)
              const { type, style } = operationStatusTagMap[status] || {}
              return (
                <div>
                  {operationNo}
                  {statusText && (
                    <ElTag
                      size="small"
                      type={type}
                      style={{ marginLeft: '6px', ...style }}
                    >
                      {statusText}
                    </ElTag>
                  )}
                </div>
              )
            })}
          {props.wallType === 'us' && row.podJomallUsNo}
        </div>
      )
    },
  },
  {
    label: '库存 SKU',
    prop: 'thirdSkuCode',
    width: 180,
    align: 'center',
  },
  {
    label: 'variant SKU',
    prop: 'variantSku',
    width: 160,
    align: 'center',
  },

  {
    label: '商品名称',
    prop: 'productName',
    minWidth: 100,
  },

  {
    label: '购买数量',
    prop: 'purchaseNumber',
    width: 90,
    align: 'center',
    fixed: 'right',
  },
  {
    label: '拣货数量',
    prop: 'count',
    width: 90,
    align: 'center',
    fixed: 'right',
  },
  {
    label: '验证结果',
    slot: 'verifyResult',
    width: 90,
    align: 'center',
    fixed: 'right',
  },
])
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(() => {
  return orderStore.podBoxList
})
const coverImage = ref<string>('')
watch(coverImage, (value) => {
  console.log('🍡🍡🍡🍡🍡coverImage changed:', value)
})
let currentCode = ''
const tableRef = ref()
watch(visible, async (value: boolean) => {
  if (value) {
    podOrderDetailsData.value = {}
    currentCode = ''
    if (props.wallType === 'sort') {
      await getSortingAreaList()
    }
    let localRaw = ''
    switch (props.wallType) {
      case 'us':
        localRaw = localStorage.getItem('locaclWarehouseId') || ''
        break
      case 'print':
        localRaw = localStorage.getItem('localNewWarehouseId') || ''
        break
      case 'sort':
        localRaw = localStorage.getItem('localSortingAreaId') || ''
        break
    }

    const localData = localRaw ? JSON.parse(localRaw) : ''
    // 配货分拣 存仓库+配货区
    if (props.wallType === 'sort') {
      const localSortingAreaId = localData.sortingAreaId
      const localWarehouseId = localData.warehouseId
      const hit = sortingAreaList.value.find(
        (item) =>
          item.id === localSortingAreaId &&
          item.warehouseId === localWarehouseId,
      )
      if (hit) {
        sortingAreaId.value = hit.id
        warehouseId.value = hit.warehouseId
        isAutoPrint.value = hit.autoPrint
      }
    } else {
      /* 先找一次，确认本地值是否存在于列表 */
      const hit = props.warehouseList.find((w) => w.id == localData)
      warehouseId.value = hit ? localData : props.warehouseList[0]?.id
      _warehouseId.value = hit ? localData : 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: props.wsOpenCode,
          factoryNo: userStore.user?.factory.id,
          warehouseId: warehouseId.value,
          packingId:
            props.wallType === 'sort' ? sortingAreaId.value : undefined,
        })
      } catch (error) {
        console.error(error)
      }
    }
    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: props.wsCloseCode,
        factoryNo: userStore.user?.factory.id,
        warehouseId: warehouseId.value,
        packingId: sortingAreaId.value,
      })
      socket.close()
    }
  }
})
watch(boxIndex, () => {
  // if (value) {

  const bool = !boxChange.value
  boxChange.value = false
  renderItemBox(bool)
  // }
})
watch(
  podBoxList,
  (value) => {
    if (value) {
      const item = value.find((item) => item.box === podBoxIndex.value)
      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)

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 {
        el.previewImgs = JSON.parse(el.imageAry || '[]')
      }
    }
  })
  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('USPSC')
          ? parts[3]
          : parts.length > 1
          ? parts[1]
          : parts[0]
    }
    console.log(540, currentCode)
    for (const product of productList) {
      if (
        product.podJomallUsNo === currentCode ||
        product.thirdSkuCode === currentCode ||
        (product.operationNos && product.operationNos.includes(currentCode))
      ) {
        if (coverImage.value !== product.previewImgs?.[0]?.url) {
          coverImage.value = product.previewImgs?.[0]?.url || ''
        }
        nextTick(() => {
          tableRef.value?.setCurrentRow(product)
        })
        break
      }
    }
    currentCode = ''
  } else {
    // 切换箱子，默认展示第一张图片
    // coverImage.value = productList[0]?.previewImgs?.[0]?.url || ''
  }

  podOrderDetailsData.value = data

  if (productList.every((item) => item.power)) {
    if (userStore.user?.id !== boxItem.fromUser) return
    // 配货分拣 非自动打单的配货区: 不打印 不打单完成； 自动打单的配货区: 打印成功后打单完成
    if (props.wallType === 'sort' && !isAutoPrint.value) {
      renderLock = false
      return
    }
    console.log('=======⭐⭐⭐打印=======')

    print(data, false, () => {
      console.log('⭐⭐⭐打印结果data.printResult', data.printResult)

      if (
        props.wallType === 'sort' &&
        isAutoPrint.value &&
        data.printResult === 'printSuccess'
      ) {
        console.log('⭐⭐⭐提交打单')
        submitInspection(() => {
          renderLock = false
        })
        return
      }
      renderLock = false
    })
  } else {
    renderLock = false
  }
}
const messageChange = (data: WebSocketMessage) => {
  if (!data) return
  const { code, ...more } = data

  // 扫码进箱
  if (
    code === 'POD_PRINT_ORDER' ||
    code === 'FACTORY_POD_ORDER_PRINT_ORDER' ||
    code === 'FACTORY_POD_ORDER_TOP_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)
    }
    console.log('WebSocketMessage', more)

    setPodBoxList(more)
  }
  // 清空箱子
  else if (
    code === 'POD_BOX_FLUSH' ||
    code === 'FACTORY_POD_ORDER_BOX_FLUSH' ||
    code === 'FACTORY_POD_ORDER_TOP_BOX_FLUSH'
  ) {
    initOrderDetailBox()
  }
}
const setPodBoxList = (data: WebSocketMessage) => {
  const obj = data.txt
  if (obj && typeof obj === 'string') {
    const parsedData = JSON.parse(obj)
    parsedData.fromUser = data.fromUser
    orderStore.setPodBoxList({
      url: props.initUrl,
      ...parsedData,
    })
  }
}
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 (props.wallType === 'sort' && !isAutoPrint.value) {
    getPackingData(code)
    return
  }
  if (everyPower) {
    /**
     * printSuccess 打印成功
     * printFail 打印失败
     * printIng 打印中
     * notPrintSuccess 未能获取打印状态
     */
    // 非配货分拣 打印成功提示；配货分拣：开启自动打单且打印成功，提交；配货分拣：不开启自动打单，不提示
    if (
      podOrderDetailsData.value?.printResult === 'printSuccess' &&
      (props.wallType !== 'sort' ||
        (props.wallType === 'sort' && isAutoPrint.value))
    ) {
      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
    }
    if (props.wallType !== 'sort' && !warehouseId.value) {
      return ElMessage.warning('请选择仓库')
    }
    let url = ''
    switch (props.wallType) {
      case 'us':
        url = 'factory/podJomallOrderUs/local/putPackingSafe'
        break
      case 'print':
        url = 'factory/podOrderPacking/local/putPackingSafe'
        break
      case 'sort':
        url = 'factory/podOrderPacking/top/putPackingSafe'
        break
    }
    let params = {}
    if (props.wallType === 'us') {
      params = {
        podJomallUsNo: code,
        box: boxIndex.value,
        factoryNo,
        warehouseId: warehouseId.value,
      }
    } else if (props.wallType === 'sort') {
      params = {
        podOperationNo: code,
        box: boxIndex.value,
        factoryNo,
      }
    } else {
      params = {
        podOperationNo: code,
        box: boxIndex.value,
        factoryNo,
        warehouseId: warehouseId.value,
      }
    }
    const res = await getPackingDataApi(url, params)

    if (res.code !== 200) {
      ElMessage.warning(res.message)
      isLock.value = false
      productionOrder.value = ''
      return
    }
    const { box, data, packingId, factoryNo: respFactoryNo } = res.data

    // 配货分拣 扫码
    if (props.wallType === 'sort') {
      const area = sortingAreaList.value.find((item) => item.id == packingId)
      const areaChanged =
        sortingAreaId.value != packingId ||
        (!!area && warehouseId.value != area.warehouseId)
      handleSortingAreaChange(
        packingId as number,
        respFactoryNo ?? factoryNo,
        'scan',
      )
      if (areaChanged) {
        await initOrderDetailBox('scan')
      }
    }

    boxChange.value = true
    boxIndex.value = box as number
    // 尝试修复线上扫码后大缩略图不更新问题
    {
      let parsedCode = code
      if (!parsedCode.startsWith('JM')) {
        const parts = parsedCode.split('_')
        parsedCode =
          parts.length > 3 && parts[3].startsWith('USPSC')
            ? parts[3]
            : parts.length > 1
            ? parts[1]
            : parts[0]
      }

      for (const product of data?.productList || []) {
        if (
          product.podJomallUsNo === parsedCode ||
          product.thirdSkuCode === parsedCode ||
          (product.operationNos && product.operationNos.includes(parsedCode))
        ) {
          if (!product.previewImgs || !product.previewImgs.length) {
            if (
              product.productMark === 'custom_normal' ||
              product.productMark === 'normal'
            ) {
              product.previewImgs = [{ url: product.variantImage || '' }]
            } else {
              product.previewImgs = product.imageAry
                ? JSON.parse(product.imageAry)
                : [{ url: product.variantImage || '' }]
            }
          }
          coverImage.value = product.previewImgs?.[0]?.url || ''
          console.log('🍉🍉🍉🍉getPackingData', coverImage.value)
          break
        }
      }
    }
    if (boxIndex.value == 0) {
      podOrderDetailsData.value = data as OrderData
      podOrderDetailsData.value.fromUser = userStore.user?.id
      if (podOrderDetailsData.value.productList?.length) {
        const list = podOrderDetailsData.value.productList
        for (const product of list) {
          if (product.count === product.purchaseNumber) {
            product.power = true
            print(data as OrderData, false, () => {
              renderLock = false
            })
          }
        }
        nextTick(() => {
          tableRef.value?.setCurrentRow(list[0])
        })
      }
    }
  } catch (error) {
    const err = error as BaseRespData<{
      inventory: number
      producingQuantity: number
      availableInventory: number
      thirdSkuCode?: string
    }>
    if (props.wallType !== 'us' && err?.code === 301) {
      loading.close()
      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,
        },
      )
    }
  } finally {
    isLock.value = false
    productionOrder.value = ''
    loading.close()
    productionOrderRef.value.focus()
  }
}
// 提交打单
const submitInspection = async (callback: () => void) => {
  const factoryNo = userStore.user?.factory.id
  console.log('⭐⭐⭐提交打单factoryNo', factoryNo)
  if (!factoryNo) {
    return
  }
  try {
    const url =
      props.wallType === 'us'
        ? 'factory/podJomallOrderUs/podPrintOrderComplete'
        : 'factory/podOrderPacking/podPrintOrderComplete'

    let params = {}
    if (props.wallType === 'us') {
      params = {
        orderId: podOrderDetailsData.value?.id,
      }
    } else {
      params = {
        orderParamList: [{ id: podOrderDetailsData.value?.id }],
      }
    }
    const res = await submitInspectionApi(
      url,
      params,
      boxIndex.value,
      warehouseId.value,
      sortingAreaId.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
    renderLock = false
    productionOrderRef.value.focus()
    console.error(error)
  }
}
const isBillLading = ref<boolean>(false)
const initOrderDetailBox = async (type: 'scan' | 'manual' = 'manual') => {
  const factoryNo = userStore.user?.factory.id
  if (!factoryNo) {
    return
  }
  if (props.wallType !== 'sort' && !warehouseId.value) {
    return ElMessage.warning('请选择仓库')
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const url = props.initUrl
    const res = await getPodBoxListApi(
      url,
      factoryNo,
      warehouseId.value,
      sortingAreaId.value,
    )
    if (res.code !== 200) {
      ElMessage.warning(res.message)
      return
    }

    orderStore.setPodBoxList({
      url,
      boxList: res.data,
      fromUser: userStore.user ? userStore.user.id : 0,
      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
    })
    const currentBox = boxIndex.value
    const currentBoxItem = currentBox
      ? boxList.find((item) => item.box === currentBox && item.data)
      : undefined
    const fallbackItem = boxList.find((item) => item.data)
    const targetItem = currentBoxItem || fallbackItem
    podOrderDetailsData.value = targetItem?.data || undefined
    boxIndex.value = targetItem?.box || null

    podOrderDetailsData.value?.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 }]
        }
      }
    })
    if (type !== 'scan') {
      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 (type === 'manual' && boxs.length > 0) {
      nextTick(async () => {
        // 切换箱子至验货完成的箱子
        boxChange.value = true
        boxIndex.value = boxs[0] as number
        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) => {
  nextStep(() => {
    done()
  })
}
const onClose = () => {
  emit('refresh')
}
// 下一步
const nextStep = async (callback: () => void) => {
  const everyPicked = podOrderDetailsData.value?.productList?.every(
    (item) => item.count === item.purchaseNumber,
  )
  if (
    everyPicked &&
    ((props.wallType === 'sort' && isAutoPrint.value) ||
      props.wallType !== 'sort') &&
    (podOrderDetailsData.value?.printResult === 'printSuccess' ||
      podOrderDetailsData.value?.printResult === 'notPrintSuccess')
  ) {
    try {
      await ElMessageBox.alert(
        `当前订单验货完成并打印面单成功，是否转至${
          props.wallType === 'sort' ? '待发货' : '已完成'
        }`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        },
      )
      submitInspection(() => {
        callback && callback()
      })
    } catch (error) {
      productionOrderRef.value.focus()
      console.error(error)
    }
  } else {
    callback && callback()
  }
}
const handleBoxClick = (item: PodMakeOrderData) => {
  const { box, data } = item
  if (box == 0) return
  isBillLading.value = !data?.filePath
  nextStep(() => {
    if (!data) {
      ElMessage.warning('暂无数据')
      return
    }
    boxIndex.value = box || null
    boxChange.value = true
    productionOrderRef.value.focus()
  })
}
const handleClearBox = async () => {
  try {
    if (!boxIndex.value) {
      ElMessage.warning('请选择箱子')
      return
    }
    await ElMessageBox.alert('确定清空当前箱子吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
  } catch {
    return
  }
  const factoryNo = userStore.user?.factory.id
  if (!factoryNo) {
    return
  }

  try {
    const url =
      props.wallType === 'us'
        ? 'factory/podJomallOrderUs/local/delPodBoxOrderDetailsByBox'
        : 'factory/podOrderPacking/local/delPodBoxOrderDetailsByBox'

    const res = await clearBoxApi(
      url,
      factoryNo,
      boxIndex.value || null,
      warehouseId.value,
      sortingAreaId.value,
    )
    if (res.code !== 200) {
      ElMessage.warning(res.message)
      return
    }
    ElMessage.success('清空成功')
    boxIndex.value = null
    podOrderDetailsData.value = {}
    coverImage.value = ''
    productionOrderRef.value.focus()
  } catch (error) {
    productionOrderRef.value.focus()
    console.error(error)
  }
}
const handlePrintFinish = async () => {
  if (podOrderDetailsData.value?.productList?.length) {
    const { productList } = podOrderDetailsData.value
    const bool = productList.some((el) => !el.power)
    if (bool) {
      try {
        await ElMessageBox.alert(
          '商品数量未配齐无法打单完成，请检查！',
          '提示',
          {
            confirmButtonText: '确定',
          },
        )
      } catch {
        return
      }
    } else {
      try {
        await ElMessageBox.alert('确定打单完成吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
        submitInspection(() => {
          productionOrderRef.value.focus()
        })
      } catch {
        productionOrderRef.value.focus()
        return
      }
    }
  } else {
    try {
      await ElMessageBox.alert('未检测到商品，请检查！', '提示', {
        confirmButtonText: '确定',
      })
    } catch {
      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'
      }
    }
    if (_boxIndex == 0) {
      if (status) {
        ;(podOrderDetailsData.value as OrderData).printResult = 'printSuccess'
      } else {
        ;(podOrderDetailsData.value as OrderData).printResult = 'printFail'
      }
    }
    const factoryNo = userStore.user?.factory.id
    if (!factoryNo) return
    if (!warehouseId.value) {
      return ElMessage.warning('请选择仓库')
    }
    orderStore.setPodBoxList({
      url: props.initUrl,
      fromUser: userStore.user ? userStore.user.id : 0,
      boxList: item ? (item.data as PodMakeOrderData[]) : null,
      factoryNo,
      box: _boxIndex || undefined,
      warehouseId: warehouseId.value,
    })
  })
}
const clearAllBox = async () => {
  try {
    await ElMessageBox.alert('确定清空所有箱子吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
  } catch {
    productionOrderRef.value.focus()
    return
  }
  try {
    const url =
      props.wallType === 'us'
        ? 'factory/podJomallOrderUs/local/delPodBoxOrderDetails'
        : 'factory/podOrderPacking/local/delPodBoxOrderDetails'
    const res = await clearAllBoxApi(
      url,
      warehouseId.value,
      userStore.user?.factory.id,
      sortingAreaId.value,
    )
    if (res.code !== 200) return
    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)
  coverImage.value = row.previewImgs?.[0]?.url || ''
  productionOrderRef.value.focus()
}
const handleCurrentChange = (url: string) => {
  if (url) {
    coverImage.value = url || ''
    console.log('🍉🍉🍉🍉handleCurrentChange', coverImage.value)
  }
}
const warehouseId = ref<string | number>('')
const _warehouseId = ref<string | number>('')
const sortingAreaList = ref<SortingList[]>([])
const sortingAreaId = ref<number | string>('')
const isAutoPrint = ref<boolean>(false) // 当前配货区是否自动打单
// 配货分拣 更新配货区
const syncSortingArea = (
  packingId: number | string,
  factoryNo: number | string,
) => {
  const currentArea = sortingAreaList.value.find((item) => item.id == packingId)
  if (!currentArea) return

  warehouseId.value = currentArea.warehouseId
  sortingAreaId.value = packingId
  isAutoPrint.value = currentArea.autoPrint
  socket.send({
    code: props.wsOpenCode,
    factoryNo,
    warehouseId: warehouseId.value,
    packingId: sortingAreaId.value,
  })
}
// 配货分拣 手动切换配货区
const handleSortingAreaChange = (
  value: string | number,
  factoryNo?: number | string,
  type: 'scan' | 'manual' = 'manual',
) => {
  const no = factoryNo ?? userStore.user?.factory.id
  if (!no) return
  syncSortingArea(value, no)
  emit('set-warehouseId', {
    warehouseId: warehouseId.value,
    sortingAreaId: sortingAreaId.value,
  })
  initOrderDetailBox(type)
}
// 手动切换仓库
const handleWarehouseChange = (value: string | number) => {
  if (!value) return
  if (_warehouseId.value !== warehouseId.value) {
    socket.send({
      code: props.wsCloseCode,
      factoryNo: userStore.user?.factory.id,
      warehouseId: _warehouseId.value,
    })
  }
  warehouseId.value = value
  emit('set-warehouseId', value)
  socket.send({
    code: props.wsOpenCode,
    factoryNo: userStore.user?.factory.id,
    warehouseId: warehouseId.value,
  })
  _warehouseId.value = value
  initOrderDetailBox()
}

const printNormal = async () => {
  const arr: (number | undefined)[] = []
  ;(podBoxList.value || []).forEach((item: PodMakeOrderData) => {
    if (item.data) {
      if (item.data.productList && item.data.productList.length > 0) {
        item.data.productList.forEach((item1) => {
          if (
            item1.productMark == 'normal' ||
            item1.productMark == 'custom_normal'
          ) {
            arr?.push(item1?.id)
          }
        })
      }
    }
  })
  if (!arr.length) {
    ElMessage.warning('暂无可打印的普货拣货单')
    return
  }
  const res = await printNormalPickPdfApi(arr.join())
  ElMessage.success('操作成功')
  window.open(filePath + res.message)
}

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: props.wsOpenCode,
      factoryNo: userStore.user?.factory.id,
      warehouseId: warehouseId.value,
      packingId: sortingAreaId.value,
    })
  } catch (error) {
    console.error('WebSocket 重连失败:', error)
    ElMessage.error('WebSocket 重连失败，请稍后重试')
  }
}

// 配货分拣 获取配货区列表
const getSortingAreaList = async () => {
  const res = await getSortingRuleListApi({})
  if (res.code !== 200) return
  sortingAreaList.value = res.data.records
  const defaultArea =
    sortingAreaList.value.find(
      (item) => item.defaultWarehouse === 1 && item.areaCode === 'AREA_0',
    ) || sortingAreaList.value[0]
  sortingAreaId.value = defaultArea.id
  warehouseId.value = defaultArea.warehouseId
  isAutoPrint.value = defaultArea.autoPrint || false
  emit('set-warehouseId', {
    warehouseId: warehouseId.value,
    sortingAreaId: sortingAreaId.value,
  })
}
</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;
}
.right-panel {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}
.right-panel-body {
  min-height: 0;
  overflow: hidden;
}
.sorting-area-content {
  border: 2px solid #666;
  padding: 10px;
  margin-bottom: 10px;
  width: 100%;
  height: 80px;
  font-size: 35px;
  color: red;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
}
.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;
  flex: 1;
  font-weight: 600;
  white-space: nowrap;
}
.box-top-item-box-index-text {
  margin-right: 15px;
  font-size: 30px;
  white-space: nowrap;
}
.box-top-item-box-index-number {
  font-size: 60px;
  color: red;
  display: inline-block;
  text-align: center;
  flex: 1;
  font-weight: 600;
}
.box-top-item-status {
  margin-bottom: 15px;
}
.order-image {
  flex: 1;
  overflow: auto;
  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;
  }
}
.fontStyle {
  font-size: 12px;
}
</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>
