import React, { useMemo, useState, useEffect, useCallback } from 'react'
import styles from './index.module.scss'
import history from '@/utils/history'
import { MessageFu } from '@/utils/message'
import { authorityFu } from '@/utils/authority'
import TableList from '@/pages/Zother/TableList'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import { API_getGoodsList, API_download } from '@/store/action/Abench/A4proof'
import { baseURL } from '@/utils/http'
import { baseFormData } from '@/pages/Zother/data'
import { voucherCenterTableC } from '@/utils/tableData'
import { Button, message } from 'antd'
import tabLeftArr from '@/pages/Layout/data'
import { downloadFileByUrl } from '@/utils'

function A4proof() {
  const tableInfo = useSelector((state: RootState) => state.A4proof.tableInfo)
  const [list, setList] = useState<any[]>([])
  // 跨页参数
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])

  // 跨页多选
  const rowSelection = useMemo(
    () => ({
      selectedRowKeys,
      // 这里不直接用 onChange 的 keys 覆盖，避免翻页时丢失其他页勾选
      onChange: () => {},
      // 单行勾选/取消
      onSelect: (record: any, selected: boolean) => {
        const id = record.id as React.Key
        setSelectedRowKeys(prev => {
          if (selected) {
            if (prev.includes(id)) return prev
            return [...prev, id]
          } else {
            return prev.filter(k => k !== id)
          }
        })
      },
      // 全选/全不选当前页
      onSelectAll: (selected: boolean, _selectedRows: any[], changeRows: any[]) => {
        const changeIds = changeRows.map(r => r.id as React.Key)
        setSelectedRowKeys(prev => {
          if (selected) {
            const set = new Set<React.Key>(prev)
            changeIds.forEach(id => set.add(id))
            return Array.from(set)
          } else {
            return prev.filter(k => !changeIds.includes(k))
          }
        })
      },
      preserveSelectedRowKeys: true
    }),
    [selectedRowKeys]
  )

  // 下载方法
  const downloadFn = async (ids: number | number[]) => {
    const idArr = Array.isArray(ids) ? ids : [ids]
    if (!idArr.length) return

    const res: any = await API_download(idArr)
    if (res && res.code === 0 && res.data) {
      const path = res.data as string
      const fullUrl = path.startsWith('http') ? path : `${baseURL}${path}`
      window.open(fullUrl)
    }
  }
  // 已知路径，单独下载 改为使用downloadFileByUrl
  // const downloadSingleFn = (path: string, fileName: string) => {
  //   const downloadUrl = `${baseURL}${path}`
  //   const link = document.createElement('a')
  //   link.href = downloadUrl
  //   link.download = fileName
  //   document.body.appendChild(link)
  //   link.click()
  //   document.body.removeChild(link)
  // }
  // 申请类型
  useEffect(() => {
    const arr: any[] = []
    tabLeftArr.forEach(v1 => {
      v1.son.forEach(v2 => {
        if (v2.pageType) arr.push({ path: v2.path, value: v2.pageType, label: v2.name, id: v2.id })
      })
    })

    setList(arr)
  }, [])

  // 点击各种操作按钮
  const tableBtnFu = useCallback((id: number, key: string) => {
    history.push(`/proof_edit/${key}/${id}`)
  }, [])

  const staBtn = useMemo(() => {
    return [
      {
        title: '业务类型',
        render: (item: any) => {
          let txt = '（空）'
          console.log('--------', item.moduleName)

          const obj = list.find(v => v.value === item.moduleName)
          if (obj) txt = obj.label
          return txt
        }
      }
    ]
  }, [list])

  const A4topSearch = useMemo(
    () => [
      {
        type: 'input',
        key: 'searchKey',
        placeholder: `请输入凭证名称或业务编号`
      },
      {
        type: 'select',
        key: 'moduleName',
        placeholder: '业务类型',
        options: list
      }
    ],
    [list]
  )

  // 故事管理/藏品总账定制右侧内容
  const storyTableListToprr = ({
    clickSearch,
    resetSelectFu
  }: {
    clickSearch: () => void
    resetSelectFu: () => void
  }) => {
    return (
      <>
        <Button
          type='primary'
          onClick={() => {
            const ids = selectedRowKeys.map(key => Number(key)).filter(id => !Number.isNaN(id))
            if (ids.length === 0) {
              message.warning('请先选择要下载的凭证')
              return
            }

            downloadFn(ids)
          }}
        >
          批量下载
        </Button>
        <Button type='primary' onClick={clickSearch}>
          查询
        </Button>
        <Button onClick={resetSelectFu}>重置</Button>
      </>
    )
  }

  // 故事管理/藏品总账定制右侧操作按钮
  const storyTableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => (
          <>
            <Button size='small' type='text' onClick={() => tableBtnFu(item.moduleId, '4')}>
              查看
            </Button>
            <Button
              size='small'
              type='text'
              onClick={() => downloadFileByUrl(item.filePath, item.fileName)}
            >
              下载
            </Button>
          </>
        )
      }
    ]
  }, [tableBtnFu])

  return (
    <div className={styles.A4proof}>
      <div className='pageTitle'>凭证中心</div>

      <TableList
        baseFormData={baseFormData}
        getListAPI={API_getGoodsList}
        pageKey='proof'
        tableInfo={tableInfo}
        columnsTemp={voucherCenterTableC}
        rightBtnWidth={240}
        leftRowWidth={'20%'}
        yHeight={592}
        staBtn={staBtn}
        searchDom={A4topSearch}
        storyTableListToprr={storyTableListToprr}
        storyTableLastBtn={storyTableLastBtn}
        rowSelection={rowSelection}
      />
    </div>
  )
}

const MemoA4proof = React.memo(A4proof)

export default MemoA4proof
