import {
  ICompareObjects,
  OrderData,
  ProductList,
  ShipmentForm,
} from '@/types/api/order'
import { useValue } from '@/utils/hooks/useValue'
import { nextTick, ref } from 'vue'
import { ShipmentType } from '../Shipment.vue'
import { getOrderBySubOrderNumber, saveOrder } from '@/api/podOrder'
import { ShipmentOrderRes } from '@/types/api/podOrder'

export default function useShipment(callback?: () => void) {
  const [orderList, resetOrderList] = useValue<OrderData[]>([])
  const [shipmentForm, resetShipmentForm] = useValue<ShipmentForm>({
    shippingWay: '',
    carriageName: '',
    logisticsTracking: '',
    carriageAmount: '',
    namespace: '',
  })
  const firstResult = ref<ICompareObjects | null>(null)
  const shipmentFormRef = ref()
  const productionOrderNumber = ref('')
  const shipmentVisible = ref(false)
  const isLock = ref(false)
  const inputRef = ref()
  // const currentRow = ref<ProductList>()
  const currentRow = ref<ProductList | undefined>(undefined)
  const shipmentLoading = ref(false)
  const shipmentOrderRef = ref<ShipmentType>()
  const searchShipmentByOrderNumber = async () => {
    let code = productionOrderNumber.value
    // AAAB_60527128-9_1_JMSC250121017 新版示例
    // const regex = /^[A-Z]{4}_/ //是否以四个大写字母加下划线开头
    // if (regex.test(code)) {
    //   code =
    //     code.split('_')[0] + '-' + code.split('_')[code.split('_').length - 1]
    // }
    shipmentVisible.value = true
    if (!code) {
      isLock.value = false
      inputRef.value.focus()
      playAudio('picking_warning')
      return ElMessage({
        message: '请录入生产单号',
        type: 'warning',
        offset: window.innerHeight / 2,
      })
    }
    let rowData
    const code1 = code?.split('_')[0]
    for (const item of orderList.value) {
      // rowData = item.productList?.find((jj) => jj.factorySubOrderNumber === code1)
      rowData = item.productList?.find(
        (jj) => `${item.userMark}-${jj.thirdSubOrderNumber}` === code1,
      )
      if (rowData) {
        rowData.factoryOrderNumber = item.factoryOrderNumber
        break
      }
    }
    if (rowData) {
      currentRow.value = rowData
      const unShipmentNum =
        (rowData.num || 0) -
        (rowData.shipmentNum || 0) +
        (rowData.notPassNum || 0)
      if (rowData.isProduction) {
        if (unShipmentNum > (rowData.count || 0)) {
          rowData.count = (rowData.count || 0) + 1
          playAudio('picking_check_success')
        } else {
          playAudio('picking_beyond')
          ElMessage({
            message: '拣货数不能大于未发数',
            type: 'warning',
            offset: window.innerHeight / 2,
          })
        }
      } else {
        if (rowData.num !== rowData.shipmentNum) {
          playAudio('picking_beyond')
          ElMessage({
            message: `单号:${rowData.factorySubOrderNumber}未生产，请生产后再发货`,
            type: 'error',
            offset: window.innerHeight / 2,
          })
        }
      }
      inputRef.value.focus()
      productionOrderNumber.value = ''
      isLock.value = false
      await nextTick()
      if (shipmentOrderRef.value) {
        const rowEl = shipmentOrderRef.value.listRef?.querySelector(
          `div[data-id="${rowData.id}"]`,
        )
        if (!rowEl) return

        rowEl.scrollIntoView()
      }
    } else {
      getPackingData(code)
    }
  }
  const getPackingData = async (code: string) => {
    try {
      shipmentLoading.value = true
      const res = await getOrderBySubOrderNumber(code)
      if (res.data) {
        if (firstResult.value === null) {
          firstResult.value = res.data
          canJoin(res.data, code)
        } else {
          if (!compareObjects(firstResult.value, res.data)) {
            ElMessageBox.confirm('不能加入,地址信息不一致!', '重要提示', {
              confirmButtonText: '确定',
              type: 'warning',
            }).catch(() => {})
          } else {
            canJoin(res.data, code)
          }
        }
      }
      inputRef.value.focus()
      productionOrderNumber.value = ''
      isLock.value = false
    } catch (e) {
      productionOrderNumber.value = ''
      isLock.value = false
      inputRef.value.focus()
      //showError(e)
      playAudio('picking_search_error')
    } finally {
      shipmentLoading.value = false
    }
  }
  const canJoin = async (data: OrderData, code: string) => {
    const code1 = code?.split('_')[0]
    for (const item of data.productList || []) {
      item.count = 0
      // if (item.factorySubOrderNumber === code1) {
      if (`${data.userMark}-${item.thirdSubOrderNumber}` === code1) {
        if (item.isProduction) {
          item.count = 1
        } else {
          if (item.num !== item.shipmentNum) {
            playAudio('picking_beyond')
            ElMessage({
              message: `单号:${item.factorySubOrderNumber}未生产，请生产后再发货`,
              type: 'error',
              offset: window.innerHeight / 2,
            })
          }
        }
        currentRow.value = item
        if (currentRow.value) {
          currentRow.value.factoryOrderNumber = data.factoryOrderNumber
        }
      }
    }
    const index = orderList.value.findIndex((item) => item.id === data.id)
    if (index === -1) {
      orderList.value.unshift(data)
    }
    playAudio('picking_search_success')
    await nextTick()
    if (shipmentOrderRef.value) {
      const rowEl = shipmentOrderRef.value.listRef?.querySelector(
        `div[data-id="${currentRow.value?.id}"]`,
      )
      if (!rowEl) return

      rowEl.scrollIntoView()
    }
  }
  const compareObjects = (
    obj1: ICompareObjects,
    obj2: ICompareObjects,
  ): boolean => {
    const keysToCompare: (keyof ICompareObjects)[] = [
      'lanshouAddress',
      'lanshouName',
      'lanshouPhone',
      'lanshouPost',
      'lanshouRegion',
    ]
    return keysToCompare.every((key) => obj1[key] === obj2[key])
  } //将后面的查询结果和第一次的结果进行比较，相同才能加入，反之不能
  const saveShipment = async () => {
    if (orderList.value.length === 0) {
      return ElMessage({
        message: '请选择订单',
        type: 'warning',
        offset: window.innerHeight / 2,
      })
    }
    try {
      await shipmentFormRef.value?.validate()
    } catch {
      return
    }

    const isEqual = orderList.value.some(
      (item) => item.namespace === orderList.value[0].namespace,
    )
    if (!isEqual) {
      ElMessage({
        message: '请选择同一工厂的订单',
        type: 'warning',
        offset: window.innerHeight / 2,
      })
      return
    }
    const data: ShipmentOrderRes[] = []
    orderList.value.forEach((item) => {
      shipmentForm.value.namespace = item.namespace
      const order = []
      for (const jj of item.productList || []) {
        if (jj.count === 0) continue
        const subOrder = {
          factorySubOrderNumber: jj.factorySubOrderNumber,
          thirdSubOrderNumber: jj.thirdSubOrderNumber,
          sendOutQuantity: jj.count,
          version: jj.version as number,
          namespace: item.namespace,
        }
        order.push(subOrder)
      }
      if (order) {
        data.push(...order)
      }
    })
    try {
      const res = await saveOrder(data, shipmentForm.value)
      fetch(res.message || '')
      // .then((response) => {
      //   // 确保响应是 OK
      //   if (!response.ok) {
      //     throw new Error('网络响应错误')
      //   }
      //   // 返回图片的二进制数据（Blob）
      //   return response.blob()
      // })
      // .then((blob) => {
      //   const a = document.createElement('a')
      //   a.href = window.URL.createObjectURL(blob)
      //   a.target = '_blank'
      //   a.download = (res.message as string).split('/')[
      //     (res.message as string).split('/').length - 1
      //   ]
      //   a.click()
      // })
      // .catch((error) => {
      //   console.error('下载图片时出错:', error)
      // })
      ElMessage.success('发货成功')
      shipmentVisible.value = false
      callback && callback()
    } catch (e) {
      // showError(e)
    }
  }
  const confirmDelivery = async () => {
    shipmentVisible.value = true
    productionOrderNumber.value = ''
    firstResult.value = null //弹窗打开前先清空第一次的结果
    resetOrderList()
    resetShipmentForm()
  }
  const onShipmentDialogOpened = () => {
    inputRef.value?.focus()
    shipmentFormRef.value?.clearValidate()
  }
  /**
   * 拣货
   * picking_warning 输入错误
   * picking_beyond SKU数量超出
   * picking_check_success 验证成功
   * picking_search_error 查询失败
   * picking_search_success 查询成功
   */
  const playAudio = (key: string) => {
    const audio = new Audio()
    const audioPath = new URL(
      `../../../assets/audio/${key}.mp3`,
      import.meta.url,
    ).href
    audio.src = audioPath
    audio.play()
  }
  return {
    shipmentFormRef,
    shipmentOrderRef,
    productionOrderNumber,
    shipmentVisible,
    inputRef,
    shipmentForm,
    currentRow,
    shipmentLoading,
    orderList,
    searchShipmentByOrderNumber,
    saveShipment,
    confirmDelivery,
    onShipmentDialogOpened,
  }
}
