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

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 () => {
    const code = getLastSegment(productionOrderNumber.value)
    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.subOrderNumber === code1)
      if (rowData) {
        rowData.orderNumber = item.orderNumber
        break
      }
    }
    if (rowData) {
      currentRow.value = rowData
      const unShipmentNum =
        (rowData.num || 0) -
        (rowData.shipmentNum || 0) +
        (rowData.notPassNum || 0)
      if (unShipmentNum > (rowData.count || 0)) {
        rowData.count = (rowData.count || 0) + 1
        playAudio('picking_check_success')
        // if (+rowData.count > 1) {
        //   ElMessageBox.confirm(`该产品未发数为${rowData.count}件`, '重要提示', {
        //     confirmButtonText: '确定',
        //     type: 'warning',
        //   }).catch(() => {
        //   })
        // }
      } else {
        playAudio('picking_beyond')
        ElMessage({
          message: '拣货数不能大于未发数',
          type: 'warning',
          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.subOrderNumber === code1) {
        item.count = 1

        // if (+item.count > 1) {
        //   ElMessageBox.confirm(`该产品未发数为${item.count}件`, '重要提示', {
        //     confirmButtonText: '确定',
        //     type: 'warning',
        //   }).catch(() => {
        //   })
        // }

        currentRow.value = item
        if (currentRow.value) {
          currentRow.value.orderNumber = data.orderNumber
        }
      }
    }
    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 = {
          erpSubOrderNumber: jj.erpSubOrderNumber,
          subOrderNumber: jj.subOrderNumber,
          sendOutQuantity: jj.count,
          version: jj.version,
        }
        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,
  }
}
