import { Button, Dropdown, MenuProps } from 'antd'
import { EXPORT_TEMPLATE_MAP, EXPORT_WORD_ENUM, exportWordHandler } from './exportTemplates'
import { API_getGoodsStorage } from '@/store/action/C1ledger'

const items: MenuProps['items'] = []
const templateKeys = Object.keys(EXPORT_TEMPLATE_MAP).map(i => Number(i)) as EXPORT_WORD_ENUM[]
for (let i = 0; i < templateKeys.length; i++) {
  const key = templateKeys[i]
  items.push({
    key,
    label: <span className='Y2xia'>{EXPORT_TEMPLATE_MAP[key].fileName}</span>
  })
}

/**
 * 导出按钮
 * @param data 数据
 * @param keys 模板keys
 */
export const EXbtnFu = (data?: any, keys = templateKeys) => {
  const menus = items.filter(i => keys.includes(i?.key as EXPORT_WORD_ENUM))

  const handleExport: ({ key }: { key: unknown }) => Promise<void> = async ({ key }) => {
    const k = Number(key) as EXPORT_WORD_ENUM

    // 单独处理流水账数据
    if (k === EXPORT_WORD_ENUM.COLLECTION_LOG) {
      const res = await API_getGoodsStorage()
      return exportWordHandler(k, { collects: res.data })
    }

    return exportWordHandler(k, data)
  }

  return menus.length > 1 ? (
    <Dropdown menu={{ items: menus, onClick: handleExport }} placement='top' arrow>
      <Button type='primary'>导出</Button>
    </Dropdown>
  ) : (
    <Button type='primary' onClick={handleExport.bind(undefined, { key: menus[0]?.key })}>
      导出
    </Button>
  )
}
