import { getQaOrderBySubOrderNumber, qaFinishedApi } from '@/api/order'
import { InspectionData, QaData, shopRemark } from '@/types/api/order'
import { useValue } from '@/utils/hooks/useValue'
import { showConfirm } from '@/utils/ui'
import { computed, ref } from 'vue'

export default function useQuarantine() {
  const [sourceData, resetOrderList] = useValue<QaData[]>([])
  const [currentRow, resetCurrentRow] = useValue<QaData>({})

  const quarantineVisible = ref(false)
  const qaCode = ref('')
  const shipmentUid = ref('')
  const qaInputRef = ref()
  const isLock = ref(false)
  const cloneRow = ref<QaData>({} as QaData)
  const activeTab = ref('all')
  const _sourceData = ref<QaData[]>([] as QaData[])
  const allTotal = ref(0)
  const dzjTotal = ref(0)
  const yzjTotal = ref(0)

  const confirmCheck = () => {
    quarantineVisible.value = true
    resetOrderList()
    resetCurrentRow()
    dzjTotal.value = 0
    shipmentUid.value = ''
    qaCode.value = ''
    yzjTotal.value = 0
    allTotal.value = 0
  }
  const isQaed = computed(() => {
    if (sourceData.value.length == 0) return false
    return sourceData.value.some((item) => item.isCheck)
  })

  const findAllIndex = (code: string) => {
    const indexList: number[] = []
    sourceData.value.forEach((el, index) => {
      if (el.factorySubOrderNumber === code && el.shipmentNum !== el.scansNum) {
        indexList.push(index)
      }
    })
    return indexList
  }
  const searchQaByOrderNumber = () => {

    const uid = shipmentUid.value
    const code = qaCode.value
    if (!code) {
      isLock.value = false
      playAudio('picking_warning')
      return ElMessage({
        message: '请录入质检单号',
        type: 'warning',
        offset: window.innerHeight / 2,
      })
    }
    if (isLock.value) {
      qaInputRef.value.focus()
      qaCode.value = ''
      shipmentUid.value = ''
      return
    }
    isLock.value = true
    const code1 = code?.split('_')[0]
    const index = sourceData.value.findIndex(
      (item) =>
        item.factorySubOrderNumber == code1 || item.subOrderNumber == code1,
    )
    // 如果扫单号没有包含当前的生产单号
    const isIncluned = sourceData.value.some(
      (item) =>
        item.factorySubOrderNumber == code1 || item.subOrderNumber == code1,
    )
    if (isQaed.value && !isIncluned) {
      saveQuarantine(() => {
        loadShipmentOrderByCode(code, uid)
      })
    } else {
      // 如果质检未完成
      // 查找是否已经存在
      const row = sourceData.value.find(
        (item) =>
          (uid === item.shipmentUid && (code1 === item.subOrderNumber || item.factorySubOrderNumber == code1)) || (!uid && (item.factorySubOrderNumber == code1 || item.subOrderNumber == code1)),
      )
      if (row) {
        // 质检数量不能大于发货数量
        const num = (row.passNum || 0) + (row.notPassNum || 0)
        if (num > (row.shipmentNum || 0)) {
          qaInputRef.value.focus()
          isLock.value = false
          qaCode.value = ''
          shipmentUid.value = ''
          playAudio('picking_beyond')
          return ElMessage({
            message: '质检数量不能大于发货数量',
            type: 'warning',
            offset: window.innerHeight / 2,
          })
        }
        const len = sourceData.value.filter(el => el.factorySubOrderNumber == code1 || code1 === el.subOrderNumber)

        const scansNum = sourceData.value[index].scansNum || 0
        const indexList = findAllIndex(code1)
        if (len.length > 1) {
          sourceData.value.forEach((el, i) => {
            console.log(el)
            if (indexList.length > 0 && i === indexList[0]) {
              sourceData.value[i]['scansNum'] = scansNum + 1
            }
          })

        } else {
          if (row.shipmentNum !== scansNum) {
            sourceData.value[index]['scansNum'] = scansNum + 1
          }
        }
        playAudio('picking_check_success')
        // row.passNum = row.shipmentNum
        qaInputRef.value.focus()
        currentRow.value = row
        cloneRow.value = JSON.parse(JSON.stringify(currentRow.value))
        isLock.value = false
        qaCode.value = ''
        shipmentUid.value = ''
      } else {
        loadShipmentOrderByCode(code, uid)
      }
    }
  }
  const loadShipmentOrderByCode = async (code: string, uid: string) => {
    try {
      const res = await getQaOrderBySubOrderNumber(code, uid)
      const code1 = code?.split('_')[0]
      res.data = res.data.map((item: QaData) => {
        return {
          ...item,
          scansNum: item.inspectionStatus ? item.passNum : 0,
          isCheck: item.inspectionStatus,
        }
      })
      // 删除旧的inspectionStatus
      res.data = res.data.map(({ inspectionStatus, ...rest }) => {
        console.log(inspectionStatus)
        return rest
      })
      res.data.sort((a, b) =>
        a.isCheck === b.isCheck ? 0 : a.isCheck ? 1 : -1,
      ) //false在前，true在后
      activeTab.value = 'all'
      sourceData.value = sourceData.value.concat(res.data)
      _sourceData.value = _sourceData.value.concat(res.data)
      allTotal.value = _sourceData.value.length
      dzjTotal.value = res.data.filter(
        (e) =>
          Number(e.shipmentNum || 0) !==
          Number(e.passNum || 0) + Number(e.notPassNum || 0),
      ).length
      yzjTotal.value = res.data.filter(
        (e) =>
          Number(e.shipmentNum || 0) ===
          Number(e.passNum || 0) + Number(e.notPassNum || 0),
      ).length
      const row = sourceData.value.find(item => {
        return (uid === item.shipmentUid && (code1 === item.subOrderNumber || item.factorySubOrderNumber == code1)) || (!uid && (item.factorySubOrderNumber == code1 || item.subOrderNumber == code1))
      })
      const index = sourceData.value.findIndex(item => {
        return (uid === item.shipmentUid && (code1 === item.subOrderNumber || item.factorySubOrderNumber == code1)) || (!uid && (item.factorySubOrderNumber == code1 || item.subOrderNumber == code1))
      })
      if (row) {
        // row.passNum += 1
        currentRow.value = row
        cloneRow.value = JSON.parse(JSON.stringify(currentRow.value))
        if (!row.inspectionStatus && !sourceData.value[index].scansNum) sourceData.value[index].scansNum = 1
      }
      qaInputRef.value.focus()
      isLock.value = false
      qaCode.value = ''
      shipmentUid.value = ''
      playAudio('picking_search_success')
    } catch (e) {
      qaInputRef.value.focus()
      isLock.value = false
      qaCode.value = ''
      shipmentUid.value = ''
      // showError(e)
      playAudio('picking_search_error')
    }
  }
  const toSaveQuarantine = async () => {
    await saveQuarantine(() => {
      sourceData.value = []
      _sourceData.value = []
    })
  }
  // 质检完成
  const saveQuarantine = async (callback?: () => void) => {
    try {
      const data: InspectionData[] = _sourceData.value
        .filter((e) => e.isCheck)
        .map((item) => ({
          notPassCount: item.notPassNum || 0,
          subOrderNumber: item.subOrderNumber || '',
          namespace: item.namespace || '',
          erpSubOrderNumber: item.erpSubOrderNumber || '',
          billNumber: item.billNumber || '',
          version: item.version || '',
          passCount: item.passNum || 0,
          remark: item.remark || '',
        }))
      await qaFinishedApi(data)
      // sourceData.value = []
      isLock.value = false
      qaInputRef.value.focus()
      qaCode.value = ''
      shipmentUid.value = ''
      currentRow.value = {}
      cloneRow.value = JSON.parse(JSON.stringify(currentRow.value))
      allTotal.value = 0
      yzjTotal.value = 0
      dzjTotal.value = 0
      callback && callback()
    } catch (e) {
      // showError(e)
    }
  }
  const onQaDialogOpened = () => {
    qaInputRef.value.focus()
  }
  const onChangeTab = (key: string) => {
    activeTab.value = key
    if (key == 'all') {
      sourceData.value = _sourceData.value
    } else if (key === 'dzj') {
      sourceData.value = _sourceData.value.filter((item) => !item.isCheck)
    } else if (key === 'yzj') {
      sourceData.value = _sourceData.value.filter((item) => item.isCheck)
    }
    const row = sourceData.value.find(
      (item) => item.subOrderNumber == cloneRow.value.subOrderNumber,
    )

    if (row) {
      currentRow.value = row
    } else {
      currentRow.value = {}
    }
  }
  const onRowClick = (row: QaData) => {
    currentRow.value = row
    cloneRow.value = JSON.parse(JSON.stringify(row))
  }
  const onSuccessQc = async () => {
    if (
      (currentRow.value.passNum || 0) + (currentRow.value.notPassNum || 0) >=
      (currentRow.value.shipmentNum || 0)
    ) {
      return ElMessage({
        message: '已质检',
        type: 'warning',
        offset: window.innerHeight / 2,
      })
    }
    try {
      await showConfirm(`该产品${currentRow.value.shipmentNum}件`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
    } catch {
      return
    }
    currentRow.value.passNum = currentRow.value.shipmentNum
    _sourceData.value.forEach((item) => {
      if (item.subOrderNumber === currentRow.value.subOrderNumber) {
        item.isCheck = true
      }
    })
    sourceData.value = _sourceData.value

    allTotal.value = _sourceData.value.length
    dzjTotal.value = _sourceData.value.filter((item) => !item.isCheck).length
    yzjTotal.value = allTotal.value - dzjTotal.value
    qaInputRef.value.focus()
    onChangeTab(activeTab.value)
  }
  // 新的onReissue
  const giveDelivery = (form: shopRemark) => {
    const resendNum = form.resendNum ?? 0
    if (Number(resendNum) > (currentRow.value.shipmentNum || 0)) {
      return ElMessage({
        message: '重发数量不能大于发货数量',
        type: 'warning',
        offset: window.innerHeight / 2,
      })
    }
    if (resendNum > 0) {
      currentRow.value.notPassNum = Number(form.resendNum)
      currentRow.value.passNum =
        (currentRow.value.shipmentNum || 0) - Number(form.resendNum)
      currentRow.value['remark'] = form.remark ?? null
      _sourceData.value.forEach((item) => {
        if (item.subOrderNumber === currentRow.value.subOrderNumber) {
          item.isCheck = true
        }
      })

      sourceData.value = _sourceData.value

      allTotal.value = _sourceData.value.length
      dzjTotal.value = _sourceData.value.filter((item) => !item.isCheck).length
      yzjTotal.value = allTotal.value - dzjTotal.value
    } else {
      return ElMessage({
        message: '重发数量必须大于0!',
        type: 'warning',
        offset: window.innerHeight / 2,
      })
    }
  }
  const onReissue = () => {
    ElMessageBox.prompt('请输入重量', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /\d+/,
      inputErrorMessage: '请输入数字',
    }).then(({ value }) => {
      if (Number(value) > (currentRow.value.shipmentNum || 0)) {
        return ElMessage({
          message: '重发数量不能大于发货数量',
          type: 'warning',
          offset: window.innerHeight / 2,
        })
      }
      currentRow.value.notPassNum = Number(value)
      currentRow.value.passNum =
        (currentRow.value.shipmentNum || 0) - Number(value)

      _sourceData.value.forEach((item) => {
        if (item.subOrderNumber === currentRow.value.subOrderNumber) {
          item.isCheck = true
        }
      })

      sourceData.value = _sourceData.value

      allTotal.value = _sourceData.value.length
      dzjTotal.value = _sourceData.value.filter((item) => !item.isCheck).length
      yzjTotal.value = allTotal.value - dzjTotal.value
    })
  }
  /**
   * 拣货
   * 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 {
    quarantineVisible,
    qaCode,
    shipmentUid,
    qaInputRef,
    allTotal,
    dzjTotal,
    yzjTotal,
    currentRow,
    sourceData,
    activeTab,
    confirmCheck,
    searchQaByOrderNumber,
    saveQuarantine,
    toSaveQuarantine,
    onQaDialogOpened,
    onChangeTab,
    onSuccessQc,
    onReissue,
    onRowClick,
    giveDelivery,
  }
}
