import { computed, ref, type Ref } from 'vue'
import BigNumber from 'bignumber.js'
import { ElMessage } from 'element-plus'
import { getBySkuAndUserMarkApi } from '@/api/warehouse'
import type {
  InterProductList,
  InterWarehouseDetail,
  InterskuList,
} from '@/types/api/warehouse'

interface UserMark {
  userId: number
  userMark: string
  userName: string
}

interface UseReceiptProductDialogOptions {
  editForm: Ref<InterWarehouseDetail>
  otherPurchaseData: Ref<InterProductList[]>
  userMark: Ref<number>
  batchUserMark: Ref<number>
  importUserMark: Ref<number>
  selectSku: Ref<string>
  userMarkList: Ref<UserMark[]>
}

export function useReceiptProductDialog(options: UseReceiptProductDialogOptions) {
  const {
    editForm,
    otherPurchaseData,
    userMark,
    batchUserMark,
    importUserMark,
    selectSku,
    userMarkList,
  } = options

  const skuData = ref<InterskuList[]>([])

  const setCostPrice = (item: InterProductList) => {
    if (item.costPrice !== 0 && !item.costPrice) {
      ElMessage.warning('商品成本价为空，请完善商品成本价')
      return
    }
    const buyStored = item.buyStored ?? 0
    const costPrice = item.costPrice ?? 0
    const amount = new BigNumber(buyStored).multipliedBy(costPrice).toFixed(2)
    item.totalPrice = Number(amount)
  }

  const getUserMarkText = (
    customerId: number,
    mode: 'query' | 'create' = 'query',
  ): string | null => {
    const item = userMarkList.value.find((e) => e.userId === customerId)
    if (customerId === 0) {
      return mode === 'query' ? null : ''
    }
    return item?.userMark || null
  }

  const batchAddCommodity = async (
    sku: string,
    type: '1' | '2' | '3',
  ): Promise<InterskuList[]> => {
    if (!editForm.value.warehouseId) {
      ElMessage.error('请选择仓库')
      return []
    }
    try {
      let userValue: number = 0
      if (type === '1') {
        userValue = userMark.value
      } else if (type === '2') {
        userValue = batchUserMark.value
      } else if (type === '3') {
        userValue = importUserMark.value
      }
      const user = getUserMarkText(userValue, 'query')
      const res = await getBySkuAndUserMarkApi(editForm.value.warehouseId, sku, user)
      const arr: InterskuList[] = res.data || []
      const ids: Record<string, boolean> = {}
      for (const item of otherPurchaseData.value) {
        if (item.warehouseSku !== undefined) {
          ids[item.warehouseSku] = true
        }
      }
      return arr.filter((currentItem: InterskuList) => {
        return currentItem.sku === undefined || !ids[currentItem.sku]
      })
    } catch (e) {
      console.error(e)
      return []
    }
  }

  const selectbySku = async () => {
    if (!editForm.value.warehouseId) return ElMessage.error('请选择仓库')
    try {
      const user = getUserMarkText(userMark.value, 'query')
      const res = await getBySkuAndUserMarkApi(
        editForm.value.warehouseId,
        selectSku.value,
        user,
      )
      skuData.value = res.data || []
    } catch (e) {
      console.error(e)
    }
  }

  const skudblclick = (val: InterskuList) => {
    const {
      locationCode = '',
      costPrice = null,
      productNo = '',
      warehouseSku = '',
      productName = '',
      skuImage = '',
      locationId = null,
      currencyName = '',
      currencyCode = null,
    } = val || {}

    const lastItem =
      otherPurchaseData.value[otherPurchaseData.value.length - 1] || null
    if (lastItem && lastItem.currencyName) {
      if (!currencyName || currencyName !== lastItem.currencyName) {
        ElMessage.error('添加的商品币种需一致')
        return
      }
    }
    const item = userMarkList.value.find((e) => e.userId === userMark.value)
    otherPurchaseData.value = [
      ...JSON.parse(JSON.stringify(otherPurchaseData.value)),
      {
        skuImage,
        warehouseSku,
        customerId: userMark.value !== 0 ? userMark.value : null,
        customerName: userMark.value !== 0 ? item?.userName || '' : null,
        userMark: userMark.value !== 0 ? item?.userMark : null,
        skuName: productName,
        productNo,
        locationCode: locationCode ?? '',
        locationId: locationId ?? null,
        costPrice,
        buyStored: null,
        totalPrice: null,
        currencyName,
        currencyCode,
      },
    ]

    const skuSet = new Set(
      otherPurchaseData.value.map((item: InterProductList) => item.warehouseSku),
    )
    skuData.value = skuData.value.filter((item: InterskuList) => !skuSet.has(item.sku))
  }

  const filterSkuData = computed(() => {
    const skuList = otherPurchaseData.value.map((el) => el.warehouseSku)
    const item = userMarkList.value.find((u) => u.userId === userMark.value)
    return skuData.value
      .filter((el) => !skuList.includes(el.warehouseSku))
      .map((e) => {
        return {
          ...e,
          userMark: userMark.value === 0 ? '' : item?.userMark,
        }
      })
  })

  return {
    skuData,
    setCostPrice,
    batchAddCommodity,
    selectbySku,
    skudblclick,
    filterSkuData,
  }
}
