// src/composables/usePurchase.js
import { ref, computed, h } from 'vue'
import { useRouter } from 'vue-router'
import uniq from 'lodash/uniq'
import { multiplied, plus } from '@/utils/bignumber'
import { Modal, message } from 'ant-design-vue'
import { ExclamationCircleFilled } from '@ant-design/icons-vue'

import {
  apiPurchase,
  saveGoodsDelistRecord,
  checkGoodsDelistRecord
} from '@/api/transaction'

export function usePurchase(prodListRef, selectedRowKeysRef) {
  const router = useRouter()

  const selectAll = ref(false)
  const mVisible  = ref(false)

  const selectedGoods = computed(() => selectedRowKeysRef.value.length)

  const selectedGoodsAmount = computed(() => {
    const list = prodListRef.value.filter(p => selectedRowKeysRef.value.includes(p.id))
    if (!list.length) return 0

    const strategies = {
      1: (sum, cur) => plus(sum, multiplied(cur.salePrice, cur.purchaseQuantity || 0)),
      2: (sum, cur) => {
        const qty = cur.purchaseQuantity || 0
        const tier = cur.wholesalePrices.find(item =>
          qty >= item.quantityMin && (!item.quantityMax || qty <= item.quantityMax)
        )
        return plus(sum, multiplied(tier?.price || 0, qty))
      }
    }
    return list.reduce((s, c) => strategies[c.priceType](s, c), 0)
  })

  function onSelectChange(item, checked) {
    const idx = selectedRowKeysRef.value.indexOf(item.id)
    if (checked && idx === -1) selectedRowKeysRef.value.push(item.id)
    if (!checked && idx > -1) selectedRowKeysRef.value.splice(idx, 1)
  }

  function clearSelectedRowKeys() {
    selectedRowKeysRef.value = []
  }

  function handleSelectAll(checked) {
    if (!checked) {
      selectAll.value = false
      return clearSelectedRowKeys()
    }
    const avail = prodListRef.value.filter(p => !p.purchaseDisabled)
    const bad = avail.filter(p => !p.purchaseQuantity)
    if (bad.length) {
      bad.forEach(p => { p.purchaseQuantityValid = false })
      return message.error('请输入采购数量')
    }
    selectAll.value = true
    const ids = avail.map(p => p.id)
    selectedRowKeysRef.value = uniq([...selectedRowKeysRef.value, ...ids])
  }

  function handlePurchaseQuantityInput(id, val) {
    const prod = prodListRef.value.find(p => p.id === id)
    if (prod) prod.purchaseQuantity = val
  }

  function beforeCreateValid(goods) {
    let ok = true
    goods.forEach(p => {
      if (!p.purchaseQuantity) {
        p.purchaseQuantityValid = false
        ok = false
      }
    })
    return ok ? '' : '请输入采购数量'
  }

  function getConfirmPurchase(goods) {
    Modal.confirm({
      title: '确认摘牌？',
      content: '点击确认摘牌后，系统将创建购销合同',
      icon: () => h(ExclamationCircleFilled),
      okText: '确认摘牌',
      cancelText: '再想想',
      async onOk() {
        const payload = {
          bizType: 0,
          goodsList: goods.map(p => ({ goodsId: p.id, delistedQuantity: p.purchaseQuantity }))
        }
        const { code, msg, data: contractId } = await apiPurchase(payload)
        if (+code !== 0) message.error(msg)
        else goToTcmSaleContract(contractId)
      }
    })
  }

  async function setApiPurchase(goods) {
    const payload = {
      bizType: 0,
      goodsList: goods.map(p => ({ goodsId: p.id, delistedQuantity: p.purchaseQuantity }))
    }
    const { code, msg, data: contractId } = await apiPurchase(payload)
    if (+code !== 0) message.error(msg)
    else goToTcmSaleContract(contractId)
  }

  async function doSaveGoodsDelist(goods) {
    const params = {
      goodsId: goods[0]?.id || '',
      goodsTitle: goods[0]?.goodsTitle || '',
      orgDelistedQuantity: goods[0]?.purchaseQuantity || '',
      orgName: localStorage.getItem('orgName') || ''
    }
    await saveGoodsDelistRecord(params)
  }

  async function doCheckGoodsDelist(goods) {
    const params = {
      bizType: 0,
      goodsList: goods.map(p => ({ goodsId: p.id, delistedQuantity: p.purchaseQuantity }))
    }
    const res = await checkGoodsDelistRecord(params)
    if (res.code === 0) mVisible.value = true
    else message.error(res.msg)
  }

  function handelPurchase(typeName) {
    if (!selectedRowKeysRef.value.length) return message.error('请选择摘牌产品')
    const goods = prodListRef.value.filter(p => selectedRowKeysRef.value.includes(p.id))
    const err = beforeCreateValid(goods)
    if (err) return message.error(err)

    const bao = goods.filter(p => p.isBaoGong)
    if (typeName === 'goodsDelist') {
      doSaveGoodsDelist(bao)
      setApiPurchase(goods)
      return
    }
    if (bao.length === 1) doCheckGoodsDelist(bao)
    else if (bao.length > 1) message.error('不可同时摘牌多个保供产品，请重新选择')
    else getConfirmPurchase(goods)
  }

  function handleCancel() {
    mVisible.value = false
  }

  function goToTcmSaleContract(id) {
    Modal.confirm({
      title: '已创建购销合同，请前往编辑买家信息',
      content: '与挂牌方确认交易信息后可以进行线上签订，双方签订完成后即可下单交易。',
      icon: () => h(ExclamationCircleFilled),
      okText: '立即编辑',
      cancelText: '稍后编辑',
      onOk() {
        if (id) router.push({ path: '/buyer/tcm-sale-contract/contract-edit', query: { id, isEdit: true } })
        else router.push({ path: 'buyer/tcm-sale-contract/index', query: { activeTab: 0 } })
      },
      onCancel() {
        Modal.confirm({
          class: 'daodi-mall__text--bold',
          content: '您可前往【我的工作台】-【合同管理】-【采购合同】起草中列表中，进行编辑。',
          icon: () => h(ExclamationCircleFilled),
          okText: '我知道了'
        })
      }
    })
  }

  return {
    selectAll,
    mVisible,
    selectedGoods,
    selectedGoodsAmount,
    handelPurchase,
    onSelectChange,
    clearSelectedRowKeys,
    handleSelectAll,
    handlePurchaseQuantityInput,
    handleCancel
  }
}
这是抽出来的方法，一会我发主页面你帮我集成进去